OrderRefundService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\common\service\order;
  3. use app\common\library\alipay\AliPay;
  4. use app\common\library\easywechat\AppOpen;
  5. use app\common\model\user\User as UserModel;
  6. use app\common\model\user\BalanceLog as BalanceLogModel;
  7. use app\common\enum\order\OrderPayTypeEnum;
  8. use app\common\enum\user\balanceLog\BalanceLogSceneEnum;
  9. use app\common\library\easywechat\WxPay;
  10. use app\common\library\easywechat\AppWx;
  11. use app\common\library\easywechat\AppMp;
  12. /**
  13. * 订单退款服务类
  14. */
  15. class OrderRefundService
  16. {
  17. /**
  18. * 执行订单退款
  19. */
  20. public function execute(&$order, $money = null)
  21. {
  22. // 退款金额,如不指定则默认为订单实付款金额
  23. is_null($money) && $money = $order['pay_price'];
  24. // 1.微信支付退款
  25. if ($order['pay_type']['value'] == OrderPayTypeEnum::WECHAT) {
  26. return $this->wxpay($order, $money);
  27. }
  28. // 2.余额支付退款
  29. if ($order['pay_type']['value'] == OrderPayTypeEnum::BALANCE) {
  30. return $this->balance($order, $money);
  31. }
  32. // 3.支付宝退款
  33. if ($order['pay_type']['value'] == OrderPayTypeEnum::ALIPAY) {
  34. return $this->alipay($order, $money);
  35. }
  36. return false;
  37. }
  38. /**
  39. * 余额支付退款
  40. */
  41. private function balance($order, $money)
  42. {
  43. // 回退用户余额
  44. $user = UserModel::detail($order['user_id']);
  45. $user->where('user_id', '=', $order['user_id'])->inc('balance', $money)->update();
  46. log_write('-------------余额退款');
  47. // 记录余额明细
  48. BalanceLogModel::add(BalanceLogSceneEnum::REFUND, [
  49. 'user_id' => $user['user_id'],
  50. 'money' => $money,
  51. 'app_id' => $order['app_id'],
  52. ], ['order_no' => $order['order_no']]);
  53. return true;
  54. }
  55. /**
  56. * 微信支付退款
  57. */
  58. private function wxpay($order, $money)
  59. {
  60. if($order['pay_source'] == 'mp' || $order['pay_source'] == 'payH5'){
  61. $app = AppMp::getWxPayApp($order['app_id']);
  62. }else if($order['pay_source'] == 'wx'){
  63. $app = AppWx::getWxPayApp($order['app_id']);
  64. } else if ($order['pay_source'] == 'app') {
  65. $app = AppOpen::getWxPayApp($order['app_id']);
  66. }
  67. $WxPay = new WxPay($app);
  68. return $WxPay->refund($order['transaction_id'], $order['pay_price'], $money);
  69. }
  70. /**
  71. * 支付宝退款
  72. */
  73. private function alipay($order, $money)
  74. {
  75. $AliPay = new AliPay();
  76. return $AliPay->refund($order['transaction_id'], $order['pay_price'], $money);
  77. }
  78. }