Refund.php 2.4 KB

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