MixedPayService.php 14 KB

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