Pay.php 12 KB

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