Pay.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. namespace addons\shopro\controller;
  3. use Psr\Http\Message\ResponseInterface;
  4. use think\exception\HttpResponseException;
  5. use app\admin\model\shopro\Pay as PayModel;
  6. use addons\shopro\service\pay\PayOper;
  7. use addons\shopro\library\pay\PayService;
  8. use app\admin\model\shopro\order\Order;
  9. use app\admin\model\shopro\trade\Order as TradeOrderModel;
  10. use think\Log;
  11. use think\Db;
  12. use addons\shopro\service\pay\PayRefund;
  13. use Yansongda\Pay\Pay as YansongdaPay;
  14. use addons\epay\library\Service;
  15. class Pay extends Common
  16. {
  17. protected $noNeedLogin = ['alipay', 'notify', 'notifyRefund'];
  18. protected $noNeedRight = ['*'];
  19. public function prepay()
  20. {
  21. $this->repeatFilter(); // 防止连点
  22. check_env(['yansongda']);
  23. $user = auth_user();
  24. $order_sn = $this->request->post('order_sn');
  25. $payment = $this->request->post('payment');
  26. $openid = $this->request->post('openid', '');
  27. $money = $this->request->post('money', 0);
  28. $money = $money > 0 ? $money : 0;
  29. $platform = $this->request->post('platform');
  30. list($order, $order_type) = $this->getOrderInstance($order_sn);
  31. $order = $order->where('user_id', $user->id)->where('order_sn', $order_sn)->find();
  32. if (!$order) {
  33. $this->error(__('No Results were found'));
  34. }
  35. if (in_array($order->status, [$order::STATUS_CLOSED, $order::STATUS_CANCEL])) {
  36. $this->error('订单已失效');
  37. }
  38. if (in_array($order->status, [$order::STATUS_PAID, $order::STATUS_COMPLETED])) {
  39. $this->error('订单已支付');
  40. }
  41. if ($order_type == 'order' && $order->isOffline($order)) {
  42. // 已经货到付款
  43. $this->error('已下单成功');
  44. }
  45. if (!$payment || !in_array($payment, ['wechat', 'alipay', 'money', 'offline'])) {
  46. $this->error('支付类型不能为空');
  47. }
  48. // pay 实例
  49. $payOper = new PayOper();
  50. if ($money && $order_type == 'order') {
  51. // 余额混合支付
  52. $order = Db::transaction(function () use ($payOper, $order, $order_type, $money) {
  53. // 加锁读订单
  54. $order = $order->lock(true)->find($order->id);
  55. // 余额支付
  56. $order = $payOper->money($order, $money, $order_type);
  57. return $order;
  58. });
  59. if (in_array($order->status, [$order::STATUS_PAID, $order::STATUS_COMPLETED])) {
  60. $this->success('订单支付成功', $order);
  61. }
  62. }
  63. if ($payment == 'money' && $order_type == 'order') {
  64. // 余额支付
  65. $order = Db::transaction(function () use ($payOper, $order, $order_type) {
  66. // 加锁读订单
  67. $order = $order->lock(true)->find($order->id);
  68. $order = $payOper->money($order, $order->remain_pay_fee, $order_type);
  69. return $order;
  70. });
  71. if ($order->status != $order::STATUS_PAID) {
  72. $this->error('订单支付失败');
  73. }
  74. $this->success('订单支付成功', $order);
  75. }
  76. if ($payment == 'offline' && $order_type == 'order') {
  77. if (!isset($order->ext['offline_status']) || $order->ext['offline_status'] != 'enable') {
  78. $this->error('订单不支持货到付款');
  79. }
  80. // 货到付款
  81. $order = Db::transaction(function () use ($payOper, $order, $order_type) {
  82. // 加锁读订单
  83. $order = $order->lock(true)->find($order->id);
  84. $order = $payOper->offline($order, 0, $order_type); // 增加 0 记录
  85. return $order;
  86. });
  87. if ($order->status != $order::STATUS_PAID) {
  88. $this->success('下单成功', $order); // 货到付款
  89. }
  90. $this->success('订单支付成功', $order);
  91. }
  92. // 微信支付宝(第三方)付款
  93. $payModel = $payOper->{$payment}($order, $order->remain_pay_fee, $order_type);
  94. $order_data = [
  95. 'order_id' => $order->id,
  96. 'out_trade_no' => $payModel->pay_sn,
  97. 'total_amount' => $payModel->pay_fee, // 剩余支付金额
  98. ];
  99. // 微信公众号,小程序支付,必须有 openid
  100. if ($payment == 'wechat') {
  101. if (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  102. if (isset($openid) && $openid) {
  103. // 如果传的有 openid
  104. $order_data['payer']['openid'] = $openid;
  105. } else {
  106. // 没有 openid 默认拿下单人的 openid
  107. $oauth = \app\admin\model\shopro\ThirdOauth::where([
  108. 'user_id' => $order->user_id,
  109. 'provider' => 'Wechat',
  110. 'platform' => lcfirst(str_replace('Wechat', '', $platform))
  111. ])->find();
  112. $order_data['payer']['openid'] = $oauth ? $oauth->openid : '';
  113. }
  114. if (empty($order_data['payer']['openid'])) {
  115. // 缺少 openid
  116. $this->error('miss_openid', -1);
  117. }
  118. }
  119. $order_data['description'] = '商城订单支付';
  120. } else {
  121. $order_data['subject'] = '商城订单支付';
  122. }
  123. //下单
  124. $params = [
  125. 'type' => $payment,
  126. 'orderid' => $payModel->pay_sn,
  127. 'title' => '商城订单支付',
  128. 'amount' => $payModel->pay_fee,
  129. 'method' => strtolower($platform),
  130. // 'openid' => $openid,
  131. 'notifyurl' => config('pay_notify_url').'/api/notify/recharge_notify_base/paytype/'.$payment,
  132. 'returnurl' => '',
  133. ];
  134. $res = Service::submitOrder($params);
  135. if($payment == 'wechat'){
  136. $this->success('success',json_decode($res,true));
  137. }else{
  138. $this->success('success',$res);
  139. }
  140. //原带支付
  141. $payService = new PayService($payment,$platform);
  142. try {
  143. $result = $payService->pay($order_data);
  144. } catch (\Yansongda\Pay\Exception\Exception $e) {
  145. $this->error('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  146. } catch (HttpResponseException $e) {
  147. $data = $e->getResponse()->getData();
  148. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  149. $this->error('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  150. }
  151. if ($platform == 'App') {
  152. if ($payment == 'wechat') {
  153. // Yansongda\Supports\Collection,可当数组,可当字符串,这里不用处理
  154. } else {
  155. // Guzzle
  156. $result = $result->getBody()->getContents();
  157. }
  158. }
  159. $this->success('', [
  160. 'pay_data' => $result,
  161. ]);
  162. }
  163. /**
  164. * 支付宝网页支付
  165. */
  166. public function alipay()
  167. {
  168. $pay_sn = $this->request->get('pay_sn');
  169. $platform = $this->request->get('platform');
  170. $payModel = PayModel::where('pay_sn', $pay_sn)->find();
  171. if (!$payModel || $payModel->status != PayModel::PAY_STATUS_UNPAID) {
  172. $this->error("支付单不存在或已支付");
  173. }
  174. try {
  175. $order_data = [
  176. 'order_id' => $payModel->order_id,
  177. 'out_trade_no' => $payModel->pay_sn,
  178. 'total_amount' => $payModel->pay_fee,
  179. 'subject' => '商城订单支付',
  180. ];
  181. $payService = new PayService('alipay', $platform);
  182. $result = $payService->pay($order_data, [], 'url');
  183. $result = $result->getBody()->getContents();
  184. echo $result;
  185. } catch (\Exception $e) {
  186. echo $e->getMessage();
  187. } catch (HttpResponseException $e) {
  188. $data = $e->getResponse()->getData();
  189. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  190. echo '支付失败' . (config('app_debug') ? ":" . $message : ',请重试');
  191. }
  192. }
  193. /**
  194. * 支付成功回调
  195. */
  196. public function notify()
  197. {
  198. Log::write('pay-notify-comein:');
  199. $payment = $this->request->param('payment');
  200. $platform = $this->request->param('platform');
  201. $payService = new PayService($payment, $platform);
  202. $result = $payService->notify(function ($data, $originData = []) use ($payment) {
  203. Log::write('pay-notify-data:' . json_encode($data));
  204. $out_trade_no = $data['out_trade_no'];
  205. // 查询 pay 交易记录
  206. $payModel = PayModel::where('pay_sn', $out_trade_no)->find();
  207. if (!$payModel || $payModel->status != PayModel::PAY_STATUS_UNPAID) {
  208. // 订单不存在,或者订单已支付
  209. return YansongdaPay::$payment()->success();
  210. }
  211. Db::transaction(function () use ($payModel, $data, $originData, $payment) {
  212. $notify = [
  213. 'pay_sn' => $data['out_trade_no'],
  214. 'transaction_id' => $data['transaction_id'],
  215. 'notify_time' => $data['notify_time'],
  216. 'buyer_info' => $data['buyer_info'],
  217. 'payment_json' => $originData ? json_encode($originData) : json_encode($data),
  218. 'pay_fee' => $data['pay_fee'], // 微信的已经*100处理过了
  219. 'pay_type' => $payment // 支付方式
  220. ];
  221. // pay 实例
  222. $payOper = new PayOper($payModel->user_id);
  223. $payOper->notify($payModel, $notify);
  224. });
  225. return YansongdaPay::$payment()->success();
  226. });
  227. return $this->payResponse($result, $payment);
  228. }
  229. /**
  230. * 微信退款回调 (仅微信用,支付宝走支付回调 notify 方法)
  231. *
  232. * @return void
  233. */
  234. public function notifyRefund()
  235. {
  236. Log::write('pay-notify-refund-comein:');
  237. $payment = $this->request->param('payment');
  238. $platform = $this->request->param('platform');
  239. $payService = new PayService($payment, $platform);
  240. $result = $payService->notifyRefund(function ($data, $originData) use ($payment, $platform) {
  241. Log::write('pay-notify-refund-result:' . json_encode($data));
  242. Db::transaction(function () use ($data, $originData, $payment) {
  243. $out_refund_no = $data['out_refund_no'];
  244. $out_trade_no = $data['out_trade_no'];
  245. // 交给退款实例处理
  246. $refund = new PayRefund();
  247. $refund->notify([
  248. 'out_trade_no' => $out_trade_no,
  249. 'out_refund_no' => $out_refund_no,
  250. 'payment_json' => json_encode($originData),
  251. ]);
  252. });
  253. return YansongdaPay::$payment()->success();
  254. });
  255. return $this->payResponse($result, $payment);
  256. }
  257. /**
  258. * 处理返回结果 tp5 不能直接 return YansongdaPay::$payment()->success()
  259. *
  260. * @param object|string $result
  261. * @param string|null $payment
  262. * @return void
  263. */
  264. private function payResponse($result = null, $payment = null)
  265. {
  266. if ($result instanceof ResponseInterface) {
  267. $content = $result->getBody()->getContents();
  268. $content = $payment == 'wechat' ? json_decode($content, true) : $content;
  269. return response($content, 200, [], ($payment == 'wechat' ? 'json' : ''));
  270. }
  271. return $result;
  272. }
  273. /**
  274. * 根据订单号获取订单实例
  275. *
  276. * @param [type] $order_sn
  277. * @return void
  278. */
  279. private function getOrderInstance($order_sn)
  280. {
  281. if (strpos($order_sn, 'TO') === 0) {
  282. // 交易订单
  283. $order_type = 'trade_order';
  284. $order = new TradeOrderModel();
  285. } else {
  286. // 订单
  287. $order_type = 'order';
  288. $order = new Order();
  289. }
  290. return [$order, $order_type];
  291. }
  292. }