Pay.php 13 KB

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