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