PaymentOrderService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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\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
  136. * @param {*} $account
  137. * @return {*}
  138. */
  139. public static function createPay($memberId,$amount,$channel,$account)
  140. {
  141. $data = [];
  142. $data['type'] = self::TYPE_PAY;
  143. $order_no = self::createOrderNo('sj'.$data['type'].'_', $memberId);
  144. $ret = QianBaoService::pay($amount, $order_no, $channel);
  145. return $ret;
  146. }
  147. /**
  148. * @description: 创建代付订单
  149. * @param {*} $memberId 会员
  150. * @param {*} $amount 金额
  151. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  152. * @param {*} $bank_name 银行名称/支付宝
  153. * @param {*} $account 姓名
  154. * @param {*} $card_no 银行卡号/支付宝账号
  155. * @return {*}
  156. */
  157. public static function createPayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  158. {
  159. $default_amount = $amount;
  160. $result = [];
  161. $result['chat_id'] = $memberId;
  162. if($amount < 100){
  163. $result['text'] = '提现金额最少100';
  164. return $result;
  165. }
  166. if($amount > 49999){
  167. $result['text'] = '提现金额最多49999';
  168. return $result;
  169. }
  170. // 在调用三方支付前开始事务
  171. DB::beginTransaction();
  172. try {
  173. $wallet = WalletService::findOne(['member_id' => $memberId]);
  174. if (!$wallet) {
  175. $result['text'] = '钱包不存在!';
  176. return $result;
  177. }
  178. $balance = $wallet->available_balance;
  179. if (bccomp($balance, $amount, 2) < 0) {
  180. $result['text'] = '您的钱包余额不足!';
  181. return $result;
  182. }
  183. $available_balance = bcsub($balance, $amount, 10);
  184. $data = [];
  185. $data['type'] = self::TYPE_PAYOUT;
  186. $order_no = self::createOrderNo('sj'.$data['type'].'_', $memberId);
  187. $data['order_no'] = $order_no;
  188. $data['member_id'] = $memberId;
  189. $data['free'] = $amount * 0.002 + 2;
  190. $amount = number_format($amount, 2, '.', '');
  191. $data['amount'] = $amount;
  192. $data['channel'] = $channel;
  193. $data['bank_name'] = $bank_name;
  194. $data['account'] = $account;
  195. $data['card_no'] = $card_no;
  196. $data['callback_url'] = QianBaoService::getNotifyUrl();
  197. $data['status'] = self::STATUS_STAY;
  198. $data['remark'] = '提现费率:0.2%+2';
  199. // 先预扣款(锁定资金)
  200. $wallet->available_balance = $available_balance;
  201. if (!$wallet->save()) {
  202. DB::rollBack();
  203. $result['text'] = '钱包更新失败!';
  204. return $result;
  205. }
  206. // 创建待处理状态的提现记录
  207. $info = self::model()::create($data);
  208. $id = $info->id;
  209. // 记录余额变动日志
  210. BalanceLogService::addLog(
  211. $memberId,
  212. $default_amount,
  213. $balance,
  214. $available_balance,
  215. '三方提现',
  216. $id,
  217. '钱宝提现费率:0.2%+2'
  218. );
  219. // 提交事务,确保预扣款成功
  220. DB::commit();
  221. } catch (\Exception $e) {
  222. // 预扣款失败,回滚事务
  223. DB::rollBack();
  224. $result['text'] = '系统繁忙,请稍后重试!';
  225. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  226. 'member_id' => $memberId,
  227. 'amount' => $amount
  228. ]);
  229. return $result;
  230. }
  231. // 调用三方支付接口(在事务外)
  232. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  233. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  234. if ($ret['code'] == 200) {
  235. // 更新提现记录状态为处理中
  236. DB::beginTransaction();
  237. try {
  238. $info->status = self::STATUS_PROCESS;
  239. $info->save();
  240. DB::commit();
  241. $text = "✅ 提现申请已提交!\n\n";
  242. $text .= "钱包余额:{$available_balance} RMB\n";
  243. $text .= "提现金额:{$default_amount} RMB\n";
  244. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  245. $result['text'] = $text;
  246. } catch (\Exception $e) {
  247. DB::rollBack();
  248. // 状态更新失败,但资金已扣款且三方支付已成功
  249. // 这里可以记录告警,需要人工干预
  250. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  251. 'member_id' => $memberId,
  252. 'order_no' => $order_no
  253. ]);
  254. $result['text'] = '提现申请已提交,系统处理中...';
  255. }
  256. } else {
  257. // 三方支付失败,需要回滚之前的预扣款
  258. DB::beginTransaction();
  259. try {
  260. // 恢复钱包余额
  261. $wallet->available_balance = $balance;
  262. $wallet->save();
  263. // 更新提现记录状态为失败
  264. $info->status = self::STATUS_FAIL;
  265. $info->remark = $ret['msg'];
  266. $info->save();
  267. // 记录退款日志
  268. BalanceLogService::addLog(
  269. $memberId,
  270. $default_amount,
  271. $available_balance,
  272. $balance,
  273. '三方提现',
  274. $id,
  275. '提现失败退款'
  276. );
  277. DB::commit();
  278. $result['text'] = $ret['msg'];
  279. } catch (\Exception $e) {
  280. DB::rollBack();
  281. // 回滚失败,需要记录告警,人工干预
  282. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  283. 'member_id' => $memberId,
  284. 'order_no' => $order_no,
  285. 'amount' => $amount
  286. ]);
  287. $result['text'] = '提现失败,请联系客服处理退款!';
  288. }
  289. }
  290. return $result;
  291. }
  292. /**
  293. * @description: 接收三方订单
  294. * @param {*} $params
  295. * @return {*}
  296. */
  297. public static function receiveOrder($params)
  298. {
  299. // 判断商户号是否一致
  300. if($params['merchantNum'] == QianBaoService::getMerchantId()){
  301. $info = self::findOne(['order_no' => $params['orderNo']]);
  302. if($info){
  303. // 判断金额是不是正确认
  304. if($info->amount != $params['amount']){
  305. return 'amount';
  306. }
  307. // 验证签名
  308. $sign = QianBaoService::verifyNotifySign($params['state'],$params['orderNo'],$params['amount']);
  309. if($params['sign'] != $sign){
  310. return false;
  311. }
  312. // 代付
  313. if($info->type == self::TYPE_PAYOUT){
  314. self::onSubmitPayout($params,$info);
  315. }
  316. // 代收
  317. if($info->type == self::TYPE_PAY){
  318. }
  319. }
  320. }
  321. }
  322. /**
  323. * @description: 处理代付订单
  324. * @param {*} $params
  325. * @return {*}
  326. */
  327. public static function onSubmitPayout($params,$info)
  328. {
  329. $memberId = $info->member_id;
  330. $amount = $params['amount'];
  331. $data = [];
  332. $result = [];
  333. $chat_id = $info->member_id;
  334. $data['callback_data'] =json_encode($params,JSON_UNESCAPED_UNICODE);
  335. DB::beginTransaction();
  336. try{
  337. if($params['state'] == 1){
  338. $data['status'] = self::STATUS_SUCCESS;
  339. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  340. if($res){
  341. DB::commit();
  342. $text = "✅ 提现通知 \n";
  343. $text .= "提现平台:{$info->bank_name} \n";
  344. $text .= "收款人:{$info->account} \n";
  345. $text .= "收款卡号:{$info->card_no} \n";
  346. $text .= "提现金额:{$info->amount} \n";
  347. $text .= "提现成功,金额已到账,请注意查收!";
  348. self::sendMessage($chat_id,$text);
  349. }
  350. }else{
  351. $data['status'] = self::STATUS_FAIL;
  352. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  353. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  354. $balance = $wallet->available_balance; // 钱包当前余额
  355. $available_balance = bcadd($balance, $params['amount'], 10);
  356. $wallet->available_balance = $available_balance;
  357. $wallet->save();
  358. // 记录退款日志
  359. BalanceLogService::addLog(
  360. $memberId,
  361. $amount,
  362. $balance,
  363. $available_balance,
  364. '三方提现',
  365. $info->id,
  366. '提现失败退款'
  367. );
  368. if($res){
  369. DB::commit();
  370. $text = "❌ 提现通知 \n";
  371. $text .= "提现平台:{$info->bank_name} \n";
  372. $text .= "收款人:{$info->account} \n";
  373. $text .= "收款卡号:{$info->card_no} \n";
  374. $text .= "提现金额:{$info->amount} \n";
  375. $text .= "提现失败,金额已返回钱包,请注意查收!";
  376. self::sendMessage($chat_id,$text);
  377. }
  378. }
  379. }catch(\Exception $e){
  380. DB::rollBack();
  381. // 回滚失败,需要记录告警,人工干预
  382. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  383. }
  384. }
  385. }