Pay.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. $logincode = $this->request->post('login_code', '');
  92. // $money = $money > 0 ? $money : 0;
  93. $platform = $this->request->header('platform');
  94. $userId = $this->auth->getUser()->id;
  95. // 获取订单实例
  96. $order = new Order();
  97. $order = $order->where('user_id', $userId)->where('id', $orderId)->find();
  98. if (!$order) {
  99. $this->error(__('No Results were found'));
  100. }
  101. // 验证订单状态
  102. if (!$order->canPayHandle()) {
  103. $this->error(__('订单状态不支持支付'));
  104. }
  105. // 验证支付类型
  106. if (!$payment || !in_array($payment, ['wechat', 'alipay', 'douyin'])) {
  107. $this->error('支付类型不能为空');
  108. }
  109. // 验证支付环境
  110. // if ($channel && !ChannelEnum::channelSupportsPayment($channel, $payment)) {
  111. // $this->error('当前渠道不支持该支付方式');
  112. // }
  113. $payOper = new PayOperService($this->auth->getUser());
  114. $orderType = $order->type;
  115. $payModel = $payOper->{$payment}($order, $order->amount, $orderType);
  116. $order->save(['pay_type' =>$payment]);
  117. $order_data = [
  118. 'order_id' => $order->id,
  119. 'out_trade_no' => $payModel->pay_sn,
  120. 'total_amount' => $payModel->pay_fee, // 剩余支付金额
  121. ];
  122. // 微信公众号,小程序支付,必须有 openid
  123. if ($payment == 'wechat') {
  124. // 如果传了 code
  125. if (!empty($logincode)) {
  126. $json = (new \app\common\library\Wechat\Service())->getWechatSession($logincode);
  127. $openid = $json['openid'] ?? '';
  128. $order_data['payer']['openid'] = $openid;
  129. }else{
  130. if (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  131. if (isset($openid) && $openid) {
  132. // 如果传的有 openid
  133. $order_data['payer']['openid'] = $openid;
  134. } else {
  135. // 没有 openid 默认拿下单人的 openid
  136. $oauth = ThirdOauth::where([
  137. 'user_id' => $order->user_id,
  138. 'platform' => $payment,
  139. 'apptype' => lcfirst(str_replace($payment, '', $platform))
  140. ])->find();
  141. $order_data['payer']['openid'] = $oauth ? $oauth->openid : '';
  142. }
  143. if (empty($order_data['payer']['openid'])) {
  144. // 缺少 openid
  145. $this->error('miss_openid', -1);
  146. }
  147. }
  148. }
  149. $order_data['description'] = '商城订单支付';
  150. } else {
  151. $order_data['subject'] = '商城订单支付';
  152. }
  153. if($platform == ChannelEnum::CHANNEL_DOUYIN_MINI_PROGRAM){
  154. $order_data['out_order_no'] = $payModel->pay_sn;
  155. }
  156. // echo "<pre>";
  157. // print_r(lcfirst(str_replace($payment, '', $platform)));
  158. // echo "</pre>";die();
  159. // echo "<pre>";
  160. // print_r($order_data);
  161. // echo "</pre>";die();
  162. try {
  163. $payService = new PayService($payment, $platform);
  164. $result = $payService->pay($order_data);
  165. } catch (\Yansongda\Pay\Exception\Exception $e) {
  166. $this->error('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  167. } catch (HttpResponseException $e) {
  168. $data = $e->getResponse()->getData();
  169. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  170. $this->error('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  171. } catch (\Exception $e) {
  172. // 捕获构造函数错误和其他异常
  173. $errorMessage = $e->getMessage();
  174. Log::error('PayService创建失败: ' . $errorMessage);
  175. $this->error('支付服务初始化失败' . (config('app_debug') ? ":" . $errorMessage : ',请重试'));
  176. }
  177. $this->success('', [
  178. 'pay_data' => $result,
  179. ]);
  180. }
  181. /**
  182. * 处理余额混合支付
  183. * @param PayOperService $payOper
  184. * @param mixed $order
  185. * @param string $order_type
  186. * @param float $money
  187. * @return mixed
  188. */
  189. protected function handleBalanceMixedPayment($payOper, $order, $order_type, $money)
  190. {
  191. return Db::transaction(function () use ($payOper, $order, $order_type, $money) {
  192. // 加锁读订单
  193. $order = $order->lock(true)->find($order->id);
  194. // 余额支付
  195. $order = $payOper->money($order, $money, $order_type);
  196. return $order;
  197. });
  198. }
  199. /**
  200. * 处理纯余额支付
  201. * @param PayOperService $payOper
  202. * @param mixed $order
  203. * @param string $order_type
  204. * @return mixed
  205. * @throws Exception
  206. */
  207. protected function handleBalancePayment($payOper, $order, $order_type)
  208. {
  209. $order = Db::transaction(function () use ($payOper, $order, $order_type) {
  210. // 加锁读订单
  211. $order = $order->lock(true)->find($order->id);
  212. $order = $payOper->money($order, $order->remain_pay_fee, $order_type);
  213. return $order;
  214. });
  215. if ($order->status != $order::STATUS_PAID) {
  216. throw new Exception('订单支付失败');
  217. }
  218. return $order;
  219. }
  220. /**
  221. * 处理货到付款
  222. * @param PayOperService $payOper
  223. * @param mixed $order
  224. * @param string $order_type
  225. * @return mixed
  226. * @throws Exception
  227. */
  228. protected function handleOfflinePayment($payOper, $order, $order_type)
  229. {
  230. if (!isset($order->ext['offline_status']) || $order->ext['offline_status'] != 'enable') {
  231. throw new Exception('订单不支持货到付款');
  232. }
  233. return Db::transaction(function () use ($payOper, $order, $order_type) {
  234. // 加锁读订单
  235. $order = $order->lock(true)->find($order->id);
  236. $order = $payOper->offline($order, 0, $order_type); // 增加 0 记录
  237. return $order;
  238. });
  239. }
  240. /**
  241. * 处理第三方支付(微信、支付宝)
  242. * @param PayOperService $payOper
  243. * @param mixed $order
  244. * @param string $order_type
  245. * @param string $payment
  246. * @param string $platform
  247. * @param string $channel
  248. * @param string $openid
  249. * @return mixed
  250. * @throws Exception
  251. */
  252. protected function handleThirdPartyPayment($payModel, $order, $payment, $platform, $openid)
  253. {
  254. $order_data = [
  255. 'order_id' => $order->id,
  256. 'out_trade_no' => $payModel->pay_sn,
  257. 'total_amount' => $payModel->pay_fee, // 剩余支付金额
  258. ];
  259. // 微信支付需要 openid
  260. if ($payment == 'wechat') {
  261. $this->handleWechatPaymentData($order_data, $platform, $openid, $order);
  262. $order_data['description'] = '商城订单支付';
  263. } else {
  264. $order_data['subject'] = '商城订单支付';
  265. }
  266. // 创建支付服务
  267. $payService = new PayService($payment, $platform);
  268. try {
  269. $result = $payService->pay($order_data);
  270. } catch (\Yansongda\Pay\Exception\Exception $e) {
  271. throw new Exception('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
  272. } catch (HttpResponseException $e) {
  273. $data = $e->getResponse()->getData();
  274. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  275. throw new Exception('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
  276. }
  277. // APP 平台特殊处理
  278. if ($platform == 'App') {
  279. if ($payment == 'wechat') {
  280. // Yansongda\Supports\Collection,可当数组,可当字符串,这里不用处理
  281. } else {
  282. // Guzzle
  283. $result = $result->getBody()->getContents();
  284. }
  285. }
  286. return $result;
  287. }
  288. /**
  289. * 处理微信支付数据
  290. * @param array &$order_data
  291. * @param string $platform
  292. * @param string $openid
  293. * @param mixed $order
  294. * @throws Exception
  295. */
  296. protected function handleWechatPaymentData(&$order_data, $platform, $openid, $order)
  297. {
  298. // 微信公众号,小程序支付,必须有 openid
  299. if (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  300. if (isset($openid) && $openid) {
  301. // 如果传的有 openid
  302. $order_data['payer']['openid'] = $openid;
  303. } else {
  304. // 没有 openid 默认拿下单人的 openid
  305. // 需要根据实际的第三方授权模型调整
  306. try {
  307. $oauthModel = '\\app\\common\\model\\Third';
  308. if (class_exists($oauthModel)) {
  309. $oauth = $oauthModel::where([
  310. 'user_id' => $order->user_id,
  311. 'platform' => 'wechat',
  312. 'apptype' => lcfirst(str_replace('wechat', '', $platform))
  313. ])->find();
  314. $order_data['payer']['openid'] = $oauth ? $oauth->openid : '';
  315. } else {
  316. $order_data['payer']['openid'] = '';
  317. }
  318. } catch (\Exception $e) {
  319. $order_data['payer']['openid'] = '';
  320. }
  321. }
  322. if (empty($order_data['payer']['openid'])) {
  323. // 缺少 openid
  324. throw new Exception('miss_openid', -1);
  325. }
  326. }
  327. }
  328. }