MixedPayService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop100%开源免费商用商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | gitee下载:https://gitee.com/likeshop_gitee
  10. // | github下载:https://github.com/likeshop-github
  11. // | 访问官网:https://www.likeshop.cn
  12. // | 访问社区:https://home.likeshop.cn
  13. // | 访问手册:http://doc.likeshop.cn
  14. // | 微信公众号:likeshop技术社区
  15. // | likeshop团队 版权所有 拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshopTeam
  18. // +----------------------------------------------------------------------
  19. namespace app\common\service\pay;
  20. use app\common\enum\AccountLogEnum;
  21. use app\common\enum\PayEnum;
  22. use app\common\enum\AfterSaleEnum;
  23. use app\common\enum\AfterSaleLogEnum;
  24. use app\common\enum\NoticeEnum;
  25. use app\common\model\AfterSale;
  26. use app\common\model\Refund;
  27. use app\common\service\after_sale\AfterSaleService;
  28. use app\common\logic\AccountLogLogic;
  29. use app\common\model\User;
  30. use app\common\model\Order;
  31. use think\facade\Db;
  32. /**
  33. * 混合支付服务(余额+微信)
  34. * Class MixedPayService
  35. * @package app\common\service\pay
  36. */
  37. class MixedPayService extends BasePayService
  38. {
  39. protected $wechatPayService;
  40. protected $balancePayService;
  41. public function __construct($terminal, $userId = null)
  42. {
  43. try {
  44. $this->wechatPayService = new WeChatPayService($terminal, $userId);
  45. $this->balancePayService = new BalancePayService();
  46. } catch (\Exception $e) {
  47. $this->setError('混合支付服务初始化失败:' . $e->getMessage());
  48. }
  49. }
  50. /**
  51. * @notes 获取真实支付对象
  52. * @return mixed
  53. */
  54. function realPay()
  55. {
  56. return $this->wechatPayService->realPay();
  57. }
  58. /**
  59. * @notes 混合支付(余额+微信)
  60. * @param $from 订单类型
  61. * @param $order 订单信息
  62. * @return array|false
  63. * @author 系统
  64. * @date 2024/12/19
  65. */
  66. public function pay($from, $order)
  67. {
  68. Db::startTrans();
  69. try {
  70. $user = User::findOrEmpty($order['user_id']);
  71. if ($user->isEmpty()) {
  72. throw new \Exception('用户不存在');
  73. }
  74. // 记录调试日志
  75. file_put_contents(
  76. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  77. "[" . date('Y-m-d H:i:s') . "] 混合支付开始 - 用户ID: {$order['user_id']}, 订单号: {$order['sn']}, 订单金额: {$order['order_amount']}" . PHP_EOL,
  78. FILE_APPEND | LOCK_EX
  79. );
  80. $userBalance = $user['user_money']; // 用户余额
  81. $orderAmount = $order['order_amount']; // 订单金额
  82. // 记录余额信息
  83. file_put_contents(
  84. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  85. "[" . date('Y-m-d H:i:s') . "] 用户余额: {$userBalance}, 订单金额: {$orderAmount}" . PHP_EOL,
  86. FILE_APPEND | LOCK_EX
  87. );
  88. // 如果余额足够支付全部订单,直接使用余额支付
  89. if ($userBalance >= $orderAmount) {
  90. file_put_contents(
  91. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  92. "[" . date('Y-m-d H:i:s') . "] 余额充足,使用纯余额支付" . PHP_EOL,
  93. FILE_APPEND | LOCK_EX
  94. );
  95. $result = $this->balancePayService->pay($from, $order);
  96. if ($result === false) {
  97. throw new \Exception('余额支付失败:' . $this->balancePayService->getError());
  98. }
  99. Db::commit();
  100. return $result;
  101. }
  102. // 余额不足,使用混合支付
  103. $balanceAmount = $userBalance; // 使用全部余额
  104. $wechatAmount = $orderAmount - $balanceAmount; // 剩余金额用微信支付
  105. file_put_contents(
  106. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  107. "[" . date('Y-m-d H:i:s') . "] 使用混合支付 - 余额部分: {$balanceAmount}, 微信部分: {$wechatAmount}" . PHP_EOL,
  108. FILE_APPEND | LOCK_EX
  109. );
  110. // 先扣除用户余额
  111. if ($balanceAmount > 0) {
  112. //先不扣余额,等为微信支付成功后扣钱
  113. // User::update([
  114. // 'user_money' => ['dec', $balanceAmount]
  115. // ], ['id' => $order['user_id']]);
  116. //
  117. // // 记录余额流水
  118. // AccountLogLogic::add(
  119. // $order['user_id'],
  120. // AccountLogEnum::BNW_DEC_ORDER,
  121. // AccountLogEnum::DEC,
  122. // $balanceAmount,
  123. // $order['sn'],
  124. // '混合支付-余额部分'
  125. // );
  126. //
  127. // file_put_contents(
  128. // runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  129. // "[" . date('Y-m-d H:i:s') . "] 余额扣除成功,扣除金额: {$balanceAmount}" . PHP_EOL,
  130. // FILE_APPEND | LOCK_EX
  131. // );
  132. Order::update([
  133. 'balance_amount' => $balanceAmount
  134. ], ['id' => $order['id']]);
  135. }
  136. // 创建微信支付订单(金额为剩余需要支付的金额)
  137. $wechatOrder = $order;
  138. $wechatOrder['order_amount'] = round($wechatAmount,2);
  139. $wechatOrder['balance_amount'] = $balanceAmount; // 记录已使用的余额金额
  140. file_put_contents(
  141. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  142. "[" . date('Y-m-d H:i:s') . "] 开始创建微信支付订单,金额: {$wechatAmount}" . PHP_EOL,
  143. FILE_APPEND | LOCK_EX
  144. );
  145. outFileLog($wechatOrder,'prepay','$wechatOrder');
  146. // Db::commit();
  147. // return $wechatOrder;
  148. $result = $this->wechatPayService->pay($from, $wechatOrder);
  149. if ($result === false) {
  150. throw new \Exception('微信支付创建失败:' . $this->wechatPayService->getError());
  151. }
  152. // 在返回结果中添加混合支付信息
  153. $result['pay_way'] = PayEnum::MIXED_PAY;
  154. $result['balance_amount'] = $balanceAmount;
  155. $result['wechat_amount'] = $wechatAmount;
  156. $result['total_amount'] = $orderAmount;
  157. file_put_contents(
  158. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  159. "[" . date('Y-m-d H:i:s') . "] 混合支付创建成功" . PHP_EOL,
  160. FILE_APPEND | LOCK_EX
  161. );
  162. Db::commit();
  163. return $result;
  164. } catch (\Exception $e) {
  165. Db::rollback();
  166. file_put_contents(
  167. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  168. "[" . date('Y-m-d H:i:s') . "] 混合支付失败: " . $e->getMessage() . PHP_EOL,
  169. FILE_APPEND | LOCK_EX
  170. );
  171. $this->setError($e->getMessage());
  172. return false;
  173. }
  174. }
  175. /**
  176. * @notes 混合支付退款
  177. * @param $order 订单信息
  178. * @param $refundAmount 退款金额
  179. * @param $afterSaleId 售后ID
  180. * @return bool
  181. */
  182. public function refund($order, $refundAmount, $afterSaleId)
  183. {
  184. Db::startTrans();
  185. try {
  186. // 记录退款日志
  187. file_put_contents(
  188. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  189. "[" . date('Y-m-d H:i:s') . "] 混合支付退款开始 - 订单号: {$order['sn']}, 退款金额: {$refundAmount}" . PHP_EOL,
  190. FILE_APPEND | LOCK_EX
  191. );
  192. // 获取订单的余额支付金额和微信支付金额
  193. $balanceAmount = $order['balance_amount'] ?? 0;
  194. $wechatAmount = $order['order_amount'] - $balanceAmount;
  195. // 计算退款比例
  196. $refundRatio = $refundAmount / $order['order_amount'];
  197. $refundBalanceAmount = round($balanceAmount * $refundRatio, 2);
  198. $refundWechatAmount = round($wechatAmount * $refundRatio, 2);
  199. // 确保退款金额精确
  200. $totalCalculated = $refundBalanceAmount + $refundWechatAmount;
  201. if ($totalCalculated != $refundAmount) {
  202. $diff = $refundAmount - $totalCalculated;
  203. if ($refundWechatAmount > 0) {
  204. $refundWechatAmount += $diff;
  205. } else {
  206. $refundBalanceAmount += $diff;
  207. }
  208. }
  209. file_put_contents(
  210. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  211. "[" . date('Y-m-d H:i:s') . "] 退款分配 - 余额退款: {$refundBalanceAmount}, 微信退款: {$refundWechatAmount}" . PHP_EOL,
  212. FILE_APPEND | LOCK_EX
  213. );
  214. // 处理余额退款
  215. if ($refundBalanceAmount > 0) {
  216. // 返回余额
  217. User::update([
  218. 'user_money' => ['inc', $refundBalanceAmount]
  219. ], ['id' => $order['user_id']]);
  220. // 记录余额流水
  221. $afterSale = AfterSale::findOrEmpty($afterSaleId);
  222. AccountLogLogic::add(
  223. $order['user_id'],
  224. AccountLogEnum::BNW_INC_AFTER_SALE,
  225. AccountLogEnum::INC,
  226. $refundBalanceAmount,
  227. $afterSale->sn,
  228. '混合支付退款-余额部分'
  229. );
  230. file_put_contents(
  231. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  232. "[" . date('Y-m-d H:i:s') . "] 余额退款完成: {$refundBalanceAmount}" . PHP_EOL,
  233. FILE_APPEND | LOCK_EX
  234. );
  235. }
  236. // 处理微信退款
  237. if ($refundWechatAmount > 0) {
  238. // 记录退款日志
  239. file_put_contents(
  240. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  241. "[" . date('Y-m-d H:i:s') . "] 混合支付退款开始 - 订单号: {$order['sn']}, 微信退款金额: {$refundWechatAmount}" . PHP_EOL,
  242. FILE_APPEND | LOCK_EX
  243. );
  244. file_put_contents(
  245. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  246. "[" . date('Y-m-d H:i:s') . "] 混合支付退款开始 - 订单号: {$order['sn']}, 微信支付金额: {$wechatAmount}" . PHP_EOL,
  247. FILE_APPEND | LOCK_EX
  248. );
  249. $pay = new WeChatPayService($order['order_terminal']);
  250. $result = $pay->refund([
  251. 'transaction_id' => $order['transaction_id'],
  252. 'refund_sn' => 'mixed_refund_' . $order['sn'] . '_' . time(),
  253. 'total_fee' => round($wechatAmount,2),
  254. 'refund_fee' => $refundWechatAmount,
  255. ]);
  256. if ($result !== true) {
  257. throw new \Exception($pay->realPay()->getMessage());
  258. }
  259. // //更新退款日志记录
  260. // Refund::update([
  261. // 'wechat_refund_id' => 0,
  262. // 'refund_status' => 1,
  263. // 'refund_msg' => json_encode([], JSON_UNESCAPED_UNICODE),
  264. // ], ['id' => self::$refund['id']]);
  265. // $refundData = [
  266. // 'transaction_id' => $order['transaction_id'],
  267. // 'refund_sn' => 'mixed_refund_' . $order['sn'] . '_' . time(),
  268. // 'total_fee' => $wechatAmount,
  269. // 'refund_fee' => $refundWechatAmount,
  270. // ];
  271. //
  272. // $result = $this->wechatPayService->refund($refundData);
  273. // if ($result !== true) {
  274. // throw new \Exception('微信退款失败:' . $this->wechatPayService->getError());
  275. // }
  276. file_put_contents(
  277. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  278. "[" . date('Y-m-d H:i:s') . "] 微信退款完成: {$refundWechatAmount}" . PHP_EOL,
  279. FILE_APPEND | LOCK_EX
  280. );
  281. }
  282. // 更新售后状态
  283. $afterSale = AfterSale::findOrEmpty($afterSaleId);
  284. if (!$afterSale->isEmpty()) {
  285. // 判断退款状态
  286. $refundStatus = ($refundAmount >= $order['order_amount']) ?
  287. AfterSaleEnum::FULL_REFUND : AfterSaleEnum::PARTIAL_REFUND;
  288. $afterSale->status = AfterSaleEnum::STATUS_SUCCESS;
  289. $afterSale->sub_status = AfterSaleEnum::SUB_STATUS_SELLER_REFUND_SUCCESS;
  290. $afterSale->refund_status = $refundStatus;
  291. $afterSale->save();
  292. // 添加售后日志
  293. AfterSaleService::createAfterLog(
  294. $afterSale->id,
  295. '系统已完成混合支付退款',
  296. 0,
  297. AfterSaleLogEnum::ROLE_SYS
  298. );
  299. // 发送退款成功通知
  300. event('Notice', [
  301. 'scene_id' => NoticeEnum::REFUND_SUCCESS_NOTICE,
  302. 'params' => [
  303. 'user_id' => $afterSale->user_id,
  304. 'order_sn' => $order['sn'],
  305. 'after_sale_sn' => $afterSale->sn,
  306. 'refund_type' => AfterSaleEnum::getRefundTypeDesc($afterSale->refund_type),
  307. 'refund_total_amount' => $afterSale->refund_total_amount,
  308. 'refund_time' => date('Y-m-d H:i:s'),
  309. ]
  310. ]);
  311. }
  312. file_put_contents(
  313. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  314. "[" . date('Y-m-d H:i:s') . "] 混合支付退款成功" . PHP_EOL,
  315. FILE_APPEND | LOCK_EX
  316. );
  317. Db::commit();
  318. return true;
  319. } catch (\Exception $e) {
  320. Db::rollback();
  321. file_put_contents(
  322. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  323. "[" . date('Y-m-d H:i:s') . "] 混合支付退款失败: " . $e->getMessage() . PHP_EOL,
  324. FILE_APPEND | LOCK_EX
  325. );
  326. $this->setError($e->getMessage());
  327. return false;
  328. }
  329. }
  330. }