Refund.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. $user->setInc('balance', $money);
  52. // 记录余额明细
  53. BalanceLogModel::add(SceneEnum::REFUND, [
  54. 'user_id' => $user['user_id'],
  55. 'money' => $money,
  56. ], ['order_no' => $order['order_no']]);
  57. return true;
  58. }
  59. /**
  60. * 微信支付退款
  61. * @param $order
  62. * @param double $money
  63. * @return bool
  64. * @throws \app\common\exception\BaseException
  65. * @throws \think\exception\DbException
  66. */
  67. private function wxpay(&$order, $money)
  68. {
  69. $wxConfig = WxappModel::getWxappCache($order['wxapp_id']);
  70. $WxPay = new WxPay($wxConfig);
  71. return $WxPay->refund($order['transaction_id'], $order['pay_price'], $money);
  72. }
  73. }