PaymentOrderService.php 15 KB

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