PaymentOrderService.php 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Models\PaymentOrder;
  5. use App\Models\User;
  6. use App\Models\Wallet as WalletModel;
  7. use Exception;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Services\Payment\JdPayService;
  11. use App\Services\Payment\NoPayService;
  12. use App\Services\Payment\QianBaoService;
  13. use App\Services\Payment\SanJinService;
  14. use App\Services\ConfigService;
  15. /**
  16. * 投注
  17. */
  18. class PaymentOrderService extends BaseService
  19. {
  20. const TYPE_PAY = 1; // 代收
  21. const TYPE_PAYOUT = 2; // 代付
  22. const TYPE_SELF_PAY = 3; // 手动充值
  23. const TYPE_SELF_PAYOUT = 4; // 手动提现打款
  24. const STATUS_STAY = 0; // 待处理
  25. const STATUS_PROCESS = 1; // 处理中
  26. const STATUS_SUCCESS = 2; // 成功
  27. const STATUS_FAIL = 3; // 失败
  28. const STATUS_USER = 4; // 待用户提交凭证
  29. const STATUS_AUDIT = 5; //待人工审核
  30. const STATUS_CANCEL = 6; //已撤回
  31. public static string $MODEL = PaymentOrder::class;
  32. /**
  33. * @description: 模型
  34. * @return {string}
  35. */
  36. public static function model(): string
  37. {
  38. return PaymentOrder::class;
  39. }
  40. /**
  41. * @description: 枚举
  42. * @return {*}
  43. */
  44. public static function enum(): string
  45. {
  46. return '';
  47. }
  48. /**
  49. * @description: 获取查询条件
  50. * @param {array} $search 查询内容
  51. * @return {array}
  52. */
  53. public static function getWhere(array $search = []): array
  54. {
  55. $where = [];
  56. if (isset($search['member_id']) && !empty($search['member_id'])) {
  57. $where[] = ['payment_orders.member_id', '=', $search['member_id']];
  58. }
  59. if (isset($search['channel']) && !empty($search['channel'])) {
  60. if ($search['channel'] == 'rgcz') {
  61. $search['type'] = 3;
  62. }
  63. $where[] = ['payment_orders.channel', '=', $search['channel']];
  64. }
  65. if (isset($search['type']) && !empty($search['type'])) {
  66. $where[] = ['payment_orders.type', '=', $search['type']];
  67. }
  68. if (isset($search['order_no']) && !empty($search['order_no'])) {
  69. $where[] = ['payment_orders.order_no', '=', $search['order_no']];
  70. }
  71. if (isset($search['id']) && !empty($search['id'])) {
  72. $where[] = ['payment_orders.id', '=', $search['id']];
  73. }
  74. if (isset($search['status']) && $search['status'] != '') {
  75. $where[] = ['payment_orders.status', '=', $search['status']];
  76. }
  77. if (isset($search['first_name']) && !empty($search['first_name'])) {
  78. $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
  79. }
  80. if (isset($search['payment_type']) && $search['payment_type'] != '') {
  81. $where[] = ['payment_orders.payment_type', '=', $search['payment_type']];
  82. }
  83. return $where;
  84. }
  85. /**
  86. * @description: 查询单条数据
  87. * @param array $search
  88. * @return \App\Models\Coin|null
  89. */
  90. public static function findOne(array $search): ?PaymentOrder
  91. {
  92. return static::$MODEL::where(self::getWhere($search))->first();
  93. }
  94. /**
  95. * @description: 查询所有数据
  96. * @param array $search
  97. * @return \Illuminate\Database\Eloquent\Collection
  98. */
  99. public static function findAll(array $search = [])
  100. {
  101. return static::$MODEL::where(self::getWhere($search))->get();
  102. }
  103. /**
  104. * @description: 分页查询
  105. * @param array $search
  106. * @return array
  107. */
  108. public static function paginate(array $search = [])
  109. {
  110. $limit = isset($search['limit']) ? $search['limit'] : 15;
  111. $paginator = static::$MODEL::where(self::getWhere($search))
  112. ->join('users', 'users.member_id', '=', 'payment_orders.member_id')
  113. ->select("payment_orders.*", "users.first_name","users.admin_note as user_admin_note") // 提前查好需要的字段
  114. ->orderByDesc('payment_orders.created_at')
  115. ->paginate($limit);
  116. $totalAmount = 0;
  117. $totalSuccess = 0;
  118. $totalFail = 0;
  119. $list = $paginator->items();
  120. foreach ($list as $item) {
  121. $item['amount'] = floatval($item['amount']);
  122. $totalAmount += $item['amount'];
  123. if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
  124. if ($item['status'] == 3) $totalFail += $item['amount'];
  125. }
  126. return [
  127. 'total' => $paginator->total(),
  128. 'total_amount' => $totalAmount,
  129. 'total_success' => $totalSuccess,
  130. 'total_fail' => $totalFail,
  131. 'data' => $list
  132. ];
  133. }
  134. /**
  135. * @description:
  136. * @param {*} $params
  137. * @return {*}
  138. */
  139. public static function submit($params = [])
  140. {
  141. $result = false;
  142. $msg['code'] = self::NOT;
  143. $msg['msg'] = '';
  144. // 2. 判断是否是更新
  145. if (!empty($params['id'])) {
  146. // 更新
  147. $info = self::findOne(['id' => $params['id']]);
  148. if (!$info) {
  149. $msg['msg'] = '数据不存在!';
  150. } else {
  151. $result = $info->update($params);
  152. $id = $params['id'];
  153. }
  154. } else {
  155. // 创建
  156. $result = $info = static::$MODEL::create($params);
  157. $id = $result->id;
  158. }
  159. if ($result) {
  160. $msg['code'] = self::YES;
  161. $msg['msg'] = '设置成功';
  162. $msg['key'] = $id;
  163. } else {
  164. $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
  165. }
  166. return $msg;
  167. }
  168. /**
  169. * @description: 创建代收订单
  170. * @param {*} $memberId
  171. * @param {*} $amount
  172. * @param {*} $paymentType 支付类型:支付宝、数字人民币
  173. * @return {*}
  174. */
  175. public static function createPay($memberId, $amount, $paymentType)
  176. {
  177. $result = [];
  178. $result['chat_id'] = $memberId;
  179. $result['code'] = 0;
  180. $result['url'] = '';
  181. $channel = ''; // 支付的通道
  182. $product = SanJinService::product();
  183. $max = 0;
  184. $min = 0;
  185. $rate = 0;
  186. $selectedProduct = null;
  187. $geText = '';
  188. foreach ($product as $k => $v) {
  189. if ($v['type'] == $paymentType) {
  190. $selectedProduct = $v;
  191. if ($v['type'] == 'zfbge') {
  192. if (in_array($amount, $v['fixed'])) {
  193. $channel = $k;
  194. } else {
  195. $geText .= "❌ 此充值通道固定充值金额为" . implode(',', $v['fixed']) . "请务必输入区间金额!";
  196. }
  197. } else {
  198. if ($amount >= $v['min'] && $amount <= $v['max']) {
  199. $channel = $k;
  200. $rate = $v['rate'];
  201. }
  202. if ($min == 0) {
  203. $min = $v['min'];
  204. }
  205. if ($max == 0) {
  206. $max = $v['max'];
  207. }
  208. if ($min > $v['min']) {
  209. $min = $v['min'];
  210. }
  211. if ($max < $v['max']) {
  212. $max = $v['max'];
  213. }
  214. }
  215. }
  216. }
  217. // 没有找到支付通道
  218. if (empty($channel) && !JdPayService::isChannel($paymentType) && !NoPayService::isRechargeChannel($paymentType)) {
  219. // $text = "发起充值失败 \n";
  220. // $text .= "最低充值:" . $min . " \n";
  221. // $text .= "最高充值:" . $max . " \n";
  222. // $text .= "请重新填写充值的金额!";
  223. $text = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
  224. $result['text'] = $text;
  225. if ($geText) {
  226. $result['text'] = $geText;
  227. }
  228. $result['code'] = 20001;
  229. return $result;
  230. }
  231. if (NoPayService::isRechargeChannel($paymentType) || NoPayService::isRechargeChannel($channel)) {
  232. $channel = NoPayService::isRechargeChannel($paymentType) ? $paymentType : $channel;
  233. $bankName = $selectedProduct['name'] ?? 'NO快捷充值';
  234. $data = [];
  235. $data['type'] = self::TYPE_PAY;
  236. $data['member_id'] = $memberId;
  237. $data['amount'] = NoPayService::amount($amount);
  238. $data['channel'] = $channel;
  239. $data['fee'] = $amount * $rate;
  240. $data['bank_name'] = $bankName;
  241. $order_no = self::createOrderNo('no' . $data['type'] . '_', $memberId);
  242. $data['order_no'] = $order_no;
  243. $data['callback_url'] = NoPayService::getDepositNotifyUrl();
  244. $data['remark'] = '充值费率:' . $rate;
  245. $data['status'] = self::STATUS_STAY;
  246. $ret = NoPayService::pay($amount, $order_no, (string)$memberId, $channel);
  247. Log::channel('payment')->info('NO支付发起', [
  248. 'order_no' => $order_no,
  249. 'member_id' => $memberId,
  250. 'amount' => $data['amount'],
  251. 'channel' => $channel,
  252. 'response' => $ret,
  253. ]);
  254. if (($ret['code'] ?? -1) == 0) {
  255. $payUrl = $ret['data']['url'] ?? '';
  256. $data['status'] = self::STATUS_PROCESS;
  257. $data['pay_url'] = $payUrl;
  258. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  259. static::$MODEL::create($data);
  260. if ($payUrl) {
  261. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  262. }
  263. $result['text'] = "{$bankName}充值确认 \n";
  264. $result['text'] .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  265. $result['text'] .= "支付地址:{$payUrl}\n";
  266. $result['text'] .= "支付金额:" . $amount . " RMB \n";
  267. $result['text'] .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  268. $result['url'] = $payUrl;
  269. } else {
  270. $result['text'] = $ret['msg'] ?? 'NO支付发起失败';
  271. $result['code'] = 20002;
  272. }
  273. return $result;
  274. }
  275. if (JdPayService::isChannel($paymentType) || JdPayService::isChannel($channel)) {
  276. $channel = JdPayService::CHANNEL;
  277. $bankName = $selectedProduct['name'] ?? 'JD钱包';
  278. $data = [];
  279. $data['type'] = self::TYPE_PAY;
  280. $data['member_id'] = $memberId;
  281. $data['amount'] = JdPayService::amount($amount);
  282. $data['channel'] = $channel;
  283. $data['fee'] = $amount * $rate;
  284. $data['bank_name'] = $bankName;
  285. $order_no = self::createOrderNo('jd' . $data['type'] . '_', $memberId);
  286. $data['order_no'] = $order_no;
  287. $data['callback_url'] = JdPayService::getNotifyUrl();
  288. $data['remark'] = '充值费率:' . $rate;
  289. $data['status'] = self::STATUS_STAY;
  290. $ret = JdPayService::pay($amount, $order_no);
  291. Log::channel('payment')->info('JD支付发起', $ret);
  292. if (($ret['code'] ?? 0) == 200) {
  293. $item = $ret['data'] ?? [];
  294. $payUrl = $item['url'] ?? '';
  295. $data['status'] = self::STATUS_PROCESS;
  296. $data['pay_no'] = $item['orderNo'] ?? '';
  297. $data['pay_url'] = $payUrl;
  298. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  299. static::$MODEL::create($data);
  300. if ($payUrl) {
  301. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  302. }
  303. $text = "{$bankName}充值确认 \n";
  304. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  305. $text .= "支付地址:{$payUrl}\n";
  306. $text .= "支付金额:" . $amount . " RMB \n";
  307. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  308. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  309. $result['text'] = $text;
  310. $result['url'] = $payUrl;
  311. } else {
  312. $result['text'] = $ret['message'] ?? 'JD支付发起失败';
  313. $result['code'] = 20002;
  314. }
  315. return $result;
  316. }
  317. $data = [];
  318. $data['type'] = self::TYPE_PAY;
  319. $data['member_id'] = $memberId;
  320. $data['amount'] = $amount;
  321. $data['channel'] = $channel;
  322. $data['fee'] = $amount * $rate;
  323. $data['bank_name'] = SanJinService::getChannel($paymentType) ?? '';
  324. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  325. $data['order_no'] = $order_no;
  326. $data['callback_url'] = SanJinService::getNotifyUrl();
  327. $data['remark'] = '充值费率:' . $rate;
  328. $data['status'] = self::STATUS_STAY;
  329. $ret = SanJinService::pay(($amount * 100), $order_no, $channel);
  330. Log::error('三斤支付发起:', $ret);
  331. if ($ret['code'] == 0) {
  332. $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
  333. $result['image'] = $qrCode;
  334. $item = $ret['data'];
  335. $data['status'] = self::STATUS_PROCESS;
  336. $data['pay_no'] = $item['tradeNo'];
  337. $data['pay_url'] = $item['payUrl'];
  338. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  339. $info = static::$MODEL::create($data);
  340. // $text = "✅ 支付提示 \n";
  341. $text = "{$data['bank_name']}充值确认 \n";
  342. // $text .= "支付方式:{$data['bank_name']} \n";
  343. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  344. $text .= "支付地址:{$ret['data']['payUrl']}\n";
  345. $text .= "支付金额:" . $amount . " RMB \n";
  346. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  347. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  348. $result['text'] = $text;
  349. $result['url'] = $ret['data']['payUrl'];
  350. } else {
  351. $result['text'] = $ret['message'];
  352. $result['code'] = 20002;
  353. }
  354. return $result;
  355. }
  356. /**
  357. * @description: 接收支付的通知
  358. * @param {*} $params
  359. * @return {*}
  360. */
  361. public static function receivePay($params)
  362. {
  363. if (NoPayService::getDepositMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getDepositMerchantId()) {
  364. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  365. if (!$info || $info->type != self::TYPE_PAY || !NoPayService::isRechargeChannel($info->channel)) {
  366. Log::error('NO钱包充值回调订单不存在或类型不匹配', [
  367. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  368. 'order_id' => $info->id ?? null,
  369. 'order_type' => $info->type ?? null,
  370. 'channel' => $info->channel ?? null,
  371. ]);
  372. return false;
  373. }
  374. if (!NoPayService::verifyDepositNotify($params)) {
  375. Log::error('NO钱包充值回调验签失败', [
  376. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  377. 'app_id' => $params['appId'] ?? '',
  378. 'signature' => NoPayService::depositNotifySignatureDiagnostics($params),
  379. ]);
  380. return false;
  381. }
  382. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  383. Log::error('NO钱包充值回调金额不一致', [
  384. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  385. 'order_amount' => $info->amount,
  386. 'callback_amount' => $params['amount'] ?? null,
  387. ]);
  388. return false;
  389. }
  390. if ($info->status != self::STATUS_PROCESS) {
  391. return true;
  392. }
  393. $processed = self::applyPayCallback(
  394. $info,
  395. NoPayService::amount($info->amount),
  396. (string)$params['state'],
  397. NoPayService::STATE_SUCCESS,
  398. NoPayService::STATE_FAIL,
  399. $params
  400. );
  401. if ($processed && (string)$params['state'] === NoPayService::STATE_SUCCESS) {
  402. self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
  403. }
  404. return true;
  405. }
  406. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  407. $info = self::findOne(['order_no' => $params['orderCode'] ?? ''])
  408. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  409. if (!$info || $info->type != self::TYPE_PAY) {
  410. return false;
  411. }
  412. if (!JdPayService::verifyPayNotify($params)) {
  413. return false;
  414. }
  415. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  416. return false;
  417. }
  418. if ($info->status != self::STATUS_PROCESS) {
  419. return true;
  420. }
  421. $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), (string)$params['status'], JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $params);
  422. if ($processed && (string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
  423. $text = "✅ 支付成功 \n";
  424. $text .= "充值金额:{$info->amount} RMB \n";
  425. $text .= "订单号:{$info->order_no} \n";
  426. $text .= "您充值的金额已到账,请注意查收!";
  427. self::notifyUser($info->member_id, $text);
  428. }
  429. return true;
  430. }
  431. // 判断商户号
  432. if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
  433. $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
  434. $info = self::findOne(['order_no' => $params['outTradeNo']]);
  435. if ($info) {
  436. // 平台以分计算转成元
  437. $payAmount = $params['payAmount'] / 100;
  438. // 判断金额是不是正确认
  439. if ($info->amount != $payAmount) {
  440. $text = '❌ 支付失败提醒 \n';
  441. $text .= "订单金额:{$info->amount} \n";
  442. $text .= "实际支付:{$payAmount} \n";
  443. $text .= "订单号:{$params['outTradeNo']} \n";
  444. $text .= "失败原因:支付金额与订单金额不一致 \n";
  445. $text .= "请联系客服处理!";
  446. self::notifyUser($info->member_id, $text);
  447. return false;
  448. }
  449. if ($params['sign'] != SanJinService::signature($params, $must)) {
  450. return false;
  451. }
  452. if ($info->status != self::STATUS_PROCESS) {
  453. return false;
  454. }
  455. // 付款
  456. if ($info->type == self::TYPE_PAY) {
  457. $processed = self::applyPayCallback($info, $payAmount, (string)$params['state'], '1', null, $params);
  458. if ($processed && $params['state'] == 1) {
  459. $text = "✅ 支付成功 \n";
  460. $text .= "充值金额:{$payAmount} RMB \n";
  461. $text .= "订单号:{$params['outTradeNo']} \n";
  462. $text .= "您充值的金额已到账,请注意查收!";
  463. self::notifyUser($info->member_id, $text);
  464. } else {
  465. $text = "❌ 支付失败 \n";
  466. $text .= "充值金额:{$payAmount} RMB \n";
  467. $text .= "订单号:{$params['outTradeNo']} \n";
  468. }
  469. return true;
  470. }
  471. }
  472. }
  473. }
  474. // 充值笔笔返
  475. public static function rechargesBibiReturn($memberId,$payAmount,$info_id)
  476. {
  477. $rate = ConfigService::getVal('recharges_bibi_return');
  478. $amount = $payAmount * $rate;
  479. if($rate > 0){
  480. $wallet = WalletService::findOne(['member_id' => $memberId]);
  481. $balance = $wallet->available_balance;
  482. $available_balance = bcadd($balance, $amount, 10);
  483. $wallet->available_balance = $available_balance;
  484. $wallet->save();
  485. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '优惠活动', $info_id, '充值笔笔返');
  486. }
  487. }
  488. private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
  489. {
  490. return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
  491. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  492. if (!$order || $order->status != self::STATUS_PROCESS) {
  493. return false;
  494. }
  495. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  496. $order->state = $status;
  497. if ($status === $successStatus) {
  498. $order->status = self::STATUS_SUCCESS;
  499. $order->save();
  500. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  501. if (!$wallet) {
  502. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  503. }
  504. $balance = $wallet->available_balance;
  505. $availableBalance = bcadd($balance, $payAmount, 10);
  506. $wallet->available_balance = $availableBalance;
  507. $wallet->save();
  508. BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
  509. $rate = ConfigService::getVal('recharges_bibi_return');
  510. $bonusAmount = $payAmount * $rate;
  511. if ($rate > 0 && $bonusAmount > 0) {
  512. $bonusBeforeBalance = $wallet->available_balance;
  513. $bonusAfterBalance = bcadd($bonusBeforeBalance, $bonusAmount, 10);
  514. $wallet->available_balance = $bonusAfterBalance;
  515. $wallet->save();
  516. BalanceLogService::addLog($order->member_id, $bonusAmount, $bonusBeforeBalance, $bonusAfterBalance, '优惠活动', $order->id, '充值笔笔返');
  517. }
  518. return true;
  519. }
  520. if ($failStatus === null || $status === $failStatus) {
  521. $order->status = self::STATUS_FAIL;
  522. }
  523. $order->save();
  524. return true;
  525. }, 3);
  526. }
  527. /**
  528. * 拒绝提现
  529. * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
  530. * @param int $orderId 订单ID PaymentOrder 表的ID
  531. * @param string $remark 失败原因
  532. * @return array
  533. */
  534. public static function withdrawalFailed($orderId, $remark): array
  535. {
  536. try {
  537. $order = PaymentOrder::where('id', $orderId)
  538. ->whereIn('type', [2,4])
  539. ->where('status', self::STATUS_STAY)
  540. ->first();
  541. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  542. // 更新提现记录状态为失败
  543. $order->status = self::STATUS_FAIL;
  544. $order->remark = $remark;
  545. if (!$order->save()) {
  546. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  547. }
  548. //钱包余额增加
  549. $wallet = WalletService::findOne(['member_id' => $order->member_id]);
  550. $beforeBalance = $wallet->available_balance;
  551. $availableBalance = bcadd($wallet->available_balance, $order->amount, 10);
  552. $wallet->available_balance = $availableBalance;
  553. if (!$wallet->save()) {
  554. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  555. }
  556. // 记录退款日志
  557. BalanceLogService::addLog($order->member_id, $order->amount, $beforeBalance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  558. } catch (Exception $e) {
  559. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  560. }
  561. return ['code' => 0, 'msg' => 'ok'];
  562. }
  563. /**
  564. * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
  565. * @param int $orderId PaymentOrder 表的ID
  566. */
  567. public static function createPayout(int $orderId): array
  568. {
  569. try {
  570. $order = PaymentOrder::where('id', $orderId)
  571. ->where('type', 2)
  572. ->where('status', self::STATUS_STAY)
  573. ->first();
  574. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  575. $amount = $order->amount;
  576. $amount = number_format($amount, 2, '.', '');
  577. if (NoPayService::isWithdrawChannel($order->channel)) {
  578. $ret = NoPayService::withdraw($amount, $order->order_no, (string)$order->member_id, (string)$order->account, (string)$order->card_no);
  579. Log::channel('payment')->info('NO提现接口调用', [
  580. 'order_id' => $order->id,
  581. 'order_no' => $order->order_no,
  582. 'member_id' => $order->member_id,
  583. 'amount' => $amount,
  584. 'q_account' => $order->card_no,
  585. 'response' => $ret,
  586. ]);
  587. if (($ret['code'] ?? -1) != 0) {
  588. throw new Exception($ret['msg'] ?? 'NO提现失败', HttpStatus::CUSTOM_ERROR);
  589. }
  590. $order->pay_no = $ret['data']['orderNo'] ?? '';
  591. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  592. } elseif (JdPayService::isChannel($order->channel)) {
  593. self::assertJdBalanceEnough($amount, [
  594. 'order_id' => $order->id,
  595. 'order_no' => $order->order_no,
  596. 'member_id' => $order->member_id,
  597. 'address' => $order->card_no,
  598. ]);
  599. $ret = JdPayService::remit($amount, $order->order_no, $order->card_no);
  600. Log::channel('payment')->info('JD下发接口调用', [
  601. 'order_id' => $order->id,
  602. 'order_no' => $order->order_no,
  603. 'member_id' => $order->member_id,
  604. 'amount' => $amount,
  605. 'address' => $order->card_no,
  606. 'response' => $ret,
  607. ]);
  608. if (($ret['code'] ?? 0) != 200) {
  609. $logContext = [
  610. 'order_id' => $order->id,
  611. 'order_no' => $order->order_no,
  612. 'member_id' => $order->member_id,
  613. 'amount' => $amount,
  614. 'address' => $order->card_no,
  615. 'response' => $ret,
  616. ];
  617. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  618. Log::error('JD下发接口失败', $logContext);
  619. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  620. }
  621. $order->pay_no = $ret['data']['orderNo'] ?? '';
  622. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  623. } else {
  624. $ret = QianBaoService::payout($amount, $order->order_no, $order->bank_name, $order->account, $order->card_no);
  625. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  626. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  627. }
  628. $order->status = self::STATUS_PROCESS;
  629. $order->save();
  630. } catch (Exception $e) {
  631. Log::channel('payment_error')->error('创建代付订单失败', [
  632. 'order_id' => $orderId,
  633. 'error' => $e->getMessage(),
  634. ]);
  635. Log::error('创建代付订单失败', [
  636. 'order_id' => $orderId,
  637. 'error' => $e->getMessage(),
  638. ]);
  639. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  640. }
  641. return ['code' => 0, 'msg' => 'ok'];
  642. }
  643. /**
  644. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  645. * @param {*} $memberId 会员ID
  646. * @param {*} $amount 代付金额
  647. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  648. * @param {*} $bank_name 银行名称/支付宝
  649. * @param {*} $account 姓名
  650. * @param {*} $card_no 银行卡号/支付宝账号
  651. * @return {*}
  652. */
  653. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  654. {
  655. $default_amount = $amount;
  656. $result = [];
  657. $result['chat_id'] = $memberId;
  658. if ($amount < 100) {
  659. $result['text'] = '提现金额最少100';
  660. return $result;
  661. }
  662. if ($amount > 49999) {
  663. $result['text'] = '提现金额最多49999';
  664. return $result;
  665. }
  666. // 在调用三方支付前开始事务
  667. DB::beginTransaction();
  668. try {
  669. $wallet = WalletService::findOne(['member_id' => $memberId]);
  670. if (!$wallet) {
  671. $result['text'] = '钱包不存在!';
  672. return $result;
  673. }
  674. $balance = $wallet->available_balance;
  675. if (bccomp($balance, $amount, 2) < 0) {
  676. $result['text'] = '您的钱包余额不足!';
  677. return $result;
  678. }
  679. $available_balance = bcsub($balance, $amount, 10);
  680. $data = [];
  681. $data['type'] = self::TYPE_PAYOUT;
  682. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  683. $data['order_no'] = $order_no;
  684. $data['member_id'] = $memberId;
  685. $data['fee'] = $amount * 0.002 + 2;
  686. $amount = number_format($amount, 2, '.', '');
  687. $data['amount'] = $amount;
  688. $data['channel'] = $channel;
  689. $data['bank_name'] = $bank_name;
  690. $data['account'] = $account;
  691. $data['card_no'] = $card_no;
  692. if (NoPayService::isWithdrawChannel($channel)) {
  693. $data['callback_url'] = NoPayService::getWithdrawNotifyUrl();
  694. } elseif (JdPayService::isChannel($channel)) {
  695. $data['callback_url'] = JdPayService::getRemitNotifyUrl();
  696. } else {
  697. $data['callback_url'] = QianBaoService::getNotifyUrl();
  698. }
  699. $data['status'] = self::STATUS_STAY;
  700. $data['remark'] = '提现费率:0.2%+2';
  701. // 先预扣款(锁定资金)
  702. $wallet->available_balance = $available_balance;
  703. if (!$wallet->save()) {
  704. DB::rollBack();
  705. $result['text'] = '钱包更新失败!';
  706. return $result;
  707. }
  708. // 创建待处理状态的提现记录
  709. $info = static::$MODEL::create($data);
  710. $id = $info->id;
  711. // 记录余额变动日志
  712. BalanceLogService::addLog($memberId, $default_amount * -1, $balance, $available_balance, '三方提现', $id, '钱宝提现费率:0.2%+2');
  713. // 提交事务,确保预扣款成功
  714. DB::commit();
  715. } //
  716. catch (Exception $e) {
  717. // 预扣款失败,回滚事务
  718. DB::rollBack();
  719. $result['text'] = '系统繁忙,请稍后重试!';
  720. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  721. 'member_id' => $memberId,
  722. 'amount' => $amount
  723. ]);
  724. return $result;
  725. }
  726. // 调用三方支付接口(在事务外)
  727. if (NoPayService::isWithdrawChannel($channel)) {
  728. try {
  729. $ret = NoPayService::withdraw($amount, $order_no, (string)$memberId, (string)$account, (string)$card_no);
  730. Log::channel('payment')->info('NO提现接口调用', [
  731. 'order_no' => $order_no,
  732. 'member_id' => $memberId,
  733. 'amount' => $amount,
  734. 'q_account' => $card_no,
  735. 'response' => $ret,
  736. ]);
  737. $success = (($ret['code'] ?? -1) == 0);
  738. $failureMessage = $ret['msg'] ?? 'NO提现失败';
  739. } catch (Exception $e) {
  740. $ret = ['msg' => $e->getMessage()];
  741. $success = false;
  742. $failureMessage = $e->getMessage();
  743. Log::channel('payment_error')->error('NO提现接口异常', [
  744. 'order_no' => $order_no,
  745. 'member_id' => $memberId,
  746. 'amount' => $amount,
  747. 'q_account' => $card_no,
  748. 'error' => $e->getMessage(),
  749. ]);
  750. }
  751. } elseif (JdPayService::isChannel($channel)) {
  752. try {
  753. self::assertJdBalanceEnough($amount, [
  754. 'order_no' => $order_no,
  755. 'member_id' => $memberId,
  756. 'address' => $card_no,
  757. ]);
  758. $ret = JdPayService::remit($amount, $order_no, $card_no);
  759. Log::channel('payment')->info('JD下发接口调用', [
  760. 'order_no' => $order_no,
  761. 'member_id' => $memberId,
  762. 'amount' => $amount,
  763. 'address' => $card_no,
  764. 'response' => $ret,
  765. ]);
  766. $success = (($ret['code'] ?? 0) == 200);
  767. $failureMessage = $ret['message'] ?? 'JD下发失败';
  768. if (!$success) {
  769. $logContext = [
  770. 'order_no' => $order_no,
  771. 'member_id' => $memberId,
  772. 'amount' => $amount,
  773. 'address' => $card_no,
  774. 'response' => $ret,
  775. ];
  776. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  777. Log::error('JD下发接口失败', $logContext);
  778. }
  779. } catch (Exception $e) {
  780. $ret = ['message' => $e->getMessage()];
  781. $success = false;
  782. $failureMessage = $e->getMessage();
  783. $logContext = [
  784. 'order_no' => $order_no,
  785. 'member_id' => $memberId,
  786. 'amount' => $amount,
  787. 'address' => $card_no,
  788. 'error' => $e->getMessage(),
  789. ];
  790. Log::channel('payment_error')->error('JD下发接口异常', $logContext);
  791. Log::error('JD下发接口异常', $logContext);
  792. }
  793. } else {
  794. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  795. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  796. $success = (($ret['code'] ?? 0) == 200);
  797. $failureMessage = $ret['msg'] ?? '代付失败';
  798. }
  799. if ($success) {
  800. // 更新提现记录状态为处理中
  801. DB::beginTransaction();
  802. try {
  803. $info->status = self::STATUS_PROCESS;
  804. if (NoPayService::isWithdrawChannel($channel) || JdPayService::isChannel($channel)) {
  805. $info->pay_no = $ret['data']['orderNo'] ?? '';
  806. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  807. }
  808. $info->save();
  809. DB::commit();
  810. $text = "✅ 提现申请已提交!\n\n";
  811. $text .= "钱包余额:{$available_balance} RMB\n";
  812. $text .= "提现金额:{$default_amount} RMB\n";
  813. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  814. $result['text'] = $text;
  815. } catch (Exception $e) {
  816. DB::rollBack();
  817. // 状态更新失败,但资金已扣款且三方支付已成功
  818. // 这里可以记录告警,需要人工干预
  819. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  820. 'member_id' => $memberId,
  821. 'order_no' => $order_no
  822. ]);
  823. $result['text'] = '提现申请已提交,系统处理中...';
  824. }
  825. } //
  826. else {
  827. // 三方支付失败,需要回滚之前的预扣款
  828. DB::beginTransaction();
  829. try {
  830. // 恢复钱包余额
  831. $wallet->available_balance = $balance;
  832. $wallet->save();
  833. // 更新提现记录状态为失败
  834. $info->status = self::STATUS_FAIL;
  835. $info->remark = $failureMessage;
  836. $info->save();
  837. // 记录退款日志
  838. BalanceLogService::addLog($memberId, $default_amount, $available_balance, $balance, '三方提现', $id, '提现失败退款');
  839. DB::commit();
  840. $result['text'] = $failureMessage;
  841. } catch (Exception $e) {
  842. DB::rollBack();
  843. // 回滚失败,需要记录告警,人工干预
  844. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  845. 'member_id' => $memberId,
  846. 'order_no' => $order_no,
  847. 'amount' => $amount
  848. ]);
  849. $result['text'] = '提现失败,请联系客服处理退款!';
  850. }
  851. }
  852. return $result;
  853. }
  854. /**
  855. * @description: 接收三方订单
  856. * @param {*} $params
  857. * @return {*}
  858. */
  859. public static function receiveOrder($params)
  860. {
  861. if (NoPayService::getWithdrawMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
  862. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  863. if (!$info || $info->type != self::TYPE_PAYOUT || !NoPayService::isWithdrawChannel($info->channel)) {
  864. Log::error('NO钱包提现回调订单不存在或类型不匹配', [
  865. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  866. 'order_id' => $info->id ?? null,
  867. 'order_type' => $info->type ?? null,
  868. 'channel' => $info->channel ?? null,
  869. ]);
  870. return false;
  871. }
  872. if (!NoPayService::verifyWithdrawNotify($params)) {
  873. Log::error('NO钱包提现回调验签失败', [
  874. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  875. 'app_id' => $params['appId'] ?? '',
  876. 'signature' => NoPayService::withdrawNotifySignatureDiagnostics($params),
  877. ]);
  878. return false;
  879. }
  880. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  881. Log::error('NO钱包提现回调金额不一致', [
  882. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  883. 'order_amount' => $info->amount,
  884. 'callback_amount' => $params['amount'] ?? null,
  885. ]);
  886. return false;
  887. }
  888. self::onSubmitNoPayout($params, $info);
  889. return true;
  890. }
  891. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  892. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  893. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  894. if (!$info || $info->type != self::TYPE_PAYOUT) {
  895. return false;
  896. }
  897. if (!JdPayService::verifyRemitNotify($params)) {
  898. return false;
  899. }
  900. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  901. return false;
  902. }
  903. self::onSubmitJdPayout($params, $info);
  904. return true;
  905. }
  906. // 判断商户号是否一致
  907. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  908. $info = self::findOne(['order_no' => $params['orderNo']]);
  909. if ($info) {
  910. // 判断金额是不是正确认
  911. if ($info->amount != $params['amount']) {
  912. return false;
  913. }
  914. // 验证签名
  915. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  916. if ($params['sign'] != $sign) {
  917. return false;
  918. }
  919. // 代付
  920. if ($info->type == self::TYPE_PAYOUT) {
  921. self::onSubmitPayout($params, $info);
  922. }
  923. // 代收
  924. if ($info->type == self::TYPE_PAY) {
  925. }
  926. }
  927. }
  928. }
  929. /**
  930. * @description: 处理代付订单
  931. * @param {*} $params
  932. * @return {*}
  933. */
  934. public static function onSubmitJdPayout($params, $info)
  935. {
  936. if ($info->status != self::STATUS_PROCESS) {
  937. return;
  938. }
  939. $memberId = $info->member_id;
  940. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  941. $data = [];
  942. $chat_id = $info->member_id;
  943. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  944. DB::beginTransaction();
  945. try {
  946. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  947. $data['status'] = self::STATUS_SUCCESS;
  948. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  949. if ($res) {
  950. $text = "✅ 提现通知 \n";
  951. $text .= "提现平台:{$info->bank_name} \n";
  952. $text .= "收款人:{$info->account} \n";
  953. $text .= "收款地址:{$info->card_no} \n";
  954. $text .= "提现金额:{$info->amount} \n";
  955. $text .= "提现成功,金额已到账,请注意查收!";
  956. self::notifyUser($chat_id, $text);
  957. }
  958. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  959. $data['status'] = self::STATUS_FAIL;
  960. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  961. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  962. $balance = $wallet->available_balance;
  963. $available_balance = bcadd($balance, $amount, 10);
  964. $wallet->available_balance = $available_balance;
  965. $wallet->save();
  966. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  967. if ($res) {
  968. $text = "❌ 提现通知 \n";
  969. $text .= "提现平台:{$info->bank_name} \n";
  970. $text .= "收款人:{$info->account} \n";
  971. $text .= "收款地址:{$info->card_no} \n";
  972. $text .= "提现金额:{$info->amount} \n";
  973. $text .= "提现失败,金额已返回钱包,请注意查收!";
  974. self::notifyUser($chat_id, $text);
  975. }
  976. }
  977. DB::commit();
  978. } catch (Exception $e) {
  979. DB::rollBack();
  980. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  981. }
  982. }
  983. public static function onSubmitNoPayout($params, $info)
  984. {
  985. $notification = null;
  986. try {
  987. DB::transaction(function () use ($params, $info, &$notification) {
  988. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  989. if (!$order || $order->status != self::STATUS_PROCESS) {
  990. return;
  991. }
  992. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  993. if ((string)$params['state'] === NoPayService::STATE_SUCCESS) {
  994. $order->status = self::STATUS_SUCCESS;
  995. $order->save();
  996. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  997. } elseif ((string)$params['state'] === NoPayService::STATE_FAIL) {
  998. $order->status = self::STATUS_FAIL;
  999. $order->save();
  1000. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  1001. if (!$wallet) {
  1002. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  1003. }
  1004. $balance = $wallet->available_balance;
  1005. $availableBalance = bcadd($balance, NoPayService::amount($order->amount), 10);
  1006. $wallet->available_balance = $availableBalance;
  1007. $wallet->save();
  1008. BalanceLogService::addLog($order->member_id, $order->amount, $balance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  1009. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  1010. } else {
  1011. $order->save();
  1012. }
  1013. }, 3);
  1014. if ($notification !== null) {
  1015. self::notifyUser($info->member_id, $notification);
  1016. }
  1017. } catch (Exception $e) {
  1018. Log::channel('payment_error')->error('NO提现回调处理异常', [
  1019. 'order_id' => $info->id,
  1020. 'params' => $params,
  1021. 'error' => $e->getMessage(),
  1022. ]);
  1023. }
  1024. }
  1025. public static function onSubmitPayout($params, $info)
  1026. {
  1027. $memberId = $info->member_id;
  1028. $amount = $params['amount'];
  1029. $data = [];
  1030. $result = [];
  1031. $chat_id = $info->member_id;
  1032. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1033. DB::beginTransaction();
  1034. try {
  1035. if ($params['state'] == 1) {
  1036. $data['status'] = self::STATUS_SUCCESS;
  1037. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1038. if ($res) {
  1039. $text = "✅ 提现通知 \n";
  1040. $text .= "提现平台:{$info->bank_name} \n";
  1041. $text .= "收款人:{$info->account} \n";
  1042. $text .= "收款卡号:{$info->card_no} \n";
  1043. $text .= "提现金额:{$info->amount} \n";
  1044. $text .= "提现成功,金额已到账,请注意查收!";
  1045. self::notifyUser($chat_id, $text);
  1046. }
  1047. } else {
  1048. $data['status'] = self::STATUS_FAIL;
  1049. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1050. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1051. $balance = $wallet->available_balance; // 钱包当前余额
  1052. $available_balance = bcadd($balance, $params['amount'], 10);
  1053. $wallet->available_balance = $available_balance;
  1054. $wallet->save();
  1055. // 记录退款日志
  1056. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  1057. if ($res) {
  1058. $text = "❌ 提现通知 \n";
  1059. $text .= "提现平台:{$info->bank_name} \n";
  1060. $text .= "收款人:{$info->account} \n";
  1061. $text .= "收款卡号:{$info->card_no} \n";
  1062. $text .= "提现金额:{$info->amount} \n";
  1063. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1064. self::notifyUser($chat_id, $text);
  1065. }
  1066. }
  1067. DB::commit();
  1068. } catch (Exception $e) {
  1069. DB::rollBack();
  1070. // 回滚失败,需要记录告警,人工干预
  1071. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  1072. }
  1073. }
  1074. /**
  1075. * @description: 查询支付订单
  1076. * @param {*} $id
  1077. * @return {*}
  1078. */
  1079. public static function singlePayOrder($id)
  1080. {
  1081. $msg = [];
  1082. $msg['code'] = self::NOT;
  1083. $info = self::findOne(['id' => $id]);
  1084. if ($info && $info->status == self::STATUS_PROCESS) {
  1085. if (NoPayService::isRechargeChannel($info->channel)) {
  1086. $ret = NoPayService::queryPayOrder($info->order_no, (string)$info->member_id);
  1087. Log::channel('payment')->info('NO支付查询订单', $ret);
  1088. if (($ret['code'] ?? -1) == 0) {
  1089. $item = $ret['data'] ?? [];
  1090. if ((string)($item['state'] ?? '') === NoPayService::STATE_SUCCESS) {
  1091. $processed = self::applyPayCallback(
  1092. $info,
  1093. NoPayService::amount($info->amount),
  1094. NoPayService::STATE_SUCCESS,
  1095. NoPayService::STATE_SUCCESS,
  1096. NoPayService::STATE_FAIL,
  1097. $ret
  1098. );
  1099. $msg['code'] = $processed ? self::YES : self::NOT;
  1100. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1101. } elseif ((string)($item['state'] ?? '') === NoPayService::STATE_FAIL) {
  1102. self::applyPayCallback(
  1103. $info,
  1104. NoPayService::amount($info->amount),
  1105. NoPayService::STATE_FAIL,
  1106. NoPayService::STATE_SUCCESS,
  1107. NoPayService::STATE_FAIL,
  1108. $ret
  1109. );
  1110. $msg['msg'] = '支付失败';
  1111. } else {
  1112. $msg['msg'] = '支付中';
  1113. }
  1114. } else {
  1115. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1116. }
  1117. return $msg;
  1118. }
  1119. if (JdPayService::isChannel($info->channel)) {
  1120. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  1121. Log::channel('payment')->info('JD支付查询订单', $ret);
  1122. if (($ret['code'] ?? 0) == 200) {
  1123. $item = $ret['data'] ?? [];
  1124. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  1125. $info->status = self::STATUS_SUCCESS;
  1126. $info->state = $item['status'];
  1127. $info->callback_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  1128. $info->save();
  1129. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1130. $balance = $wallet->available_balance;
  1131. $available_balance = bcadd($balance, $info->amount, 10);
  1132. $wallet->available_balance = $available_balance;
  1133. $wallet->save();
  1134. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  1135. self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
  1136. $msg['code'] = self::YES;
  1137. $msg['msg'] = '支付成功';
  1138. } else {
  1139. $msg['msg'] = '支付中';
  1140. }
  1141. } else {
  1142. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  1143. }
  1144. return $msg;
  1145. }
  1146. $ret = SanJinService::queryOrder($info->order_no);
  1147. Log::error('三斤支付查询订单:', $ret);
  1148. if ($ret['code'] == 0) {
  1149. $item = [];
  1150. $item['state'] = $ret['data']['state'];
  1151. if ($ret['data']['state'] == 1) {
  1152. $item['status'] = self::STATUS_SUCCESS;
  1153. $info->update($item);
  1154. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1155. $balance = $wallet->available_balance;
  1156. $available_balance = bcadd($balance, $info->amount, 10);
  1157. $wallet->available_balance = $available_balance;
  1158. $wallet->save();
  1159. // 记录余额变动日志
  1160. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  1161. $msg['code'] = self::YES;
  1162. $msg['msg'] = '支付成功';
  1163. } else {
  1164. $msg['msg'] = '支付中';
  1165. }
  1166. } else {
  1167. $msg['msg'] = '查询失败:' . $ret['message'];
  1168. }
  1169. } else {
  1170. $msg['msg'] = '该状态无法查询';
  1171. }
  1172. return $msg;
  1173. }
  1174. private static function assertJdBalanceEnough($amount, array $context = []): void
  1175. {
  1176. $ret = JdPayService::balance();
  1177. Log::channel('payment')->info('JD余额查询', $context + [
  1178. 'amount' => $amount,
  1179. 'response' => $ret,
  1180. ]);
  1181. if (($ret['code'] ?? 0) != 200) {
  1182. $logContext = $context + [
  1183. 'amount' => $amount,
  1184. 'response' => $ret,
  1185. ];
  1186. Log::channel('payment_error')->error('JD余额查询失败', $logContext);
  1187. Log::error('JD余额查询失败', $logContext);
  1188. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  1189. }
  1190. $balance = $ret['data']['balance'] ?? null;
  1191. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  1192. $logContext = $context + [
  1193. 'amount' => $amount,
  1194. 'balance' => $balance,
  1195. 'response' => $ret,
  1196. ];
  1197. Log::channel('payment_error')->error('JD商户余额不足', $logContext);
  1198. Log::error('JD商户余额不足', $logContext);
  1199. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  1200. }
  1201. }
  1202. private static function notifyUser($chatId, string $text): void
  1203. {
  1204. if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
  1205. return;
  1206. }
  1207. try {
  1208. self::sendMessage($chatId, $text);
  1209. } catch (\Throwable $e) {
  1210. Log::channel('payment_error')->error('支付订单用户通知失败', [
  1211. 'chat_id' => $chatId,
  1212. 'error' => $e->getMessage(),
  1213. ]);
  1214. }
  1215. }
  1216. public static function syncPayOrder()
  1217. {
  1218. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  1219. // foreach($list->toArray() as $k => $v){
  1220. // $item= [];
  1221. // if($v['status'] == self::STATUS_SUCCESS){
  1222. // $item['state'] = 1;
  1223. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1224. // }else{
  1225. // $ret = SanJinService::queryOrder($v['order_no']);
  1226. // var_dump($ret);
  1227. // if($ret['code'] == 0){
  1228. // $item['state'] = $ret['data']['state'];
  1229. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1230. // }
  1231. // }
  1232. // }
  1233. }
  1234. }