MixedPayService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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\service\after_sale\AfterSaleService;
  27. use app\common\logic\AccountLogLogic;
  28. use app\common\model\User;
  29. use think\facade\Db;
  30. /**
  31. * 混合支付服务(余额+微信)
  32. * Class MixedPayService
  33. * @package app\common\service\pay
  34. */
  35. class MixedPayService extends BasePayService
  36. {
  37. protected $wechatPayService;
  38. protected $balancePayService;
  39. public function __construct($terminal, $userId = null)
  40. {
  41. try {
  42. $this->wechatPayService = new WeChatPayService($terminal, $userId);
  43. $this->balancePayService = new BalancePayService();
  44. } catch (\Exception $e) {
  45. $this->setError('混合支付服务初始化失败:' . $e->getMessage());
  46. }
  47. }
  48. /**
  49. * @notes 获取真实支付对象
  50. * @return mixed
  51. */
  52. function realPay()
  53. {
  54. return $this->wechatPayService->realPay();
  55. }
  56. /**
  57. * @notes 混合支付(余额+微信)
  58. * @param $from 订单类型
  59. * @param $order 订单信息
  60. * @return array|false
  61. * @author 系统
  62. * @date 2024/12/19
  63. */
  64. public function pay($from, $order)
  65. {
  66. Db::startTrans();
  67. try {
  68. $user = User::findOrEmpty($order['user_id']);
  69. if ($user->isEmpty()) {
  70. throw new \Exception('用户不存在');
  71. }
  72. // 记录调试日志
  73. file_put_contents(
  74. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  75. "[" . date('Y-m-d H:i:s') . "] 混合支付开始 - 用户ID: {$order['user_id']}, 订单号: {$order['sn']}, 订单金额: {$order['order_amount']}" . PHP_EOL,
  76. FILE_APPEND | LOCK_EX
  77. );
  78. $userBalance = $user['user_money']; // 用户余额
  79. $orderAmount = $order['order_amount']; // 订单金额
  80. // 记录余额信息
  81. file_put_contents(
  82. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  83. "[" . date('Y-m-d H:i:s') . "] 用户余额: {$userBalance}, 订单金额: {$orderAmount}" . PHP_EOL,
  84. FILE_APPEND | LOCK_EX
  85. );
  86. // 如果余额足够支付全部订单,直接使用余额支付
  87. if ($userBalance >= $orderAmount) {
  88. file_put_contents(
  89. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  90. "[" . date('Y-m-d H:i:s') . "] 余额充足,使用纯余额支付" . PHP_EOL,
  91. FILE_APPEND | LOCK_EX
  92. );
  93. $result = $this->balancePayService->pay($from, $order);
  94. if ($result === false) {
  95. throw new \Exception('余额支付失败:' . $this->balancePayService->getError());
  96. }
  97. Db::commit();
  98. return $result;
  99. }
  100. // 余额不足,使用混合支付
  101. $balanceAmount = $userBalance; // 使用全部余额
  102. $wechatAmount = $orderAmount - $balanceAmount; // 剩余金额用微信支付
  103. file_put_contents(
  104. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  105. "[" . date('Y-m-d H:i:s') . "] 使用混合支付 - 余额部分: {$balanceAmount}, 微信部分: {$wechatAmount}" . PHP_EOL,
  106. FILE_APPEND | LOCK_EX
  107. );
  108. // 先扣除用户余额
  109. if ($balanceAmount > 0) {
  110. User::update([
  111. 'user_money' => ['dec', $balanceAmount]
  112. ], ['id' => $order['user_id']]);
  113. // 记录余额流水
  114. AccountLogLogic::add(
  115. $order['user_id'],
  116. AccountLogEnum::BNW_DEC_ORDER,
  117. AccountLogEnum::DEC,
  118. $balanceAmount,
  119. $order['sn'],
  120. '混合支付-余额部分'
  121. );
  122. file_put_contents(
  123. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  124. "[" . date('Y-m-d H:i:s') . "] 余额扣除成功,扣除金额: {$balanceAmount}" . PHP_EOL,
  125. FILE_APPEND | LOCK_EX
  126. );
  127. }
  128. // 创建微信支付订单(金额为剩余需要支付的金额)
  129. $wechatOrder = $order;
  130. $wechatOrder['order_amount'] = $wechatAmount;
  131. $wechatOrder['balance_amount'] = $balanceAmount; // 记录已使用的余额金额
  132. file_put_contents(
  133. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  134. "[" . date('Y-m-d H:i:s') . "] 开始创建微信支付订单,金额: {$wechatAmount}" . PHP_EOL,
  135. FILE_APPEND | LOCK_EX
  136. );
  137. $result = $this->wechatPayService->pay($from, $wechatOrder);
  138. if ($result === false) {
  139. throw new \Exception('微信支付创建失败:' . $this->wechatPayService->getError());
  140. }
  141. // 在返回结果中添加混合支付信息
  142. $result['pay_way'] = PayEnum::MIXED_PAY;
  143. $result['balance_amount'] = $balanceAmount;
  144. $result['wechat_amount'] = $wechatAmount;
  145. $result['total_amount'] = $orderAmount;
  146. file_put_contents(
  147. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  148. "[" . date('Y-m-d H:i:s') . "] 混合支付创建成功" . PHP_EOL,
  149. FILE_APPEND | LOCK_EX
  150. );
  151. Db::commit();
  152. return $result;
  153. } catch (\Exception $e) {
  154. Db::rollback();
  155. file_put_contents(
  156. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  157. "[" . date('Y-m-d H:i:s') . "] 混合支付失败: " . $e->getMessage() . PHP_EOL,
  158. FILE_APPEND | LOCK_EX
  159. );
  160. $this->setError($e->getMessage());
  161. return false;
  162. }
  163. }
  164. /**
  165. * @notes 混合支付退款
  166. * @param $order 订单信息
  167. * @param $refundAmount 退款金额
  168. * @param $afterSaleId 售后ID
  169. * @return bool
  170. */
  171. public function refund($order, $refundAmount, $afterSaleId)
  172. {
  173. Db::startTrans();
  174. try {
  175. // 记录退款日志
  176. file_put_contents(
  177. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  178. "[" . date('Y-m-d H:i:s') . "] 混合支付退款开始 - 订单号: {$order['sn']}, 退款金额: {$refundAmount}" . PHP_EOL,
  179. FILE_APPEND | LOCK_EX
  180. );
  181. // 获取订单的余额支付金额和微信支付金额
  182. $balanceAmount = $order['balance_amount'] ?? 0;
  183. $wechatAmount = $order['order_amount'] - $balanceAmount;
  184. // 计算退款比例
  185. $refundRatio = $refundAmount / $order['order_amount'];
  186. $refundBalanceAmount = round($balanceAmount * $refundRatio, 2);
  187. $refundWechatAmount = round($wechatAmount * $refundRatio, 2);
  188. // 确保退款金额精确
  189. $totalCalculated = $refundBalanceAmount + $refundWechatAmount;
  190. if ($totalCalculated != $refundAmount) {
  191. $diff = $refundAmount - $totalCalculated;
  192. if ($refundWechatAmount > 0) {
  193. $refundWechatAmount += $diff;
  194. } else {
  195. $refundBalanceAmount += $diff;
  196. }
  197. }
  198. file_put_contents(
  199. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  200. "[" . date('Y-m-d H:i:s') . "] 退款分配 - 余额退款: {$refundBalanceAmount}, 微信退款: {$refundWechatAmount}" . PHP_EOL,
  201. FILE_APPEND | LOCK_EX
  202. );
  203. // 处理余额退款
  204. if ($refundBalanceAmount > 0) {
  205. // 返回余额
  206. User::update([
  207. 'user_money' => ['inc', $refundBalanceAmount]
  208. ], ['id' => $order['user_id']]);
  209. // 记录余额流水
  210. $afterSale = AfterSale::findOrEmpty($afterSaleId);
  211. AccountLogLogic::add(
  212. $order['user_id'],
  213. AccountLogEnum::BNW_INC_AFTER_SALE,
  214. AccountLogEnum::INC,
  215. $refundBalanceAmount,
  216. $afterSale->sn,
  217. '混合支付退款-余额部分'
  218. );
  219. file_put_contents(
  220. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  221. "[" . date('Y-m-d H:i:s') . "] 余额退款完成: {$refundBalanceAmount}" . PHP_EOL,
  222. FILE_APPEND | LOCK_EX
  223. );
  224. }
  225. // 处理微信退款
  226. if ($refundWechatAmount > 0) {
  227. $refundData = [
  228. 'transaction_id' => $order['transaction_id'],
  229. 'refund_sn' => 'mixed_refund_' . $order['sn'] . '_' . time(),
  230. 'total_fee' => $wechatAmount,
  231. 'refund_fee' => $refundWechatAmount,
  232. ];
  233. $result = $this->wechatPayService->refund($refundData);
  234. if ($result !== true) {
  235. throw new \Exception('微信退款失败:' . $this->wechatPayService->getError());
  236. }
  237. file_put_contents(
  238. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  239. "[" . date('Y-m-d H:i:s') . "] 微信退款完成: {$refundWechatAmount}" . PHP_EOL,
  240. FILE_APPEND | LOCK_EX
  241. );
  242. }
  243. // 更新售后状态
  244. $afterSale = AfterSale::findOrEmpty($afterSaleId);
  245. if (!$afterSale->isEmpty()) {
  246. // 判断退款状态
  247. $refundStatus = ($refundAmount >= $order['order_amount']) ?
  248. AfterSaleEnum::FULL_REFUND : AfterSaleEnum::PARTIAL_REFUND;
  249. $afterSale->status = AfterSaleEnum::STATUS_SUCCESS;
  250. $afterSale->sub_status = AfterSaleEnum::SUB_STATUS_SELLER_REFUND_SUCCESS;
  251. $afterSale->refund_status = $refundStatus;
  252. $afterSale->save();
  253. // 添加售后日志
  254. AfterSaleService::createAfterLog(
  255. $afterSale->id,
  256. '系统已完成混合支付退款',
  257. 0,
  258. AfterSaleLogEnum::ROLE_SYS
  259. );
  260. // 发送退款成功通知
  261. event('Notice', [
  262. 'scene_id' => NoticeEnum::REFUND_SUCCESS_NOTICE,
  263. 'params' => [
  264. 'user_id' => $afterSale->user_id,
  265. 'order_sn' => $order['sn'],
  266. 'after_sale_sn' => $afterSale->sn,
  267. 'refund_type' => AfterSaleEnum::getRefundTypeDesc($afterSale->refund_type),
  268. 'refund_total_amount' => $afterSale->refund_total_amount,
  269. 'refund_time' => date('Y-m-d H:i:s'),
  270. ]
  271. ]);
  272. }
  273. file_put_contents(
  274. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  275. "[" . date('Y-m-d H:i:s') . "] 混合支付退款成功" . PHP_EOL,
  276. FILE_APPEND | LOCK_EX
  277. );
  278. Db::commit();
  279. return true;
  280. } catch (\Exception $e) {
  281. Db::rollback();
  282. file_put_contents(
  283. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  284. "[" . date('Y-m-d H:i:s') . "] 混合支付退款失败: " . $e->getMessage() . PHP_EOL,
  285. FILE_APPEND | LOCK_EX
  286. );
  287. $this->setError($e->getMessage());
  288. return false;
  289. }
  290. }
  291. }