Pay.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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' ? '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. // echo "<pre>";
  149. // print_r(lcfirst(str_replace($payment, '', $platform)));
  150. // echo "</pre>";die();
  151. try {
  152. $payService = new PayService($payment, $platform);
  153. $result = $payService->pay($order_data);
  154. } catch (\Yansongda\Pay\Exception\Exception $e) {
  155. $this->error('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  156. } catch (HttpResponseException $e) {
  157. $data = $e->getResponse()->getData();
  158. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  159. $this->error('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  160. } catch (\Exception $e) {
  161. // 捕获构造函数错误和其他异常
  162. $errorMessage = $e->getMessage();
  163. Log::error('PayService创建失败: ' . $errorMessage);
  164. $this->error('支付服务初始化失败' . (config('app_debug') ? ":" . $errorMessage : ',请重试'));
  165. }
  166. $this->success('', [
  167. 'pay_data' => $result,
  168. ]);
  169. }
  170. /**
  171. * 处理余额混合支付
  172. * @param PayOperService $payOper
  173. * @param mixed $order
  174. * @param string $order_type
  175. * @param float $money
  176. * @return mixed
  177. */
  178. protected function handleBalanceMixedPayment($payOper, $order, $order_type, $money)
  179. {
  180. return Db::transaction(function () use ($payOper, $order, $order_type, $money) {
  181. // 加锁读订单
  182. $order = $order->lock(true)->find($order->id);
  183. // 余额支付
  184. $order = $payOper->money($order, $money, $order_type);
  185. return $order;
  186. });
  187. }
  188. /**
  189. * 处理纯余额支付
  190. * @param PayOperService $payOper
  191. * @param mixed $order
  192. * @param string $order_type
  193. * @return mixed
  194. * @throws Exception
  195. */
  196. protected function handleBalancePayment($payOper, $order, $order_type)
  197. {
  198. $order = Db::transaction(function () use ($payOper, $order, $order_type) {
  199. // 加锁读订单
  200. $order = $order->lock(true)->find($order->id);
  201. $order = $payOper->money($order, $order->remain_pay_fee, $order_type);
  202. return $order;
  203. });
  204. if ($order->status != $order::STATUS_PAID) {
  205. throw new Exception('订单支付失败');
  206. }
  207. return $order;
  208. }
  209. /**
  210. * 处理货到付款
  211. * @param PayOperService $payOper
  212. * @param mixed $order
  213. * @param string $order_type
  214. * @return mixed
  215. * @throws Exception
  216. */
  217. protected function handleOfflinePayment($payOper, $order, $order_type)
  218. {
  219. if (!isset($order->ext['offline_status']) || $order->ext['offline_status'] != 'enable') {
  220. throw new Exception('订单不支持货到付款');
  221. }
  222. return Db::transaction(function () use ($payOper, $order, $order_type) {
  223. // 加锁读订单
  224. $order = $order->lock(true)->find($order->id);
  225. $order = $payOper->offline($order, 0, $order_type); // 增加 0 记录
  226. return $order;
  227. });
  228. }
  229. /**
  230. * 处理第三方支付(微信、支付宝)
  231. * @param PayOperService $payOper
  232. * @param mixed $order
  233. * @param string $order_type
  234. * @param string $payment
  235. * @param string $platform
  236. * @param string $channel
  237. * @param string $openid
  238. * @return mixed
  239. * @throws Exception
  240. */
  241. protected function handleThirdPartyPayment($payModel, $order, $payment, $platform, $openid)
  242. {
  243. $order_data = [
  244. 'order_id' => $order->id,
  245. 'out_trade_no' => $payModel->pay_sn,
  246. 'total_amount' => $payModel->pay_fee, // 剩余支付金额
  247. ];
  248. // 微信支付需要 openid
  249. if ($payment == 'wechat') {
  250. $this->handleWechatPaymentData($order_data, $platform, $openid, $order);
  251. $order_data['description'] = '商城订单支付';
  252. } else {
  253. $order_data['subject'] = '商城订单支付';
  254. }
  255. // 创建支付服务
  256. $payService = new PayService($payment, $platform);
  257. try {
  258. $result = $payService->pay($order_data);
  259. } catch (\Yansongda\Pay\Exception\Exception $e) {
  260. throw new Exception('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  261. } catch (HttpResponseException $e) {
  262. $data = $e->getResponse()->getData();
  263. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  264. throw new Exception('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  265. }
  266. // APP 平台特殊处理
  267. if ($platform == 'App') {
  268. if ($payment == 'wechat') {
  269. // Yansongda\Supports\Collection,可当数组,可当字符串,这里不用处理
  270. } else {
  271. // Guzzle
  272. $result = $result->getBody()->getContents();
  273. }
  274. }
  275. return $result;
  276. }
  277. /**
  278. * 处理微信支付数据
  279. * @param array &$order_data
  280. * @param string $platform
  281. * @param string $openid
  282. * @param mixed $order
  283. * @throws Exception
  284. */
  285. protected function handleWechatPaymentData(&$order_data, $platform, $openid, $order)
  286. {
  287. // 微信公众号,小程序支付,必须有 openid
  288. if (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  289. if (isset($openid) && $openid) {
  290. // 如果传的有 openid
  291. $order_data['payer']['openid'] = $openid;
  292. } else {
  293. // 没有 openid 默认拿下单人的 openid
  294. // 需要根据实际的第三方授权模型调整
  295. try {
  296. $oauthModel = '\\app\\common\\model\\Third';
  297. if (class_exists($oauthModel)) {
  298. $oauth = $oauthModel::where([
  299. 'user_id' => $order->user_id,
  300. 'platform' => 'wechat',
  301. 'apptype' => lcfirst(str_replace('wechat', '', $platform))
  302. ])->find();
  303. $order_data['payer']['openid'] = $oauth ? $oauth->openid : '';
  304. } else {
  305. $order_data['payer']['openid'] = '';
  306. }
  307. } catch (\Exception $e) {
  308. $order_data['payer']['openid'] = '';
  309. }
  310. }
  311. if (empty($order_data['payer']['openid'])) {
  312. // 缺少 openid
  313. throw new Exception('miss_openid', -1);
  314. }
  315. }
  316. }
  317. }