PaymentOrderService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. namespace App\Services;
  3. use App\Services\BaseService;
  4. use App\Models\PaymentOrder;
  5. use App\Models\Config;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Services\Payment\SanJinService;
  11. use App\Services\WalletService;
  12. use App\Services\BalanceLogService;
  13. /**
  14. * 投注
  15. */
  16. class PaymentOrderService extends BaseService
  17. {
  18. const TYPE_PAY = 1; // 代收
  19. const TYPE_PAYOUT = 2; // 代付
  20. const STATUS_STAY = 0; // 待处理
  21. const STATUS_PROCESS = 1; // 处理中
  22. const STATUS_SUCCESS = 2; // 成功
  23. const STATUS_FAIL = 3; // 失败
  24. /**
  25. * @description: 模型
  26. * @return {string}
  27. */
  28. public static function model() :string
  29. {
  30. return PaymentOrder::class;
  31. }
  32. /**
  33. * @description: 枚举
  34. * @return {*}
  35. */
  36. public static function enum() :string
  37. {
  38. return '';
  39. }
  40. /**
  41. * @description: 获取查询条件
  42. * @param {array} $search 查询内容
  43. * @return {array}
  44. */
  45. public static function getWhere(array $search = []) :array
  46. {
  47. $where = [];
  48. if(isset($search['member_id']) && !empty($search['member_id'])){
  49. $where[] = ['member_id', '=', $search['member_id']];
  50. }
  51. if(isset($search['type']) && !empty($search['type'])){
  52. $where[] = ['type', '=', $search['type']];
  53. }
  54. if(isset($search['channel']) && !empty($search['channel'])){
  55. $where[] = ['channel', '=', $search['channel']];
  56. }
  57. if(isset($search['order_no']) && !empty($search['order_no'])){
  58. $where[] = ['order_no', '=', $search['order_no']];
  59. }
  60. if(isset($search['id']) && !empty($search['id'])){
  61. $where[] = ['id', '=', $search['id']];
  62. }
  63. if(isset($search['status']) && $search['status'] != ''){
  64. $where[] = ['status', '=', $search['status']];
  65. }
  66. return $where;
  67. }
  68. /**
  69. * @description: 查询单条数据
  70. * @param array $search
  71. * @return \App\Models\Coin|null
  72. */
  73. public static function findOne(array $search): ?PaymentOrder
  74. {
  75. return self::model()::where(self::getWhere($search))->first();
  76. }
  77. /**
  78. * @description: 查询所有数据
  79. * @param array $search
  80. * @return \Illuminate\Database\Eloquent\Collection
  81. */
  82. public static function findAll(array $search = [])
  83. {
  84. return self::model()::where(self::getWhere($search))->get();
  85. }
  86. /**
  87. * @description: 分页查询
  88. * @param array $search
  89. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  90. */
  91. public static function paginate(array $search = [])
  92. {
  93. $limit = isset($search['limit'])?$search['limit']:15;
  94. $paginator = self::model()::where(self::getWhere($search))->paginate($limit);
  95. return ['total' => $paginator->total(), 'data' => $paginator->items()];
  96. }
  97. /**
  98. * @description:
  99. * @param {*} $params
  100. * @return {*}
  101. */
  102. public static function submit($params = [])
  103. {
  104. $result = false;
  105. $msg['code'] = self::NOT;
  106. $msg['msg'] = '';
  107. // 2. 判断是否是更新
  108. if (!empty($params['id'])) {
  109. // 更新
  110. $info = self::findOne(['id'=>$params['id']] );
  111. if (!$info) {
  112. $msg['msg'] = '数据不存在!';
  113. }else{
  114. $result = $info->update($params);
  115. $id = $params['id'];
  116. }
  117. } else {
  118. // 创建
  119. $result = $info = self::model()::create($params);
  120. $id = $result->id;
  121. }
  122. if($result){
  123. $msg['code'] = self::YES;
  124. $msg['msg'] = '设置成功';
  125. $msg['key'] = $id;
  126. }else{
  127. $msg['msg'] = empty($msg['msg']) ?'操作失败':$msg['msg'];
  128. }
  129. return $msg;
  130. }
  131. /**
  132. * @description: 创建代付订单
  133. * @param {*} $memberId 会员
  134. * @param {*} $amount 金额
  135. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  136. * @param {*} $bank_name 银行名称/支付宝
  137. * @param {*} $account 姓名
  138. * @param {*} $card_no 银行卡号/支付宝账号
  139. * @return {*}
  140. */
  141. public static function createPayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  142. {
  143. $default_amount = $amount;
  144. $result = [];
  145. $result['chat_id'] = $memberId;
  146. if($amount < 100){
  147. $result['text'] = '提现金额最少100';
  148. return $result;
  149. }
  150. if($amount > 49999){
  151. $result['text'] = '提现金额最多49999';
  152. return $result;
  153. }
  154. // 在调用三方支付前开始事务
  155. DB::beginTransaction();
  156. try {
  157. $wallet = WalletService::findOne(['member_id' => $memberId]);
  158. if (!$wallet) {
  159. $result['text'] = '钱包不存在!';
  160. return $result;
  161. }
  162. $balance = $wallet->available_balance;
  163. if (bccomp($balance, $amount, 2) < 0) {
  164. $result['text'] = '您的钱包余额不足!';
  165. return $result;
  166. }
  167. $available_balance = bcsub($balance, $amount, 10);
  168. $data = [];
  169. $data['type'] = self::TYPE_PAYOUT;
  170. $order_no = self::createOrderNo('sj'.$data['type'].'_', $memberId);
  171. $data['order_no'] = $order_no;
  172. $data['member_id'] = $memberId;
  173. $data['free'] = $amount * 0.002 + 2;
  174. $amount = number_format($amount, 2, '.', '');
  175. $data['amount'] = $amount;
  176. $data['channel'] = $channel;
  177. $data['bank_name'] = $bank_name;
  178. $data['account'] = $account;
  179. $data['card_no'] = $card_no;
  180. $data['callback_url'] = SanJinService::getNotifyUrl();
  181. $data['status'] = self::STATUS_STAY;
  182. $data['remark'] = '提现费率:0.2%+2';
  183. // 先预扣款(锁定资金)
  184. $wallet->available_balance = $available_balance;
  185. if (!$wallet->save()) {
  186. DB::rollBack();
  187. $result['text'] = '钱包更新失败!';
  188. return $result;
  189. }
  190. // 创建待处理状态的提现记录
  191. $info = self::model()::create($data);
  192. $id = $info->id;
  193. // 记录余额变动日志
  194. BalanceLogService::addLog(
  195. $memberId,
  196. $default_amount,
  197. $balance,
  198. $available_balance,
  199. '三方提现',
  200. $id,
  201. '钱宝提现费率:0.2%+2'
  202. );
  203. // 提交事务,确保预扣款成功
  204. DB::commit();
  205. } catch (\Exception $e) {
  206. // 预扣款失败,回滚事务
  207. DB::rollBack();
  208. $result['text'] = '系统繁忙,请稍后重试!';
  209. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  210. 'member_id' => $memberId,
  211. 'amount' => $amount
  212. ]);
  213. return $result;
  214. }
  215. // 调用三方支付接口(在事务外)
  216. $ret = SanJinService::payout($amount, $order_no, $bank_name, $account, $card_no);
  217. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  218. if ($ret['code'] == 200) {
  219. // 更新提现记录状态为处理中
  220. DB::beginTransaction();
  221. try {
  222. $info->status = self::STATUS_PROCESS;
  223. $info->save();
  224. DB::commit();
  225. $text = "✅ 提现申请已提交!\n\n";
  226. $text .= "钱包余额:{$available_balance} RMB\n";
  227. $text .= "提现金额:{$default_amount} RMB\n";
  228. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  229. $result['text'] = $text;
  230. } catch (\Exception $e) {
  231. DB::rollBack();
  232. // 状态更新失败,但资金已扣款且三方支付已成功
  233. // 这里可以记录告警,需要人工干预
  234. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  235. 'member_id' => $memberId,
  236. 'order_no' => $order_no
  237. ]);
  238. $result['text'] = '提现申请已提交,系统处理中...';
  239. }
  240. } else {
  241. // 三方支付失败,需要回滚之前的预扣款
  242. DB::beginTransaction();
  243. try {
  244. // 恢复钱包余额
  245. $wallet->available_balance = $balance;
  246. $wallet->save();
  247. // 更新提现记录状态为失败
  248. $info->status = self::STATUS_FAIL;
  249. $info->remark = $ret['msg'];
  250. $info->save();
  251. // 记录退款日志
  252. BalanceLogService::addLog(
  253. $memberId,
  254. $default_amount,
  255. $available_balance,
  256. $balance,
  257. '三方提现',
  258. $id,
  259. '提现失败退款'
  260. );
  261. DB::commit();
  262. $result['text'] = $ret['msg'];
  263. } catch (\Exception $e) {
  264. DB::rollBack();
  265. // 回滚失败,需要记录告警,人工干预
  266. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  267. 'member_id' => $memberId,
  268. 'order_no' => $order_no,
  269. 'amount' => $amount
  270. ]);
  271. $result['text'] = '提现失败,请联系客服处理退款!';
  272. }
  273. }
  274. return $result;
  275. }
  276. /**
  277. * @description: 接收三方订单
  278. * @param {*} $params
  279. * @return {*}
  280. */
  281. public static function receiveOrder($params)
  282. {
  283. // 判断商户号是否一致
  284. if($params['merchantNum'] == SanJinService::getMerchantId()){
  285. $info = self::findOne(['order_no' => $params['orderNo']]);
  286. if($info){
  287. // 判断金额是不是正确认
  288. if($info->amount != $params['amount']){
  289. return 'amount';
  290. }
  291. // 验证签名
  292. $sign = SanJinService::verifyNotifySign($params['state'],$params['orderNo'],$params['amount']);
  293. if($params['sign'] != $sign){
  294. return false;
  295. }
  296. $params['state'] = 0;
  297. // 代付
  298. if($info->type == self::TYPE_PAYOUT){
  299. self::onSubmitPayout($params,$info);
  300. }
  301. // 代收
  302. if($info->type == self::TYPE_PAY){
  303. }
  304. }
  305. }
  306. }
  307. /**
  308. * @description: 处理代付订单
  309. * @param {*} $params
  310. * @return {*}
  311. */
  312. public static function onSubmitPayout($params,$info)
  313. {
  314. $memberId = $info->member_id;
  315. $amount = $params['amount'];
  316. $data = [];
  317. $result = [];
  318. $chat_id = $info->member_id;
  319. $data['callback_data'] =json_encode($params,JSON_UNESCAPED_UNICODE);
  320. DB::beginTransaction();
  321. try{
  322. if($params['state'] == 1){
  323. $data['status'] = self::STATUS_SUCCESS;
  324. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  325. if($res){
  326. DB::commit();
  327. $text = "✅ 提现通知 \n";
  328. $text .= "提现平台:{$info->bank_name} \n";
  329. $text .= "收款人:{$info->account} \n";
  330. $text .= "收款卡号:{$info->card_no} \n";
  331. $text .= "提现金额:{$info->amount} \n";
  332. $text .= "提现成功,金额已到账,请注意查收!";
  333. self::sendMessage($chat_id,$text);
  334. }
  335. }else{
  336. $data['status'] = self::STATUS_FAIL;
  337. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  338. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  339. $balance = $wallet->available_balance; // 钱包当前余额
  340. $available_balance = bcadd($balance, $params['amount'], 10);
  341. $wallet->available_balance = $available_balance;
  342. $wallet->save();
  343. // 记录退款日志
  344. BalanceLogService::addLog(
  345. $memberId,
  346. $amount,
  347. $balance,
  348. $available_balance,
  349. '三方提现',
  350. $info->id,
  351. '提现失败退款'
  352. );
  353. if($res){
  354. DB::commit();
  355. $text = "❌ 提现通知 \n";
  356. $text .= "提现平台:{$info->bank_name} \n";
  357. $text .= "收款人:{$info->account} \n";
  358. $text .= "收款卡号:{$info->card_no} \n";
  359. $text .= "提现金额:{$info->amount} \n";
  360. $text .= "提现失败,金额已返回钱包,请注意查收!";
  361. self::sendMessage($chat_id,$text);
  362. }
  363. }
  364. }catch(\Exception $e){
  365. DB::rollBack();
  366. // 回滚失败,需要记录告警,人工干预
  367. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  368. }
  369. }
  370. }