Pay.php 13 KB

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