WithdrawTransferService.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace addons\Store\common\services;
  3. use addons\Store\common\models\Store;
  4. use addons\Store\common\models\StoreWithdrawLog;
  5. use common\enums\StatusEnum;
  6. /**
  7. * 提现事务服务
  8. */
  9. class WithdrawTransferService
  10. {
  11. /**
  12. * @param array $data
  13. * @return bool
  14. */
  15. public function refund(array $data): bool
  16. {
  17. $trans = \Yii::$app->db->beginTransaction();
  18. try {
  19. // 根据流水号获取提现记录
  20. $withdrawLog = StoreWithdrawLog::find()->where(['id' => $data['withdrawal_source_id'], 'status' => 1])->one();
  21. if (!$withdrawLog) {
  22. throw new \Exception("提现记录不存在");
  23. }
  24. $withdrawLog->withdraw_status = 2;
  25. if (!$withdrawLog->save()) {
  26. throw new \Exception("提现状态修改失败");
  27. }
  28. $mch = Store::find()->where([
  29. 'id' => $withdrawLog->mch_id,
  30. 'mall_id' => $withdrawLog->mall_id,
  31. 'user_id' => $withdrawLog->user_id,
  32. 'status' => 1
  33. ])->one();
  34. if ($mch) {
  35. $mch->balance += $withdrawLog->num;
  36. if (!$mch->save()) {
  37. throw new \Exception("商户余额修改失败");
  38. }
  39. \Yii::$app->custom->logs("商户提现回退:" . $withdrawLog->user_id, '回退金额:' . $withdrawLog->num);
  40. }
  41. $trans->commit();
  42. return true;
  43. } catch (\Exception $e) {
  44. $trans->rollBack();
  45. \Yii::$app->custom->logs("退款失败", $e->getMessage());
  46. return false;
  47. }
  48. }
  49. /**
  50. * 打款成功
  51. * @return void
  52. * @throws \Exception
  53. */
  54. public static function remit_success($cash, $msg = '打款成功')
  55. {
  56. $content = [];
  57. if ($cash->content) {
  58. $content = json_decode($cash->content, true);
  59. }
  60. $cash->withdraw_status = 1;
  61. $content['remit_at'] = date('Y-m-d H:i:s', time());
  62. $content['remit_content'] = $msg;
  63. $cash->content = json_encode($content);
  64. if (!$cash->save()) {
  65. throw new \Exception("保存提现数据失败");
  66. }
  67. // 添加以支出金额
  68. $storeInfo = Store::findOne(['user_id' => $cash->user_id, 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
  69. $storeInfo->total_expenses += $cash->num;
  70. if (!$storeInfo->save()) {
  71. throw new \Exception("保存提现数据失败");
  72. }
  73. }
  74. public static function remit_fail($cash, $msg = '打款失败')
  75. {
  76. $content = empty($cash->content) ? [] : json_decode($cash->content, true);
  77. $content['remit_content'] = $msg;
  78. $res = StoreWithdrawLog::updateAll([
  79. 'withdraw_status' => 0,
  80. 'content' => json_encode($content),
  81. 'updated_at' => time()
  82. ], ['id' => $cash->id]);
  83. }
  84. }