Refund.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace app\common\service\order;
  3. use app\common\model\User as UserModel;
  4. use app\common\model\Wxapp as WxappModel;
  5. use app\common\model\user\BalanceLog as BalanceLogModel;
  6. use app\common\enum\order\PayType as PayTypeEnum;
  7. use app\common\enum\user\balanceLog\Scene as SceneEnum;
  8. use app\common\library\wechat\WxPay;
  9. /**
  10. * 订单退款服务类
  11. * Class Refund
  12. * @package app\common\service\order
  13. */
  14. class Refund
  15. {
  16. /**
  17. * 执行订单退款
  18. * @param \app\common\model\BaseModel $order 订单信息
  19. * @param double|null $money 指定退款金额
  20. * @return bool
  21. * @throws \think\Exception
  22. * @throws \think\exception\DbException
  23. * @throws \app\common\exception\BaseException
  24. */
  25. public function execute($order, $money = null)
  26. {
  27. // 退款金额,如不指定则默认为订单实付款金额
  28. is_null($money) && $money = $order['pay_price'];
  29. // 1.微信支付退款
  30. if ($order['pay_type']['value'] == PayTypeEnum::WECHAT) {
  31. return $this->wxpay($order, $money);
  32. }
  33. // 2.余额支付退款
  34. if ($order['pay_type']['value'] == PayTypeEnum::BALANCE) {
  35. return $this->balance($order, $money);
  36. }
  37. return false;
  38. }
  39. /**
  40. * 余额支付退款
  41. * @param $order
  42. * @param $money
  43. * @return bool
  44. * @throws \think\Exception
  45. * @throws \think\exception\DbException
  46. */
  47. private function balance(&$order, $money)
  48. {
  49. // 回退用户余额
  50. $user = UserModel::detail($order['user_id']);
  51. if (empty($user)) return false;
  52. $user->setInc('balance', $money);
  53. // 记录余额明细
  54. BalanceLogModel::add(SceneEnum::REFUND, [
  55. 'user_id' => $user['user_id'],
  56. 'money' => $money,
  57. ], ['order_no' => $order['order_no']]);
  58. return true;
  59. }
  60. /**
  61. * 微信支付退款
  62. * @param $order
  63. * @param double $money
  64. * @return bool
  65. * @throws \app\common\exception\BaseException
  66. * @throws \think\exception\DbException
  67. */
  68. private function wxpay(&$order, $money)
  69. {
  70. $wxConfig = WxappModel::getWxappCache($order['wxapp_id']);
  71. $WxPay = new WxPay($wxConfig);
  72. return $WxPay->refund($order['transaction_id'], $order['pay_price'], $money);
  73. }
  74. }