MixedPayService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. // Db::commit();
  138. // return $wechatOrder;
  139. $result = $this->wechatPayService->pay($from, $wechatOrder);
  140. if ($result === false) {
  141. throw new \Exception('微信支付创建失败:' . $this->wechatPayService->getError());
  142. }
  143. // 在返回结果中添加混合支付信息
  144. $result['pay_way'] = PayEnum::MIXED_PAY;
  145. $result['balance_amount'] = $balanceAmount;
  146. $result['wechat_amount'] = $wechatAmount;
  147. $result['total_amount'] = $orderAmount;
  148. file_put_contents(
  149. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_pay_debug_' . date('Y-m-d') . '.log',
  150. "[" . date('Y-m-d H:i:s') . "] 混合支付创建成功" . PHP_EOL,
  151. FILE_APPEND | LOCK_EX
  152. );
  153. Db::commit();
  154. return $result;
  155. } catch (\Exception $e) {
  156. Db::rollback();
  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') . "] 混合支付失败: " . $e->getMessage() . PHP_EOL,
  160. FILE_APPEND | LOCK_EX
  161. );
  162. $this->setError($e->getMessage());
  163. return false;
  164. }
  165. }
  166. /**
  167. * @notes 混合支付退款
  168. * @param $order 订单信息
  169. * @param $refundAmount 退款金额
  170. * @param $afterSaleId 售后ID
  171. * @return bool
  172. */
  173. public function refund($order, $refundAmount, $afterSaleId)
  174. {
  175. Db::startTrans();
  176. try {
  177. // 记录退款日志
  178. file_put_contents(
  179. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  180. "[" . date('Y-m-d H:i:s') . "] 混合支付退款开始 - 订单号: {$order['sn']}, 退款金额: {$refundAmount}" . PHP_EOL,
  181. FILE_APPEND | LOCK_EX
  182. );
  183. // 获取订单的余额支付金额和微信支付金额
  184. $balanceAmount = $order['balance_amount'] ?? 0;
  185. $wechatAmount = $order['order_amount'] - $balanceAmount;
  186. // 计算退款比例
  187. $refundRatio = $refundAmount / $order['order_amount'];
  188. $refundBalanceAmount = round($balanceAmount * $refundRatio, 2);
  189. $refundWechatAmount = round($wechatAmount * $refundRatio, 2);
  190. // 确保退款金额精确
  191. $totalCalculated = $refundBalanceAmount + $refundWechatAmount;
  192. if ($totalCalculated != $refundAmount) {
  193. $diff = $refundAmount - $totalCalculated;
  194. if ($refundWechatAmount > 0) {
  195. $refundWechatAmount += $diff;
  196. } else {
  197. $refundBalanceAmount += $diff;
  198. }
  199. }
  200. file_put_contents(
  201. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  202. "[" . date('Y-m-d H:i:s') . "] 退款分配 - 余额退款: {$refundBalanceAmount}, 微信退款: {$refundWechatAmount}" . PHP_EOL,
  203. FILE_APPEND | LOCK_EX
  204. );
  205. // 处理余额退款
  206. if ($refundBalanceAmount > 0) {
  207. // 返回余额
  208. User::update([
  209. 'user_money' => ['inc', $refundBalanceAmount]
  210. ], ['id' => $order['user_id']]);
  211. // 记录余额流水
  212. $afterSale = AfterSale::findOrEmpty($afterSaleId);
  213. AccountLogLogic::add(
  214. $order['user_id'],
  215. AccountLogEnum::BNW_INC_AFTER_SALE,
  216. AccountLogEnum::INC,
  217. $refundBalanceAmount,
  218. $afterSale->sn,
  219. '混合支付退款-余额部分'
  220. );
  221. file_put_contents(
  222. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  223. "[" . date('Y-m-d H:i:s') . "] 余额退款完成: {$refundBalanceAmount}" . PHP_EOL,
  224. FILE_APPEND | LOCK_EX
  225. );
  226. }
  227. // 处理微信退款
  228. if ($refundWechatAmount > 0) {
  229. $refundData = [
  230. 'transaction_id' => $order['transaction_id'],
  231. 'refund_sn' => 'mixed_refund_' . $order['sn'] . '_' . time(),
  232. 'total_fee' => $wechatAmount,
  233. 'refund_fee' => $refundWechatAmount,
  234. ];
  235. $result = $this->wechatPayService->refund($refundData);
  236. if ($result !== true) {
  237. throw new \Exception('微信退款失败:' . $this->wechatPayService->getError());
  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') . "] 微信退款完成: {$refundWechatAmount}" . PHP_EOL,
  242. FILE_APPEND | LOCK_EX
  243. );
  244. }
  245. // 更新售后状态
  246. $afterSale = AfterSale::findOrEmpty($afterSaleId);
  247. if (!$afterSale->isEmpty()) {
  248. // 判断退款状态
  249. $refundStatus = ($refundAmount >= $order['order_amount']) ?
  250. AfterSaleEnum::FULL_REFUND : AfterSaleEnum::PARTIAL_REFUND;
  251. $afterSale->status = AfterSaleEnum::STATUS_SUCCESS;
  252. $afterSale->sub_status = AfterSaleEnum::SUB_STATUS_SELLER_REFUND_SUCCESS;
  253. $afterSale->refund_status = $refundStatus;
  254. $afterSale->save();
  255. // 添加售后日志
  256. AfterSaleService::createAfterLog(
  257. $afterSale->id,
  258. '系统已完成混合支付退款',
  259. 0,
  260. AfterSaleLogEnum::ROLE_SYS
  261. );
  262. // 发送退款成功通知
  263. event('Notice', [
  264. 'scene_id' => NoticeEnum::REFUND_SUCCESS_NOTICE,
  265. 'params' => [
  266. 'user_id' => $afterSale->user_id,
  267. 'order_sn' => $order['sn'],
  268. 'after_sale_sn' => $afterSale->sn,
  269. 'refund_type' => AfterSaleEnum::getRefundTypeDesc($afterSale->refund_type),
  270. 'refund_total_amount' => $afterSale->refund_total_amount,
  271. 'refund_time' => date('Y-m-d H:i:s'),
  272. ]
  273. ]);
  274. }
  275. file_put_contents(
  276. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  277. "[" . date('Y-m-d H:i:s') . "] 混合支付退款成功" . PHP_EOL,
  278. FILE_APPEND | LOCK_EX
  279. );
  280. Db::commit();
  281. return true;
  282. } catch (\Exception $e) {
  283. Db::rollback();
  284. file_put_contents(
  285. runtime_path() . 'log' . DIRECTORY_SEPARATOR . 'mixed_refund_debug_' . date('Y-m-d') . '.log',
  286. "[" . date('Y-m-d H:i:s') . "] 混合支付退款失败: " . $e->getMessage() . PHP_EOL,
  287. FILE_APPEND | LOCK_EX
  288. );
  289. $this->setError($e->getMessage());
  290. return false;
  291. }
  292. }
  293. }