Pay.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. namespace app\api\controller;
  3. use think\Db;
  4. use think\Log;
  5. use think\Exception;
  6. use think\exception\HttpResponseException;
  7. use app\common\Service\Pay\PayService;
  8. use app\common\Service\Pay\PayOperService;
  9. use app\common\Enum\ChannelEnum;
  10. use app\common\Service\OrderService;
  11. use app\common\model\Third as ThirdOauth;
  12. use app\common\model\Order;
  13. /**
  14. * 支付接口
  15. */
  16. class Pay extends Base
  17. {
  18. protected $noNeedLogin = ['notify'];
  19. protected $noNeedRight = '*';
  20. public function _initialize()
  21. {
  22. parent::_initialize();
  23. set_addon_config('epay', ['version'=>'v3'], false);
  24. }
  25. /**
  26. *
  27. * 支付回调
  28. * @return void
  29. */
  30. public function notify()
  31. {
  32. $type = $this->request->param('type');
  33. $paytype = $this->request->param('paytype');
  34. if ($type == 'notify') {
  35. $pay = \addons\epay\library\Service::checkNotify($paytype);
  36. if (!$pay) {
  37. echo '签名错误';
  38. \think\Log::write('签名错误', 'epay',);
  39. return;
  40. }
  41. $data = $pay->verify();
  42. // try {
  43. $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
  44. PayOperService::settle($data['out_trade_no'], $payamount, $paytype == 'alipay' ? $data['trade_no'] : $data['transaction_id']);
  45. // } catch (\Exception $e) {
  46. // \think\Log::write($e->getMessage(), 'epay');
  47. // }
  48. echo $pay->success();
  49. }// pc 支付
  50. elseif ($type == 'return') {
  51. // $order_sn = $this->request->param('order_sn');
  52. // $this->redirect("index/shop.order/detail", ['orderid' => $order_sn]);
  53. }
  54. return;
  55. }
  56. /**
  57. * 预支付订单接口
  58. * @return void
  59. */
  60. public function prepay()
  61. {
  62. $orderId = $this->request->post('orderId');
  63. $payment = $this->request->post('payment');
  64. $openid = $this->request->post('openid', '');
  65. $money = $this->request->post('money', 0);
  66. $money = $money > 0 ? $money : 0;
  67. $platform = $this->request->header('platform');
  68. $userId = $this->auth->getUser()->id;
  69. // 获取订单实例
  70. $order = new Order();
  71. $order = $order->where('user_id', $userId)->where('id', $orderId)->find();
  72. if (!$order) {
  73. $this->error(__('No Results were found'));
  74. }
  75. // 验证订单状态
  76. if (!$order->canPayHandle()) {
  77. $this->error(__('订单状态不支持支付'));
  78. }
  79. // 验证支付类型
  80. if (!$payment || !in_array($payment, ['wechat', 'alipay', 'douyin'])) {
  81. $this->error('支付类型不能为空');
  82. }
  83. // 验证支付环境
  84. // if ($channel && !ChannelEnum::channelSupportsPayment($channel, $payment)) {
  85. // $this->error('当前渠道不支持该支付方式');
  86. // }
  87. $payOper = new PayOperService($this->auth->getUser());
  88. $orderType = $order->type;
  89. $payModel = $payOper->{$payment}($order, $order->amount, $orderType);
  90. $order->save(['pay_type' =>$payment]);
  91. $order_data = [
  92. 'order_id' => $order->id,
  93. 'out_trade_no' => $payModel->pay_sn,
  94. 'total_amount' => $payModel->pay_fee, // 剩余支付金额
  95. ];
  96. // 微信公众号,小程序支付,必须有 openid
  97. if ($payment == 'wechat' || $payment == 'douyin' ) {
  98. if (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram','DouyinMiniProgram'])) {
  99. if (isset($openid) && $openid) {
  100. // 如果传的有 openid
  101. $order_data['payer']['openid'] = $openid;
  102. } else {
  103. // 没有 openid 默认拿下单人的 openid
  104. $oauth = ThirdOauth::where([
  105. 'user_id' => $order->user_id,
  106. 'platform' => $payment,
  107. 'apptype' => lcfirst(str_replace($payment, '', $platform))
  108. ])->find();
  109. $order_data['payer']['openid'] = $oauth ? $oauth->openid : '';
  110. }
  111. if (empty($order_data['payer']['openid'])) {
  112. // 缺少 openid
  113. $this->error('miss_openid', -1);
  114. }
  115. }
  116. $order_data['description'] = '商城订单支付';
  117. } else {
  118. $order_data['subject'] = '商城订单支付';
  119. }
  120. if($platform == ChannelEnum::CHANNEL_DOUYIN_MINI_PROGRAM){
  121. $order_data['out_order_no'] = $payModel->pay_sn;
  122. }
  123. // echo "<pre>";
  124. // print_r(lcfirst(str_replace($payment, '', $platform)));
  125. // echo "</pre>";die();
  126. try {
  127. $payService = new PayService($payment, $platform);
  128. $result = $payService->pay($order_data);
  129. } catch (\Yansongda\Pay\Exception\Exception $e) {
  130. $this->error('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  131. } catch (HttpResponseException $e) {
  132. $data = $e->getResponse()->getData();
  133. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  134. $this->error('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  135. } catch (\Exception $e) {
  136. // 捕获构造函数错误和其他异常
  137. $errorMessage = $e->getMessage();
  138. Log::error('PayService创建失败: ' . $errorMessage);
  139. $this->error('支付服务初始化失败' . (config('app_debug') ? ":" . $errorMessage : ',请重试'));
  140. }
  141. $this->success('', [
  142. 'pay_data' => $result,
  143. ]);
  144. }
  145. /**
  146. * 处理余额混合支付
  147. * @param PayOperService $payOper
  148. * @param mixed $order
  149. * @param string $order_type
  150. * @param float $money
  151. * @return mixed
  152. */
  153. protected function handleBalanceMixedPayment($payOper, $order, $order_type, $money)
  154. {
  155. return Db::transaction(function () use ($payOper, $order, $order_type, $money) {
  156. // 加锁读订单
  157. $order = $order->lock(true)->find($order->id);
  158. // 余额支付
  159. $order = $payOper->money($order, $money, $order_type);
  160. return $order;
  161. });
  162. }
  163. /**
  164. * 处理纯余额支付
  165. * @param PayOperService $payOper
  166. * @param mixed $order
  167. * @param string $order_type
  168. * @return mixed
  169. * @throws Exception
  170. */
  171. protected function handleBalancePayment($payOper, $order, $order_type)
  172. {
  173. $order = Db::transaction(function () use ($payOper, $order, $order_type) {
  174. // 加锁读订单
  175. $order = $order->lock(true)->find($order->id);
  176. $order = $payOper->money($order, $order->remain_pay_fee, $order_type);
  177. return $order;
  178. });
  179. if ($order->status != $order::STATUS_PAID) {
  180. throw new Exception('订单支付失败');
  181. }
  182. return $order;
  183. }
  184. /**
  185. * 处理货到付款
  186. * @param PayOperService $payOper
  187. * @param mixed $order
  188. * @param string $order_type
  189. * @return mixed
  190. * @throws Exception
  191. */
  192. protected function handleOfflinePayment($payOper, $order, $order_type)
  193. {
  194. if (!isset($order->ext['offline_status']) || $order->ext['offline_status'] != 'enable') {
  195. throw new Exception('订单不支持货到付款');
  196. }
  197. return Db::transaction(function () use ($payOper, $order, $order_type) {
  198. // 加锁读订单
  199. $order = $order->lock(true)->find($order->id);
  200. $order = $payOper->offline($order, 0, $order_type); // 增加 0 记录
  201. return $order;
  202. });
  203. }
  204. /**
  205. * 处理第三方支付(微信、支付宝)
  206. * @param PayOperService $payOper
  207. * @param mixed $order
  208. * @param string $order_type
  209. * @param string $payment
  210. * @param string $platform
  211. * @param string $channel
  212. * @param string $openid
  213. * @return mixed
  214. * @throws Exception
  215. */
  216. protected function handleThirdPartyPayment($payModel, $order, $payment, $platform, $openid)
  217. {
  218. $order_data = [
  219. 'order_id' => $order->id,
  220. 'out_trade_no' => $payModel->pay_sn,
  221. 'total_amount' => $payModel->pay_fee, // 剩余支付金额
  222. ];
  223. // 微信支付需要 openid
  224. if ($payment == 'wechat') {
  225. $this->handleWechatPaymentData($order_data, $platform, $openid, $order);
  226. $order_data['description'] = '商城订单支付';
  227. } else {
  228. $order_data['subject'] = '商城订单支付';
  229. }
  230. // 创建支付服务
  231. $payService = new PayService($payment, $platform);
  232. try {
  233. $result = $payService->pay($order_data);
  234. } catch (\Yansongda\Pay\Exception\Exception $e) {
  235. throw new Exception('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  236. } catch (HttpResponseException $e) {
  237. $data = $e->getResponse()->getData();
  238. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  239. throw new Exception('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  240. }
  241. // APP 平台特殊处理
  242. if ($platform == 'App') {
  243. if ($payment == 'wechat') {
  244. // Yansongda\Supports\Collection,可当数组,可当字符串,这里不用处理
  245. } else {
  246. // Guzzle
  247. $result = $result->getBody()->getContents();
  248. }
  249. }
  250. return $result;
  251. }
  252. /**
  253. * 处理微信支付数据
  254. * @param array &$order_data
  255. * @param string $platform
  256. * @param string $openid
  257. * @param mixed $order
  258. * @throws Exception
  259. */
  260. protected function handleWechatPaymentData(&$order_data, $platform, $openid, $order)
  261. {
  262. // 微信公众号,小程序支付,必须有 openid
  263. if (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  264. if (isset($openid) && $openid) {
  265. // 如果传的有 openid
  266. $order_data['payer']['openid'] = $openid;
  267. } else {
  268. // 没有 openid 默认拿下单人的 openid
  269. // 需要根据实际的第三方授权模型调整
  270. try {
  271. $oauthModel = '\\app\\common\\model\\Third';
  272. if (class_exists($oauthModel)) {
  273. $oauth = $oauthModel::where([
  274. 'user_id' => $order->user_id,
  275. 'platform' => 'wechat',
  276. 'apptype' => lcfirst(str_replace('wechat', '', $platform))
  277. ])->find();
  278. $order_data['payer']['openid'] = $oauth ? $oauth->openid : '';
  279. } else {
  280. $order_data['payer']['openid'] = '';
  281. }
  282. } catch (\Exception $e) {
  283. $order_data['payer']['openid'] = '';
  284. }
  285. }
  286. if (empty($order_data['payer']['openid'])) {
  287. // 缺少 openid
  288. throw new Exception('miss_openid', -1);
  289. }
  290. }
  291. }
  292. }