PaymentOrderService.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Models\PaymentOrder;
  5. use App\Models\Agent\AgentPaymentOrder;
  6. use App\Services\Agent\AgentPaymentService;
  7. use App\Services\Agent\AgentWithdrawalService;
  8. use App\Models\Agent\AgentWithdrawal;
  9. use App\Models\RechargeChannel;
  10. use App\Models\User;
  11. use App\Models\Wallet as WalletModel;
  12. use Exception;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use App\Services\Payment\JdPayService;
  16. use App\Services\Payment\NoPayService;
  17. use App\Services\Payment\QianBaoService;
  18. use App\Services\Payment\SanJinService;
  19. use App\Services\Payment\ZimuPayService;
  20. use App\Services\Payment\PaymentProviderService;
  21. use App\Services\ConfigService;
  22. use App\Services\AdminRealtime\AdminRealtime;
  23. /**
  24. * 投注
  25. */
  26. class PaymentOrderService extends BaseService
  27. {
  28. const TYPE_PAY = 1; // 代收
  29. const TYPE_PAYOUT = 2; // 代付
  30. const TYPE_SELF_PAY = 3; // 手动充值
  31. const TYPE_SELF_PAYOUT = 4; // 手动提现打款
  32. const STATUS_STAY = 0; // 待处理
  33. const STATUS_PROCESS = 1; // 处理中
  34. const STATUS_SUCCESS = 2; // 成功
  35. const STATUS_FAIL = 3; // 失败
  36. const STATUS_USER = 4; // 待用户提交凭证
  37. const STATUS_AUDIT = 5; //待人工审核
  38. const STATUS_CANCEL = 6; //已撤回
  39. const STATUS_TIMEOUT = 7; //超时(在线充值处理中超过 PAY_TIMEOUT_MINUTES 未支付,仍可接收迟到的回调)
  40. const PAY_TIMEOUT_MINUTES = 30;
  41. const PAY_OPEN_STATUSES = [self::STATUS_PROCESS, self::STATUS_TIMEOUT]; // 在线充值可接收回调/查询入账的状态
  42. public static string $MODEL = PaymentOrder::class;
  43. /**
  44. * @description: 模型
  45. * @return {string}
  46. */
  47. public static function model(): string
  48. {
  49. return PaymentOrder::class;
  50. }
  51. /**
  52. * @description: 枚举
  53. * @return {*}
  54. */
  55. public static function enum(): string
  56. {
  57. return '';
  58. }
  59. /**
  60. * @description: 获取查询条件
  61. * @param {array} $search 查询内容
  62. * @return {array}
  63. */
  64. public static function getWhere(array $search = []): array
  65. {
  66. $where = [];
  67. if (isset($search['member_id']) && !empty($search['member_id'])) {
  68. $where[] = ['payment_orders.member_id', '=', $search['member_id']];
  69. }
  70. if (isset($search['channel']) && !empty($search['channel'])) {
  71. if ($search['channel'] == 'rgcz') {
  72. $search['type'] = 3;
  73. }
  74. $where[] = ['payment_orders.channel', '=', $search['channel']];
  75. }
  76. if (isset($search['type']) && !empty($search['type'])) {
  77. $where[] = ['payment_orders.type', '=', $search['type']];
  78. }
  79. if (isset($search['order_no']) && !empty($search['order_no'])) {
  80. $where[] = ['payment_orders.order_no', '=', $search['order_no']];
  81. }
  82. if (isset($search['id']) && !empty($search['id'])) {
  83. $where[] = ['payment_orders.id', '=', $search['id']];
  84. }
  85. if (isset($search['status']) && $search['status'] != '') {
  86. $where[] = ['payment_orders.status', '=', $search['status']];
  87. }
  88. if (!empty($search['account'])) {
  89. $where[] = ['users.account', 'like', '%' . trim((string)$search['account']) . '%'];
  90. }
  91. if (isset($search['first_name']) && !empty($search['first_name'])) {
  92. $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
  93. }
  94. if (isset($search['payment_type']) && $search['payment_type'] != '') {
  95. $where[] = ['payment_orders.payment_type', '=', $search['payment_type']];
  96. }
  97. return $where;
  98. }
  99. /**
  100. * @description: 查询单条数据
  101. * @param array $search
  102. * @return \App\Models\Coin|null
  103. */
  104. public static function findOne(array $search): ?PaymentOrder
  105. {
  106. return static::$MODEL::where(self::getWhere($search))->first();
  107. }
  108. /**
  109. * @description: 查询所有数据
  110. * @param array $search
  111. * @return \Illuminate\Database\Eloquent\Collection
  112. */
  113. public static function findAll(array $search = [])
  114. {
  115. return static::$MODEL::where(self::getWhere($search))->get();
  116. }
  117. /**
  118. * @description: 分页查询
  119. * @param array $search
  120. * @return array
  121. */
  122. public static function paginate(array $search = [])
  123. {
  124. $limit = isset($search['limit']) ? $search['limit'] : 15;
  125. $paginator = static::$MODEL::where(self::getWhere($search))
  126. ->join('users', 'users.member_id', '=', 'payment_orders.member_id')
  127. ->select("payment_orders.*", "users.first_name", "users.account", "users.admin_note as user_admin_note") // 提前查好需要的字段
  128. ->orderByDesc('payment_orders.created_at')
  129. ->paginate($limit);
  130. $totalAmount = 0;
  131. $totalSuccess = 0;
  132. $totalFail = 0;
  133. $list = $paginator->items();
  134. foreach ($list as $item) {
  135. $item['amount'] = floatval($item['amount']);
  136. $totalAmount += $item['amount'];
  137. if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
  138. if ($item['status'] == 3) $totalFail += $item['amount'];
  139. }
  140. return [
  141. 'total' => $paginator->total(),
  142. 'total_amount' => $totalAmount,
  143. 'total_success' => $totalSuccess,
  144. 'total_fail' => $totalFail,
  145. 'data' => $list
  146. ];
  147. }
  148. /**
  149. * @description:
  150. * @param {*} $params
  151. * @return {*}
  152. */
  153. public static function submit($params = [])
  154. {
  155. $result = false;
  156. $msg['code'] = self::NOT;
  157. $msg['msg'] = '';
  158. // 2. 判断是否是更新
  159. if (!empty($params['id'])) {
  160. // 更新
  161. $info = self::findOne(['id' => $params['id']]);
  162. if (!$info) {
  163. $msg['msg'] = '数据不存在!';
  164. } else {
  165. $result = $info->update($params);
  166. $id = $params['id'];
  167. }
  168. } else {
  169. // 创建
  170. $result = $info = static::$MODEL::create($params);
  171. $id = $result->id;
  172. }
  173. if ($result) {
  174. $msg['code'] = self::YES;
  175. $msg['msg'] = '设置成功';
  176. $msg['key'] = $id;
  177. } else {
  178. $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
  179. }
  180. return $msg;
  181. }
  182. /**
  183. * @description: 创建代收订单
  184. * @param {*} $memberId
  185. * @param {*} $amount
  186. * @param {*} $paymentType 支付类型:支付宝、数字人民币
  187. * @return {*}
  188. */
  189. public static function createPay($memberId, $amount, $paymentType)
  190. {
  191. $result = [];
  192. $result['chat_id'] = $memberId;
  193. $result['code'] = 0;
  194. $result['url'] = '';
  195. if (!PaymentProviderService::requestEnabled((string)$paymentType, 1)) {
  196. $result['code'] = 20001;
  197. $result['text'] = '支付公司已禁用';
  198. return $result;
  199. }
  200. $user = User::query()->where('member_id', $memberId)->first();
  201. $groupId = (int)($user->recharge_channel_group_id ?? 1);
  202. $channelConfig = RechargeChannel::checkRechargeChannel($paymentType, $groupId);
  203. if ($channelConfig === false) {
  204. $result['text'] = '不支持此充值方式';
  205. $result['code'] = 20001;
  206. return $result;
  207. }
  208. $bonusSnapshot = RechargeBonusService::capture((string)$channelConfig->type, (string)$memberId);
  209. $extra = $bonusSnapshot === null ? [] : ['recharge_bonus_snapshot' => $bonusSnapshot];
  210. return self::createPayOrder(PaymentOrder::class, $memberId, $amount, $paymentType, $groupId, $channelConfig, $extra);
  211. }
  212. /**
  213. * 按通道向三方(808/NO/JD/三斤)发起代收并保存订单。会员和代理共用:
  214. * - $model:PaymentOrder(会员)或 AgentPaymentOrder(代理);
  215. * - $memberId:付款人标识,会员为 member_id,代理为 AG{代理ID};
  216. * - $extra:额外写入订单的字段;$orderPrefix:订单号前缀(代理为 ag)。
  217. * 调用方需先校验支付公司启用、通道可用。成功时返回值带 order_no。
  218. */
  219. public static function createPayOrder(string $model, $memberId, $amount, $paymentType, int $groupId, $channelConfig, array $extra = [], string $orderPrefix = ''): array
  220. {
  221. $result = [];
  222. $result['chat_id'] = $memberId;
  223. $result['code'] = 0;
  224. $result['url'] = '';
  225. $channel = ''; // 支付的通道
  226. $product = SanJinService::product($groupId);
  227. $max = (float)($channelConfig->max ?? 0);
  228. $min = (float)($channelConfig->min ?? 0);
  229. $rate = (float)($channelConfig->rate ?? 0);
  230. $selectedProduct = null;
  231. $geText = '';
  232. foreach ($product as $k => $v) {
  233. if ($v['type'] == $paymentType) {
  234. $selectedProduct = $v;
  235. if ($v['type'] == 'zfbge') {
  236. if (in_array($amount, $v['fixed'])) {
  237. $channel = $k;
  238. } else {
  239. $geText .= "❌ 此充值通道固定充值金额为" . implode(',', $v['fixed']) . "请选择上述固定金额!";
  240. }
  241. } else {
  242. if ($amount >= $v['min'] && $amount <= $v['max']) {
  243. $channel = $k;
  244. $rate = $v['rate'];
  245. }
  246. if ($min == 0) {
  247. $min = $v['min'];
  248. }
  249. if ($max == 0) {
  250. $max = $v['max'];
  251. }
  252. if ($min > $v['min']) {
  253. $min = $v['min'];
  254. }
  255. if ($max < $v['max']) {
  256. $max = $v['max'];
  257. }
  258. }
  259. }
  260. }
  261. $isDirectProvider = JdPayService::isChannel($paymentType)
  262. || NoPayService::isRechargeChannel($paymentType)
  263. || ZimuPayService::isRechargeChannel($paymentType);
  264. if ($isDirectProvider && ($amount < $min || ($max > 0 && $amount > $max))) {
  265. $result['text'] = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
  266. $result['code'] = 20001;
  267. return $result;
  268. }
  269. // 没有找到支付通道
  270. if (empty($channel) && !JdPayService::isChannel($paymentType) && !NoPayService::isRechargeChannel($paymentType) && !ZimuPayService::isRechargeChannel($paymentType)) {
  271. // $text = "发起充值失败 \n";
  272. // $text .= "最低充值:" . $min . " \n";
  273. // $text .= "最高充值:" . $max . " \n";
  274. // $text .= "请重新填写充值的金额!";
  275. $text = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
  276. $result['text'] = $text;
  277. if ($geText) {
  278. $result['text'] = $geText;
  279. }
  280. $result['code'] = 20001;
  281. return $result;
  282. }
  283. if (ZimuPayService::isRechargeChannel($paymentType) || ZimuPayService::isRechargeChannel($channel)) {
  284. $channel = ZimuPayService::CHANNEL_RECHARGE;
  285. $bankName = $selectedProduct['name'] ?? '808充值';
  286. $data = [];
  287. $data['type'] = self::TYPE_PAY;
  288. $data['member_id'] = $memberId;
  289. $data['amount'] = ZimuPayService::amount($amount);
  290. $data['channel'] = $channel;
  291. $data['fee'] = $amount * $rate;
  292. $data['bank_name'] = $bankName;
  293. $order_no = self::createOrderNo($orderPrefix . 'zm' . $data['type'] . '_', $memberId);
  294. $data['order_no'] = $order_no;
  295. $data['callback_url'] = ZimuPayService::getPayNotifyUrl();
  296. $data['remark'] = '充值费率:' . $rate;
  297. $data['status'] = self::STATUS_STAY;
  298. $ret = ZimuPayService::pay($amount, $order_no, (string)$memberId);
  299. Log::channel('payment')->info('ZIMU支付发起', [
  300. 'order_no' => $order_no,
  301. 'member_id' => $memberId,
  302. 'amount' => $data['amount'],
  303. 'response' => $ret,
  304. ]);
  305. if (($ret['code'] ?? -1) == 0) {
  306. $item = $ret['data'] ?? [];
  307. $payUrl = $item['payUrl'] ?? '';
  308. $data['status'] = self::STATUS_PROCESS;
  309. $data['pay_no'] = $item['orderNo'] ?? '';
  310. $data['pay_url'] = $payUrl;
  311. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  312. $model::create($data + $extra);
  313. $result['order_no'] = $order_no;
  314. if ($payUrl) {
  315. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  316. }
  317. $result['text'] = "{$bankName}确认 \n";
  318. $result['text'] .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  319. $result['text'] .= "支付地址:{$payUrl}\n";
  320. $result['text'] .= "支付金额:" . $amount . " RMB \n";
  321. $result['text'] .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  322. $result['url'] = $payUrl;
  323. } else {
  324. $result['text'] = $ret['msg'] ?? 'ZIMU支付发起失败';
  325. $result['code'] = 20002;
  326. }
  327. return $result;
  328. }
  329. if (NoPayService::isRechargeChannel($paymentType) || NoPayService::isRechargeChannel($channel)) {
  330. $channel = NoPayService::isRechargeChannel($paymentType) ? $paymentType : $channel;
  331. $bankName = $selectedProduct['name'] ?? 'NO快捷充值';
  332. $data = [];
  333. $data['type'] = self::TYPE_PAY;
  334. $data['member_id'] = $memberId;
  335. $data['amount'] = NoPayService::amount($amount);
  336. $data['channel'] = $channel;
  337. $data['fee'] = $amount * $rate;
  338. $data['bank_name'] = $bankName;
  339. $order_no = self::createOrderNo($orderPrefix . 'no' . $data['type'] . '_', $memberId);
  340. $data['order_no'] = $order_no;
  341. $data['callback_url'] = NoPayService::getDepositNotifyUrl();
  342. $data['remark'] = '充值费率:' . $rate;
  343. $data['status'] = self::STATUS_STAY;
  344. $ret = NoPayService::pay($amount, $order_no, (string)$memberId, $channel);
  345. Log::channel('payment')->info('NO支付发起', [
  346. 'order_no' => $order_no,
  347. 'member_id' => $memberId,
  348. 'amount' => $data['amount'],
  349. 'channel' => $channel,
  350. 'response' => $ret,
  351. ]);
  352. if (($ret['code'] ?? -1) == 0) {
  353. $payUrl = $ret['data']['url'] ?? '';
  354. $data['status'] = self::STATUS_PROCESS;
  355. $data['pay_url'] = $payUrl;
  356. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  357. $model::create($data + $extra);
  358. $result['order_no'] = $order_no;
  359. if ($payUrl) {
  360. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  361. }
  362. $result['text'] = "{$bankName}充值确认 \n";
  363. $result['text'] .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  364. $result['text'] .= "支付地址:{$payUrl}\n";
  365. $result['text'] .= "支付金额:" . $amount . " RMB \n";
  366. $result['text'] .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  367. $result['url'] = $payUrl;
  368. } else {
  369. $result['text'] = $ret['msg'] ?? 'NO支付发起失败';
  370. $result['code'] = 20002;
  371. }
  372. return $result;
  373. }
  374. if (JdPayService::isChannel($paymentType) || JdPayService::isChannel($channel)) {
  375. $channel = JdPayService::CHANNEL;
  376. $bankName = $selectedProduct['name'] ?? 'JD钱包';
  377. $data = [];
  378. $data['type'] = self::TYPE_PAY;
  379. $data['member_id'] = $memberId;
  380. $data['amount'] = JdPayService::amount($amount);
  381. $data['channel'] = $channel;
  382. $data['fee'] = $amount * $rate;
  383. $data['bank_name'] = $bankName;
  384. $order_no = self::createOrderNo($orderPrefix . 'jd' . $data['type'] . '_', $memberId);
  385. $data['order_no'] = $order_no;
  386. $data['callback_url'] = JdPayService::getNotifyUrl();
  387. $data['remark'] = '充值费率:' . $rate;
  388. $data['status'] = self::STATUS_STAY;
  389. $ret = JdPayService::pay($amount, $order_no);
  390. Log::channel('payment')->info('JD支付发起', $ret);
  391. if (($ret['code'] ?? 0) == 200) {
  392. $item = $ret['data'] ?? [];
  393. $payUrl = $item['url'] ?? '';
  394. $data['status'] = self::STATUS_PROCESS;
  395. $data['pay_no'] = $item['orderNo'] ?? '';
  396. $data['pay_url'] = $payUrl;
  397. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  398. $model::create($data + $extra);
  399. $result['order_no'] = $order_no;
  400. if ($payUrl) {
  401. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  402. }
  403. $text = "{$bankName}充值确认 \n";
  404. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  405. $text .= "支付地址:{$payUrl}\n";
  406. $text .= "支付金额:" . $amount . " RMB \n";
  407. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  408. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  409. $result['text'] = $text;
  410. $result['url'] = $payUrl;
  411. } else {
  412. $result['text'] = $ret['message'] ?? 'JD支付发起失败';
  413. $result['code'] = 20002;
  414. }
  415. return $result;
  416. }
  417. $data = [];
  418. $data['type'] = self::TYPE_PAY;
  419. $data['member_id'] = $memberId;
  420. $data['amount'] = $amount;
  421. $data['channel'] = $channel;
  422. $data['fee'] = $amount * $rate;
  423. $data['bank_name'] = SanJinService::getChannel($paymentType) ?? '';
  424. $order_no = self::createOrderNo($orderPrefix . 'sj' . $data['type'] . '_', $memberId);
  425. $data['order_no'] = $order_no;
  426. $data['callback_url'] = SanJinService::getNotifyUrl();
  427. $data['remark'] = '充值费率:' . $rate;
  428. $data['status'] = self::STATUS_STAY;
  429. $ret = SanJinService::pay(($amount * 100), $order_no, $channel);
  430. Log::error('三斤支付发起:', $ret);
  431. if ($ret['code'] == 0) {
  432. $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
  433. $result['image'] = $qrCode;
  434. $item = $ret['data'];
  435. $data['status'] = self::STATUS_PROCESS;
  436. $data['pay_no'] = $item['tradeNo'];
  437. $data['pay_url'] = $item['payUrl'];
  438. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  439. $info = $model::create($data + $extra);
  440. $result['order_no'] = $order_no;
  441. // $text = "✅ 支付提示 \n";
  442. $text = "{$data['bank_name']}充值确认 \n";
  443. // $text .= "支付方式:{$data['bank_name']} \n";
  444. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  445. $text .= "支付地址:{$ret['data']['payUrl']}\n";
  446. $text .= "支付金额:" . $amount . " RMB \n";
  447. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  448. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  449. $result['text'] = $text;
  450. $result['url'] = $ret['data']['payUrl'];
  451. } else {
  452. $result['text'] = $ret['message'];
  453. $result['code'] = 20002;
  454. }
  455. return $result;
  456. }
  457. /**
  458. * @description: 接收支付的通知
  459. * @param {*} $params
  460. * @return {*}
  461. */
  462. public static function receivePay($params)
  463. {
  464. if (ZimuPayService::getAppId() !== '' && ($params['appId'] ?? '') === ZimuPayService::getAppId()) {
  465. $info = self::findPayOrder((string)($params['mchOrderNo'] ?? ''));
  466. if (!$info || $info->type != self::TYPE_PAY || !ZimuPayService::isRechargeChannel($info->channel)) {
  467. Log::error('ZIMU充值回调订单不存在或类型不匹配', [
  468. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  469. 'order_id' => $info->id ?? null,
  470. 'order_type' => $info->type ?? null,
  471. 'channel' => $info->channel ?? null,
  472. ]);
  473. return false;
  474. }
  475. if (!ZimuPayService::verifyNotify($params)) {
  476. Log::error('ZIMU充值回调验签失败', [
  477. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  478. 'app_id' => $params['appId'] ?? '',
  479. 'signature' => ZimuPayService::notifySignatureDiagnostics($params),
  480. ]);
  481. return false;
  482. }
  483. if (bccomp(ZimuPayService::amount($info->amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  484. Log::error('ZIMU充值回调金额不一致', [
  485. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  486. 'order_amount' => $info->amount,
  487. 'callback_amount' => $params['amount'] ?? null,
  488. ]);
  489. return false;
  490. }
  491. if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
  492. return true;
  493. }
  494. $processed = self::applyPayCallback(
  495. $info,
  496. ZimuPayService::amount($info->amount),
  497. (string)$params['status'],
  498. ZimuPayService::PAY_STATUS_SUCCESS,
  499. ZimuPayService::PAY_STATUS_FAIL,
  500. $params
  501. );
  502. if ($processed && (string)$params['status'] === ZimuPayService::PAY_STATUS_SUCCESS) {
  503. self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
  504. }
  505. return true;
  506. }
  507. if (NoPayService::getDepositMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getDepositMerchantId()) {
  508. $info = self::findPayOrder((string)($params['merchantOrderNo'] ?? ''));
  509. if (!$info || $info->type != self::TYPE_PAY || !NoPayService::isRechargeChannel($info->channel)) {
  510. Log::error('NO钱包充值回调订单不存在或类型不匹配', [
  511. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  512. 'order_id' => $info->id ?? null,
  513. 'order_type' => $info->type ?? null,
  514. 'channel' => $info->channel ?? null,
  515. ]);
  516. return false;
  517. }
  518. if (!NoPayService::verifyDepositNotify($params)) {
  519. Log::error('NO钱包充值回调验签失败', [
  520. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  521. 'app_id' => $params['appId'] ?? '',
  522. 'signature' => NoPayService::depositNotifySignatureDiagnostics($params),
  523. ]);
  524. return false;
  525. }
  526. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  527. Log::error('NO钱包充值回调金额不一致', [
  528. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  529. 'order_amount' => $info->amount,
  530. 'callback_amount' => $params['amount'] ?? null,
  531. ]);
  532. return false;
  533. }
  534. if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
  535. return true;
  536. }
  537. $processed = self::applyPayCallback(
  538. $info,
  539. NoPayService::amount($info->amount),
  540. (string)$params['state'],
  541. NoPayService::STATE_SUCCESS,
  542. NoPayService::STATE_FAIL,
  543. $params
  544. );
  545. if ($processed && (string)$params['state'] === NoPayService::STATE_SUCCESS) {
  546. self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
  547. }
  548. return true;
  549. }
  550. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  551. $info = self::findPayOrder((string)($params['orderCode'] ?? ''), true);
  552. if (!$info || $info->type != self::TYPE_PAY) {
  553. return false;
  554. }
  555. if (!JdPayService::verifyPayNotify($params)) {
  556. return false;
  557. }
  558. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  559. return false;
  560. }
  561. if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
  562. return true;
  563. }
  564. $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), (string)$params['status'], JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $params);
  565. if ($processed && (string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
  566. $text = "✅ 支付成功 \n";
  567. $text .= "充值金额:{$info->amount} RMB \n";
  568. $text .= "订单号:{$info->order_no} \n";
  569. $text .= "您充值的金额已到账,请注意查收!";
  570. self::notifyUser($info->member_id, $text);
  571. }
  572. return true;
  573. }
  574. // 判断商户号
  575. if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
  576. $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
  577. $info = self::findPayOrder((string)($params['outTradeNo'] ?? ''));
  578. if ($info) {
  579. // 平台以分计算转成元
  580. $payAmount = $params['payAmount'] / 100;
  581. // 判断金额是不是正确认
  582. if ($info->amount != $payAmount) {
  583. $text = '❌ 支付失败提醒 \n';
  584. $text .= "订单金额:{$info->amount} \n";
  585. $text .= "实际支付:{$payAmount} \n";
  586. $text .= "订单号:{$params['outTradeNo']} \n";
  587. $text .= "失败原因:支付金额与订单金额不一致 \n";
  588. $text .= "请联系客服处理!";
  589. self::notifyUser($info->member_id, $text);
  590. return false;
  591. }
  592. if ($params['sign'] != SanJinService::signature($params, $must)) {
  593. return false;
  594. }
  595. if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
  596. return false;
  597. }
  598. // 付款
  599. if ($info->type == self::TYPE_PAY) {
  600. $processed = self::applyPayCallback($info, $payAmount, (string)$params['state'], '1', null, $params);
  601. if ($processed && $params['state'] == 1) {
  602. $text = "✅ 支付成功 \n";
  603. $text .= "充值金额:{$payAmount} RMB \n";
  604. $text .= "订单号:{$params['outTradeNo']} \n";
  605. $text .= "您充值的金额已到账,请注意查收!";
  606. self::notifyUser($info->member_id, $text);
  607. } else {
  608. $text = "❌ 支付失败 \n";
  609. $text .= "充值金额:{$payAmount} RMB \n";
  610. $text .= "订单号:{$params['outTradeNo']} \n";
  611. }
  612. return true;
  613. }
  614. }
  615. }
  616. }
  617. /**
  618. * 按订单号找在线充值订单:ag 开头的是代理订单(agent_payment_orders),其余是会员订单。
  619. * JD 回调的 orderCode 可能是三方单号,$byPayNo 时再按 pay_no 查。
  620. */
  621. public static function findPayOrder(string $orderNo, bool $byPayNo = false): ?PaymentOrder
  622. {
  623. if ($orderNo === '') return null;
  624. // 按 ag 前缀先查代理订单,找不到再查另一张表,避免前缀约定被打破时回调丢单。
  625. $models = str_starts_with($orderNo, AgentPaymentOrder::ORDER_PREFIX)
  626. ? [AgentPaymentOrder::class, PaymentOrder::class] : [PaymentOrder::class, AgentPaymentOrder::class];
  627. $order = $models[0]::where('order_no', $orderNo)->first() ?: $models[1]::where('order_no', $orderNo)->first();
  628. if (!$order && $byPayNo) {
  629. $order = PaymentOrder::where('pay_no', $orderNo)->first() ?: AgentPaymentOrder::where('pay_no', $orderNo)->first();
  630. }
  631. return $order;
  632. }
  633. private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
  634. {
  635. return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
  636. $order = $info::query()->where('id', $info->id)->lockForUpdate()->first();
  637. if (!$order || (int)$order->type !== self::TYPE_PAY || !in_array((int)$order->status, self::PAY_OPEN_STATUSES, true)) {
  638. return false;
  639. }
  640. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  641. $order->state = $status;
  642. if ($status === $successStatus) {
  643. $order->status = self::STATUS_SUCCESS;
  644. $order->save();
  645. if ($order instanceof AgentPaymentOrder) {
  646. // 代理订单入代理钱包(合营计入保证金),不发充值优惠。
  647. app(AgentPaymentService::class)->credit($order, (string)$payAmount, 'system', null);
  648. return true;
  649. }
  650. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  651. if (!$wallet) {
  652. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  653. }
  654. $balance = $wallet->available_balance;
  655. $availableBalance = bcadd($balance, $payAmount, 10);
  656. $wallet->available_balance = $availableBalance;
  657. $wallet->save();
  658. $principal = BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
  659. RechargeBonusService::grant('payment_order', $order, $principal);
  660. // Deposit hooks can grant an immediately available first-deposit reward.
  661. $wallet->refresh();
  662. return true;
  663. }
  664. if ($failStatus === null || $status === $failStatus) {
  665. $order->status = self::STATUS_FAIL;
  666. }
  667. $order->save();
  668. return true;
  669. }, 3);
  670. }
  671. /**
  672. * 拒绝提现
  673. * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
  674. * @param int $orderId 订单ID PaymentOrder 表的ID
  675. * @param string $remark 失败原因
  676. * @return array
  677. */
  678. public static function withdrawalFailed($orderId, $remark): array
  679. {
  680. try {
  681. DB::transaction(function () use ($orderId, $remark) {
  682. $order = PaymentOrder::where('id', $orderId)
  683. ->whereIn('type', [2,4])
  684. ->where('status', self::STATUS_STAY)
  685. ->lockForUpdate()
  686. ->first();
  687. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  688. // 更新提现记录状态为失败
  689. $order->status = self::STATUS_FAIL;
  690. $order->remark = $remark;
  691. if (!$order->save()) {
  692. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  693. }
  694. // 冻结余额退回可用余额,并记录退款日志
  695. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, $order->amount, '三方提现', '提现失败退款');
  696. }, 3);
  697. } catch (Exception $e) {
  698. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  699. }
  700. return ['code' => 0, 'msg' => 'ok'];
  701. }
  702. /**
  703. * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
  704. * @param int $orderId PaymentOrder 表的ID
  705. */
  706. public static function createPayout(int $orderId): array
  707. {
  708. try {
  709. $order = PaymentOrder::where('id', $orderId)
  710. ->where('type', 2)
  711. ->where('status', self::STATUS_STAY)
  712. ->first();
  713. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  714. $ret = self::requestPayout((string)$order->channel, (string)$order->order_no, (string)$order->member_id, $order->amount,
  715. (string)$order->account, (string)$order->card_no, (string)$order->bank_name, ['order_id' => $order->id]);
  716. if ($ret['pay_no'] !== null) $order->pay_no = $ret['pay_no'];
  717. if ($ret['pay_data'] !== null) $order->pay_data = $ret['pay_data'];
  718. $order->status = self::STATUS_PROCESS;
  719. $order->save();
  720. } catch (Exception $e) {
  721. Log::channel('payment_error')->error('创建代付订单失败', [
  722. 'order_id' => $orderId,
  723. 'error' => $e->getMessage(),
  724. ]);
  725. Log::error('创建代付订单失败', [
  726. 'order_id' => $orderId,
  727. 'error' => $e->getMessage(),
  728. ]);
  729. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  730. }
  731. return ['code' => 0, 'msg' => 'ok'];
  732. }
  733. /**
  734. * 向三方发起代付(NO/808/JD/钱宝),会员提现和代理提现共用。失败抛异常;成功返回三方单号和下单返回。
  735. * $memberId:会员为 member_id,代理为 AG{代理ID};$context 只用于日志。
  736. */
  737. public static function requestPayout(string $channel, string $orderNo, string $memberId, $amount, string $accountName, string $cardNo, string $bankName, array $context = []): array
  738. {
  739. $payNo = null;
  740. $payData = null;
  741. if (!PaymentProviderService::requestEnabled($channel, 2)) {
  742. throw new Exception('支付公司已禁用', HttpStatus::CUSTOM_ERROR);
  743. }
  744. if (!RechargeChannel::query()->where('data_type', 2)->where('type', $channel)->available()->exists()) {
  745. throw new Exception('提现通道已停用或删除', HttpStatus::CUSTOM_ERROR);
  746. }
  747. $amount = number_format($amount, 2, '.', '');
  748. if (NoPayService::isWithdrawChannel($channel)) {
  749. $ret = NoPayService::withdraw($amount, $orderNo, $memberId, $accountName, $cardNo);
  750. Log::channel('payment')->info('NO提现接口调用', [
  751. 'order_id' => ($context['order_id'] ?? null),
  752. 'order_no' => $orderNo,
  753. 'member_id' => $memberId,
  754. 'amount' => $amount,
  755. 'q_account' => $cardNo,
  756. 'response' => $ret,
  757. ]);
  758. if (($ret['code'] ?? -1) != 0) {
  759. throw new Exception($ret['msg'] ?? 'NO提现失败', HttpStatus::CUSTOM_ERROR);
  760. }
  761. $payNo = $ret['data']['orderNo'] ?? '';
  762. $payData = json_encode($ret, JSON_UNESCAPED_UNICODE);
  763. } elseif (ZimuPayService::isPayoutChannel($channel)) {
  764. self::assertZimuBalanceEnough($amount, [
  765. 'order_id' => ($context['order_id'] ?? null),
  766. 'order_no' => $orderNo,
  767. 'member_id' => $memberId,
  768. 'channel' => $channel,
  769. ]);
  770. if (ZimuPayService::isCashChannel($channel)) {
  771. $ret = ZimuPayService::cash(
  772. $amount,
  773. $orderNo,
  774. $accountName,
  775. $cardNo,
  776. $bankName,
  777. ZimuPayService::cashPayMethod($bankName)
  778. );
  779. } else {
  780. $ret = ZimuPayService::withdraw($amount, $orderNo, $memberId, $cardNo, $accountName);
  781. }
  782. Log::channel('payment')->info('ZIMU提现/代付接口调用', [
  783. 'order_id' => ($context['order_id'] ?? null),
  784. 'order_no' => $orderNo,
  785. 'member_id' => $memberId,
  786. 'amount' => $amount,
  787. 'channel' => $channel,
  788. 'response' => $ret,
  789. ]);
  790. if (($ret['code'] ?? -1) != 0) {
  791. throw new Exception($ret['msg'] ?? 'ZIMU提现/代付失败', HttpStatus::CUSTOM_ERROR);
  792. }
  793. $payNo = $ret['data']['orderNo'] ?? '';
  794. $payData = json_encode($ret, JSON_UNESCAPED_UNICODE);
  795. } elseif (JdPayService::isChannel($channel)) {
  796. self::assertJdBalanceEnough($amount, [
  797. 'order_id' => ($context['order_id'] ?? null),
  798. 'order_no' => $orderNo,
  799. 'member_id' => $memberId,
  800. 'address' => $cardNo,
  801. ]);
  802. $ret = JdPayService::remit($amount, $orderNo, $cardNo);
  803. Log::channel('payment')->info('JD下发接口调用', [
  804. 'order_id' => ($context['order_id'] ?? null),
  805. 'order_no' => $orderNo,
  806. 'member_id' => $memberId,
  807. 'amount' => $amount,
  808. 'address' => $cardNo,
  809. 'response' => $ret,
  810. ]);
  811. if (($ret['code'] ?? 0) != 200) {
  812. $logContext = [
  813. 'order_id' => ($context['order_id'] ?? null),
  814. 'order_no' => $orderNo,
  815. 'member_id' => $memberId,
  816. 'amount' => $amount,
  817. 'address' => $cardNo,
  818. 'response' => $ret,
  819. ];
  820. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  821. Log::error('JD下发接口失败', $logContext);
  822. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  823. }
  824. $payNo = $ret['data']['orderNo'] ?? '';
  825. $payData = json_encode($ret, JSON_UNESCAPED_UNICODE);
  826. } else {
  827. $ret = QianBaoService::payout(
  828. $amount, $orderNo, $bankName, $accountName, $cardNo, $channel
  829. );
  830. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  831. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  832. }
  833. return ['pay_no' => $payNo, 'pay_data' => $payData];
  834. }
  835. /**
  836. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  837. * @param {*} $memberId 会员ID
  838. * @param {*} $amount 代付金额
  839. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  840. * @param {*} $bank_name 银行名称/支付宝
  841. * @param {*} $card_no 银行卡号/支付宝账号
  842. * @return {*}
  843. */
  844. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $card_no, ?string $bankBranch = null)
  845. {
  846. $default_amount = $amount;
  847. $result = [];
  848. $result['chat_id'] = $memberId;
  849. if ($channel === 'rgtx') {
  850. $result['text'] = lang('不支持此提现方式');
  851. return $result;
  852. }
  853. if (!PaymentProviderService::requestEnabled((string)$channel, 2)) {
  854. $result['text'] = '支付公司已禁用';
  855. return $result;
  856. }
  857. $user = User::query()->where('member_id', $memberId)->first();
  858. $groupId = (int)($user->recharge_channel_group_id ?? 1);
  859. $channelConfig = RechargeChannel::checkWithdrawChannel($channel, $groupId);
  860. if ($channelConfig === false) {
  861. $result['text'] = '不支持此提现方式';
  862. return $result;
  863. }
  864. $minAmount = (float)($channelConfig->min ?? 0);
  865. $maxAmount = (float)($channelConfig->max ?? 0);
  866. if ($amount < $minAmount || ($maxAmount > 0 && $amount > $maxAmount)) {
  867. $result['text'] = "提现金额范围为{$minAmount}-{$maxAmount}";
  868. return $result;
  869. }
  870. $channelRate = (float)($channelConfig->rate ?? 0);
  871. // 在调用三方支付前开始事务
  872. DB::beginTransaction();
  873. try {
  874. $account = WithdrawalName::forPayout($user, $channel);
  875. $bankBranch = WithdrawalDestination::bankBranch($channel, $bank_name, $bankBranch);
  876. $data = [];
  877. $data['type'] = self::TYPE_PAYOUT;
  878. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  879. $data['order_no'] = $order_no;
  880. $data['member_id'] = $memberId;
  881. $data['fee'] = $amount * $channelRate + 2;
  882. $amount = number_format($amount, 2, '.', '');
  883. $data['amount'] = $amount;
  884. $data['channel'] = $channel;
  885. $data['bank_name'] = $bank_name;
  886. if ($bankBranch !== null) {
  887. $data['bank_branch'] = $bankBranch;
  888. }
  889. $data['account'] = $account;
  890. $data['card_no'] = $card_no;
  891. if (NoPayService::isWithdrawChannel($channel)) {
  892. $data['callback_url'] = NoPayService::getWithdrawNotifyUrl();
  893. } elseif (JdPayService::isChannel($channel)) {
  894. $data['callback_url'] = JdPayService::getRemitNotifyUrl();
  895. } elseif (ZimuPayService::isPayoutChannel($channel)) {
  896. $data['callback_url'] = ZimuPayService::getPayoutNotifyUrl();
  897. } else {
  898. $data['callback_url'] = QianBaoService::getNotifyUrl();
  899. }
  900. $data['status'] = self::STATUS_STAY;
  901. $data['remark'] = '提现费率:' . ($channelRate * 100) . '%+2';
  902. // 校验打码量 → 冻结资金 → 创建待处理的提现记录 → 重置打码周期
  903. [$info, $wallet] = WithdrawFundsService::hold((string)$memberId, $default_amount, '三方提现', '钱宝提现费率:' . ($channelRate * 100) . '%+2',
  904. WithdrawFundsService::PAYMENT_ORDERS, fn () => static::$MODEL::create($data));
  905. $id = $info->id;
  906. $available_balance = $wallet->available_balance;
  907. // 提交事务,确保预扣款成功
  908. DB::commit();
  909. } //
  910. catch (Exception $e) {
  911. // 预扣款失败,回滚事务
  912. DB::rollBack();
  913. $result['text'] = $e->getCode() === HttpStatus::CUSTOM_ERROR ? $e->getMessage() : '系统繁忙,请稍后重试!';
  914. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  915. 'member_id' => $memberId,
  916. 'amount' => $amount
  917. ]);
  918. return $result;
  919. }
  920. // 调用三方支付接口(在事务外)
  921. if (NoPayService::isWithdrawChannel($channel)) {
  922. try {
  923. $ret = NoPayService::withdraw($amount, $order_no, (string)$memberId, (string)$account, (string)$card_no);
  924. Log::channel('payment')->info('NO提现接口调用', [
  925. 'order_no' => $order_no,
  926. 'member_id' => $memberId,
  927. 'amount' => $amount,
  928. 'q_account' => $card_no,
  929. 'response' => $ret,
  930. ]);
  931. $success = (($ret['code'] ?? -1) == 0);
  932. $failureMessage = $ret['msg'] ?? 'NO提现失败';
  933. } catch (Exception $e) {
  934. $ret = ['msg' => $e->getMessage()];
  935. $success = false;
  936. $failureMessage = $e->getMessage();
  937. Log::channel('payment_error')->error('NO提现接口异常', [
  938. 'order_no' => $order_no,
  939. 'member_id' => $memberId,
  940. 'amount' => $amount,
  941. 'q_account' => $card_no,
  942. 'error' => $e->getMessage(),
  943. ]);
  944. }
  945. } elseif (ZimuPayService::isPayoutChannel($channel)) {
  946. try {
  947. self::assertZimuBalanceEnough($amount, [
  948. 'order_no' => $order_no,
  949. 'member_id' => $memberId,
  950. 'channel' => $channel,
  951. ]);
  952. if (ZimuPayService::isCashChannel($channel)) {
  953. $ret = ZimuPayService::cash(
  954. $amount,
  955. $order_no,
  956. (string)$account,
  957. (string)$card_no,
  958. (string)$bank_name,
  959. ZimuPayService::cashPayMethod((string)$bank_name)
  960. );
  961. } else {
  962. $ret = ZimuPayService::withdraw($amount, $order_no, (string)$memberId, (string)$card_no, $account);
  963. }
  964. Log::channel('payment')->info('ZIMU提现/代付接口调用', [
  965. 'order_no' => $order_no,
  966. 'member_id' => $memberId,
  967. 'amount' => $amount,
  968. 'channel' => $channel,
  969. 'response' => $ret,
  970. ]);
  971. $success = (($ret['code'] ?? -1) == 0);
  972. $failureMessage = $ret['msg'] ?? 'ZIMU提现/代付失败';
  973. } catch (Exception $e) {
  974. $ret = ['msg' => $e->getMessage()];
  975. $success = false;
  976. $failureMessage = $e->getMessage();
  977. Log::channel('payment_error')->error('ZIMU提现/代付接口异常', [
  978. 'order_no' => $order_no,
  979. 'member_id' => $memberId,
  980. 'amount' => $amount,
  981. 'channel' => $channel,
  982. 'error' => $e->getMessage(),
  983. ]);
  984. }
  985. } elseif (JdPayService::isChannel($channel)) {
  986. try {
  987. self::assertJdBalanceEnough($amount, [
  988. 'order_no' => $order_no,
  989. 'member_id' => $memberId,
  990. 'address' => $card_no,
  991. ]);
  992. $ret = JdPayService::remit($amount, $order_no, $card_no);
  993. Log::channel('payment')->info('JD下发接口调用', [
  994. 'order_no' => $order_no,
  995. 'member_id' => $memberId,
  996. 'amount' => $amount,
  997. 'address' => $card_no,
  998. 'response' => $ret,
  999. ]);
  1000. $success = (($ret['code'] ?? 0) == 200);
  1001. $failureMessage = $ret['message'] ?? 'JD下发失败';
  1002. if (!$success) {
  1003. $logContext = [
  1004. 'order_no' => $order_no,
  1005. 'member_id' => $memberId,
  1006. 'amount' => $amount,
  1007. 'address' => $card_no,
  1008. 'response' => $ret,
  1009. ];
  1010. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  1011. Log::error('JD下发接口失败', $logContext);
  1012. }
  1013. } catch (Exception $e) {
  1014. $ret = ['message' => $e->getMessage()];
  1015. $success = false;
  1016. $failureMessage = $e->getMessage();
  1017. $logContext = [
  1018. 'order_no' => $order_no,
  1019. 'member_id' => $memberId,
  1020. 'amount' => $amount,
  1021. 'address' => $card_no,
  1022. 'error' => $e->getMessage(),
  1023. ];
  1024. Log::channel('payment_error')->error('JD下发接口异常', $logContext);
  1025. Log::error('JD下发接口异常', $logContext);
  1026. }
  1027. } else {
  1028. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no, $channel);
  1029. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  1030. $success = (($ret['code'] ?? 0) == 200);
  1031. $failureMessage = $ret['msg'] ?? '代付失败';
  1032. }
  1033. if ($success) {
  1034. // 更新提现记录状态为处理中
  1035. DB::beginTransaction();
  1036. try {
  1037. $info->status = self::STATUS_PROCESS;
  1038. if (NoPayService::isWithdrawChannel($channel) || JdPayService::isChannel($channel) || ZimuPayService::isPayoutChannel($channel)) {
  1039. $info->pay_no = $ret['data']['orderNo'] ?? '';
  1040. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  1041. }
  1042. $info->save();
  1043. DB::commit();
  1044. $text = "✅ 提现申请已提交!\n\n";
  1045. $text .= "钱包余额:{$available_balance} RMB\n";
  1046. $text .= "提现金额:{$default_amount} RMB\n";
  1047. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  1048. $result['text'] = $text;
  1049. } catch (Exception $e) {
  1050. DB::rollBack();
  1051. // 状态更新失败,但资金已扣款且三方支付已成功
  1052. // 这里可以记录告警,需要人工干预
  1053. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  1054. 'member_id' => $memberId,
  1055. 'order_no' => $order_no
  1056. ]);
  1057. $result['text'] = '提现申请已提交,系统处理中...';
  1058. }
  1059. } //
  1060. else {
  1061. // 三方支付失败,需要回滚之前的预扣款
  1062. DB::beginTransaction();
  1063. try {
  1064. // 更新提现记录状态为失败
  1065. $info->status = self::STATUS_FAIL;
  1066. $info->remark = $failureMessage;
  1067. $info->save();
  1068. // 冻结余额退回可用余额,并记录退款日志
  1069. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $info, $default_amount, '三方提现', '提现失败退款');
  1070. DB::commit();
  1071. $result['text'] = $failureMessage;
  1072. } catch (Exception $e) {
  1073. DB::rollBack();
  1074. // 回滚失败,需要记录告警,人工干预
  1075. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  1076. 'member_id' => $memberId,
  1077. 'order_no' => $order_no,
  1078. 'amount' => $amount
  1079. ]);
  1080. $result['text'] = '提现失败,请联系客服处理退款!';
  1081. }
  1082. }
  1083. return $result;
  1084. }
  1085. /**
  1086. * @description: 接收三方订单
  1087. * @param {*} $params
  1088. * @return {*}
  1089. */
  1090. public static function receiveOrder($params)
  1091. {
  1092. if (ZimuPayService::getAppId() !== '' && ($params['appId'] ?? '') === ZimuPayService::getAppId()) {
  1093. $info = self::findOne(['order_no' => $params['mchOrderNo'] ?? '']);
  1094. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['mchOrderNo'] ?? '')))) {
  1095. if (!ZimuPayService::verifyNotify($params)
  1096. || bccomp(ZimuPayService::amount($agentPayout->actual_amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1097. Log::error('ZIMU代理提现回调验签或金额不一致', ['mch_order_no' => $params['mchOrderNo'] ?? '']);
  1098. return false;
  1099. }
  1100. $cash = ZimuPayService::isCashChannel((string)$agentPayout->account_type);
  1101. return self::agentPayoutResult($agentPayout, (string)($params['status'] ?? ''),
  1102. $cash ? ZimuPayService::CASH_STATUS_SUCCESS : ZimuPayService::WITHDRAW_STATUS_SUCCESS,
  1103. $cash ? ZimuPayService::CASH_STATUS_FAIL : ZimuPayService::WITHDRAW_STATUS_FAIL, $params);
  1104. }
  1105. if (!$info || $info->type != self::TYPE_PAYOUT || !ZimuPayService::isPayoutChannel($info->channel)) {
  1106. Log::error('ZIMU提现/代付回调订单不存在或类型不匹配', [
  1107. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  1108. 'order_id' => $info->id ?? null,
  1109. 'order_type' => $info->type ?? null,
  1110. 'channel' => $info->channel ?? null,
  1111. ]);
  1112. return false;
  1113. }
  1114. if (!ZimuPayService::verifyNotify($params)) {
  1115. Log::error('ZIMU提现/代付回调验签失败', [
  1116. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  1117. 'app_id' => $params['appId'] ?? '',
  1118. 'signature' => ZimuPayService::notifySignatureDiagnostics($params),
  1119. ]);
  1120. return false;
  1121. }
  1122. if (bccomp(ZimuPayService::amount($info->amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1123. Log::error('ZIMU提现/代付回调金额不一致', [
  1124. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  1125. 'order_amount' => $info->amount,
  1126. 'callback_amount' => $params['amount'] ?? null,
  1127. ]);
  1128. return false;
  1129. }
  1130. self::onSubmitZimuPayout($params, $info);
  1131. return true;
  1132. }
  1133. if (NoPayService::getWithdrawMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
  1134. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  1135. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['merchantOrderNo'] ?? '')))) {
  1136. if (!NoPayService::verifyWithdrawNotify($params)
  1137. || bccomp(NoPayService::amount($agentPayout->actual_amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1138. Log::error('NO代理提现回调验签或金额不一致', ['merchant_order_no' => $params['merchantOrderNo'] ?? '']);
  1139. return false;
  1140. }
  1141. return self::agentPayoutResult($agentPayout, (string)($params['state'] ?? ''),
  1142. NoPayService::STATE_SUCCESS, NoPayService::STATE_FAIL, $params);
  1143. }
  1144. if (!$info || $info->type != self::TYPE_PAYOUT || !NoPayService::isWithdrawChannel($info->channel)) {
  1145. Log::error('NO钱包提现回调订单不存在或类型不匹配', [
  1146. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  1147. 'order_id' => $info->id ?? null,
  1148. 'order_type' => $info->type ?? null,
  1149. 'channel' => $info->channel ?? null,
  1150. ]);
  1151. return false;
  1152. }
  1153. if (!NoPayService::verifyWithdrawNotify($params)) {
  1154. Log::error('NO钱包提现回调验签失败', [
  1155. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  1156. 'app_id' => $params['appId'] ?? '',
  1157. 'signature' => NoPayService::withdrawNotifySignatureDiagnostics($params),
  1158. ]);
  1159. return false;
  1160. }
  1161. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1162. Log::error('NO钱包提现回调金额不一致', [
  1163. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  1164. 'order_amount' => $info->amount,
  1165. 'callback_amount' => $params['amount'] ?? null,
  1166. ]);
  1167. return false;
  1168. }
  1169. self::onSubmitNoPayout($params, $info);
  1170. return true;
  1171. }
  1172. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  1173. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  1174. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  1175. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['customerOrderCode'] ?? ''), (string)($params['orderCode'] ?? '')))) {
  1176. if (!JdPayService::verifyRemitNotify($params)
  1177. || bccomp(JdPayService::amount($agentPayout->actual_amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1178. return false;
  1179. }
  1180. return self::agentPayoutResult($agentPayout, (string)($params['status'] ?? ''),
  1181. JdPayService::REMIT_STATUS_SUCCESS, JdPayService::REMIT_STATUS_FAIL, $params);
  1182. }
  1183. if (!$info || $info->type != self::TYPE_PAYOUT) {
  1184. return false;
  1185. }
  1186. if (!JdPayService::verifyRemitNotify($params)) {
  1187. return false;
  1188. }
  1189. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1190. return false;
  1191. }
  1192. self::onSubmitJdPayout($params, $info);
  1193. return true;
  1194. }
  1195. // 判断商户号是否一致
  1196. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  1197. $info = self::findOne(['order_no' => $params['orderNo']]);
  1198. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['orderNo'] ?? '')))) {
  1199. if (bccomp((string)$agentPayout->actual_amount, (string)($params['amount'] ?? 0), 2) !== 0
  1200. || ($params['sign'] ?? '') != QianBaoService::verifyNotifySign($params['state'] ?? '', $params['orderNo'], $params['amount'])) {
  1201. return false;
  1202. }
  1203. // 钱宝:state=1 成功,其他为失败(与会员代付一致)
  1204. $state = (string)($params['state'] ?? '');
  1205. return self::agentPayoutResult($agentPayout, $state, '1', $state === '1' ? '' : $state, $params);
  1206. }
  1207. if ($info) {
  1208. // 判断金额是不是正确认
  1209. if ($info->amount != $params['amount']) {
  1210. return false;
  1211. }
  1212. // 验证签名
  1213. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  1214. if ($params['sign'] != $sign) {
  1215. return false;
  1216. }
  1217. // 代付
  1218. if ($info->type == self::TYPE_PAYOUT) {
  1219. self::onSubmitPayout($params, $info);
  1220. }
  1221. // 代收
  1222. if ($info->type == self::TYPE_PAY) {
  1223. }
  1224. }
  1225. }
  1226. }
  1227. /** 三方代付回调的订单号不在会员订单里时,查代理提现(订单号 AW 开头;JD 也可按三方单号)。 */
  1228. private static function findAgentPayout(string $orderNo, string $payNo = ''): ?AgentWithdrawal
  1229. {
  1230. if ($orderNo === '' && $payNo === '') return null;
  1231. $order = $orderNo === '' ? null : AgentWithdrawal::query()->where('order_no', $orderNo)->first();
  1232. return $order ?: ($payNo === '' ? null : AgentWithdrawal::query()->where('pay_no', $payNo)->first());
  1233. }
  1234. /** 代理提现代付结果:成功扣冻结、失败退回代理余额;其他状态只记录回调。重复回调幂等。 */
  1235. private static function agentPayoutResult(AgentWithdrawal $withdrawal, string $status, string $success, string $fail, array $params): bool
  1236. {
  1237. $result = $status === $success ? true : ($fail !== '' && $status === $fail ? false : null);
  1238. app(AgentWithdrawalService::class)->providerResult((int)$withdrawal->id, $result, $params);
  1239. return true;
  1240. }
  1241. /**
  1242. * @description: 处理代付订单
  1243. * @param {*} $params
  1244. * @return {*}
  1245. */
  1246. public static function onSubmitJdPayout($params, $info)
  1247. {
  1248. if ($info->status != self::STATUS_PROCESS) {
  1249. return;
  1250. }
  1251. $memberId = $info->member_id;
  1252. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  1253. $data = [];
  1254. $chat_id = $info->member_id;
  1255. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1256. DB::beginTransaction();
  1257. try {
  1258. $locked = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
  1259. if (!$locked || $locked->status != self::STATUS_PROCESS) {
  1260. DB::rollBack();
  1261. return;
  1262. }
  1263. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  1264. $data['status'] = self::STATUS_SUCCESS;
  1265. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  1266. AdminRealtime::record('payment_orders', $info->id);
  1267. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $locked);
  1268. if ($res) {
  1269. $text = "✅ 提现通知 \n";
  1270. $text .= "提现平台:{$info->bank_name} \n";
  1271. $text .= "收款人:{$info->account} \n";
  1272. $text .= "收款地址:{$info->card_no} \n";
  1273. $text .= "提现金额:{$info->amount} \n";
  1274. $text .= "提现成功,金额已到账,请注意查收!";
  1275. self::notifyUser($chat_id, $text);
  1276. }
  1277. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  1278. $data['status'] = self::STATUS_FAIL;
  1279. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  1280. AdminRealtime::record('payment_orders', $info->id);
  1281. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $locked, $amount, '三方提现', '提现失败退款');
  1282. if ($res) {
  1283. $text = "❌ 提现通知 \n";
  1284. $text .= "提现平台:{$info->bank_name} \n";
  1285. $text .= "收款人:{$info->account} \n";
  1286. $text .= "收款地址:{$info->card_no} \n";
  1287. $text .= "提现金额:{$info->amount} \n";
  1288. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1289. self::notifyUser($chat_id, $text);
  1290. }
  1291. }
  1292. DB::commit();
  1293. } catch (Exception $e) {
  1294. DB::rollBack();
  1295. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  1296. }
  1297. }
  1298. public static function onSubmitNoPayout($params, $info)
  1299. {
  1300. $notification = null;
  1301. try {
  1302. DB::transaction(function () use ($params, $info, &$notification) {
  1303. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  1304. if (!$order || $order->status != self::STATUS_PROCESS) {
  1305. return;
  1306. }
  1307. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  1308. if ((string)$params['state'] === NoPayService::STATE_SUCCESS) {
  1309. $order->status = self::STATUS_SUCCESS;
  1310. $order->save();
  1311. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $order);
  1312. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  1313. } elseif ((string)$params['state'] === NoPayService::STATE_FAIL) {
  1314. $order->status = self::STATUS_FAIL;
  1315. $order->save();
  1316. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, NoPayService::amount($order->amount), '三方提现', '提现失败退款');
  1317. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  1318. } else {
  1319. $order->save();
  1320. }
  1321. }, 3);
  1322. if ($notification !== null) {
  1323. self::notifyUser($info->member_id, $notification);
  1324. }
  1325. } catch (Exception $e) {
  1326. Log::channel('payment_error')->error('NO提现回调处理异常', [
  1327. 'order_id' => $info->id,
  1328. 'params' => $params,
  1329. 'error' => $e->getMessage(),
  1330. ]);
  1331. }
  1332. }
  1333. public static function onSubmitZimuPayout($params, $info)
  1334. {
  1335. $notification = null;
  1336. $successStatus = ZimuPayService::isCashChannel($info->channel)
  1337. ? ZimuPayService::CASH_STATUS_SUCCESS
  1338. : ZimuPayService::WITHDRAW_STATUS_SUCCESS;
  1339. $failStatus = ZimuPayService::isCashChannel($info->channel)
  1340. ? ZimuPayService::CASH_STATUS_FAIL
  1341. : ZimuPayService::WITHDRAW_STATUS_FAIL;
  1342. try {
  1343. DB::transaction(function () use ($params, $info, &$notification, $successStatus, $failStatus) {
  1344. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  1345. if (!$order || $order->status != self::STATUS_PROCESS) {
  1346. return;
  1347. }
  1348. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  1349. if ((string)$params['status'] === $successStatus) {
  1350. $order->status = self::STATUS_SUCCESS;
  1351. $order->save();
  1352. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $order);
  1353. $accountLabel = ZimuPayService::isCashChannel($order->channel) ? '收款账号' : '808钱包地址';
  1354. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \n{$accountLabel}:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  1355. } elseif ((string)$params['status'] === $failStatus) {
  1356. $order->status = self::STATUS_FAIL;
  1357. $order->save();
  1358. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, ZimuPayService::amount($order->amount), '三方提现', '提现失败退款');
  1359. $accountLabel = ZimuPayService::isCashChannel($order->channel) ? '收款账号' : '808钱包地址';
  1360. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \n{$accountLabel}:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  1361. } else {
  1362. $order->save();
  1363. }
  1364. }, 3);
  1365. if ($notification !== null) {
  1366. self::notifyUser($info->member_id, $notification);
  1367. }
  1368. } catch (Exception $e) {
  1369. Log::channel('payment_error')->error('ZIMU提现/代付回调处理异常', [
  1370. 'order_id' => $info->id,
  1371. 'params' => $params,
  1372. 'error' => $e->getMessage(),
  1373. ]);
  1374. }
  1375. }
  1376. public static function onSubmitPayout($params, $info)
  1377. {
  1378. $memberId = $info->member_id;
  1379. $amount = $params['amount'];
  1380. $data = [];
  1381. $result = [];
  1382. $chat_id = $info->member_id;
  1383. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1384. DB::beginTransaction();
  1385. try {
  1386. // 只处理“处理中”的代付单,避免重复回调重复退款
  1387. $locked = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
  1388. if (!$locked || $locked->status != self::STATUS_PROCESS) {
  1389. DB::rollBack();
  1390. return;
  1391. }
  1392. if ($params['state'] == 1) {
  1393. $data['status'] = self::STATUS_SUCCESS;
  1394. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1395. AdminRealtime::record('payment_orders', $info->id);
  1396. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $locked);
  1397. if ($res) {
  1398. $text = "✅ 提现通知 \n";
  1399. $text .= "提现平台:{$info->bank_name} \n";
  1400. $text .= "收款人:{$info->account} \n";
  1401. $text .= "收款卡号:{$info->card_no} \n";
  1402. $text .= "提现金额:{$info->amount} \n";
  1403. $text .= "提现成功,金额已到账,请注意查收!";
  1404. self::notifyUser($chat_id, $text);
  1405. }
  1406. } else {
  1407. $data['status'] = self::STATUS_FAIL;
  1408. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1409. AdminRealtime::record('payment_orders', $info->id);
  1410. // 冻结余额退回可用余额,并记录退款日志
  1411. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $locked, $amount, '三方提现', '提现失败退款');
  1412. if ($res) {
  1413. $text = "❌ 提现通知 \n";
  1414. $text .= "提现平台:{$info->bank_name} \n";
  1415. $text .= "收款人:{$info->account} \n";
  1416. $text .= "收款卡号:{$info->card_no} \n";
  1417. $text .= "提现金额:{$info->amount} \n";
  1418. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1419. self::notifyUser($chat_id, $text);
  1420. }
  1421. }
  1422. DB::commit();
  1423. } catch (Exception $e) {
  1424. DB::rollBack();
  1425. // 回滚失败,需要记录告警,人工干预
  1426. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  1427. }
  1428. }
  1429. /**
  1430. * @description: 查询支付订单
  1431. * @param {*} $id
  1432. * @return {*}
  1433. */
  1434. public static function singlePayOrder($id)
  1435. {
  1436. return self::queryPayOrder(self::findOne(['id' => $id]));
  1437. }
  1438. /** 向三方查询在线充值订单并按结果入账。会员和代理订单共用。 */
  1439. public static function queryPayOrder(?PaymentOrder $info): array
  1440. {
  1441. $msg = [];
  1442. $msg['code'] = self::NOT;
  1443. if ($info && (int)$info->type === self::TYPE_PAY && in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
  1444. if (NoPayService::isRechargeChannel($info->channel)) {
  1445. $ret = NoPayService::queryPayOrder($info->order_no, (string)$info->member_id);
  1446. Log::channel('payment')->info('NO支付查询订单', $ret);
  1447. if (($ret['code'] ?? -1) == 0) {
  1448. $item = $ret['data'] ?? [];
  1449. if ((string)($item['state'] ?? '') === NoPayService::STATE_SUCCESS) {
  1450. $processed = self::applyPayCallback(
  1451. $info,
  1452. NoPayService::amount($info->amount),
  1453. NoPayService::STATE_SUCCESS,
  1454. NoPayService::STATE_SUCCESS,
  1455. NoPayService::STATE_FAIL,
  1456. $ret
  1457. );
  1458. $msg['code'] = $processed ? self::YES : self::NOT;
  1459. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1460. } elseif ((string)($item['state'] ?? '') === NoPayService::STATE_FAIL) {
  1461. self::applyPayCallback(
  1462. $info,
  1463. NoPayService::amount($info->amount),
  1464. NoPayService::STATE_FAIL,
  1465. NoPayService::STATE_SUCCESS,
  1466. NoPayService::STATE_FAIL,
  1467. $ret
  1468. );
  1469. $msg['msg'] = '支付失败';
  1470. } else {
  1471. $msg['msg'] = '支付中';
  1472. }
  1473. } else {
  1474. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1475. }
  1476. return $msg;
  1477. }
  1478. if (ZimuPayService::isRechargeChannel($info->channel)) {
  1479. $ret = ZimuPayService::queryPayOrder($info->order_no);
  1480. Log::channel('payment')->info('ZIMU支付查询订单', $ret);
  1481. if (($ret['code'] ?? -1) == 0) {
  1482. $item = $ret['data'] ?? [];
  1483. if ((string)($item['status'] ?? '') === ZimuPayService::PAY_STATUS_SUCCESS) {
  1484. $processed = self::applyPayCallback(
  1485. $info,
  1486. ZimuPayService::amount($info->amount),
  1487. ZimuPayService::PAY_STATUS_SUCCESS,
  1488. ZimuPayService::PAY_STATUS_SUCCESS,
  1489. ZimuPayService::PAY_STATUS_FAIL,
  1490. $ret
  1491. );
  1492. $msg['code'] = $processed ? self::YES : self::NOT;
  1493. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1494. } elseif ((string)($item['status'] ?? '') === ZimuPayService::PAY_STATUS_FAIL) {
  1495. self::applyPayCallback(
  1496. $info,
  1497. ZimuPayService::amount($info->amount),
  1498. ZimuPayService::PAY_STATUS_FAIL,
  1499. ZimuPayService::PAY_STATUS_SUCCESS,
  1500. ZimuPayService::PAY_STATUS_FAIL,
  1501. $ret
  1502. );
  1503. $msg['msg'] = '支付失败';
  1504. } else {
  1505. $msg['msg'] = '支付中';
  1506. }
  1507. } else {
  1508. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1509. }
  1510. return $msg;
  1511. }
  1512. if (JdPayService::isChannel($info->channel)) {
  1513. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  1514. Log::channel('payment')->info('JD支付查询订单', $ret);
  1515. if (($ret['code'] ?? 0) == 200) {
  1516. $item = $ret['data'] ?? [];
  1517. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  1518. $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), JdPayService::PAY_STATUS_SUCCESS,
  1519. JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $ret);
  1520. $msg['code'] = $processed ? self::YES : self::NOT;
  1521. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1522. } else {
  1523. $msg['msg'] = '支付中';
  1524. }
  1525. } else {
  1526. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  1527. }
  1528. return $msg;
  1529. }
  1530. $ret = SanJinService::queryOrder($info->order_no);
  1531. Log::error('三斤支付查询订单:', $ret);
  1532. if ($ret['code'] == 0) {
  1533. $item = [];
  1534. $item['state'] = $ret['data']['state'];
  1535. if ($ret['data']['state'] == 1) {
  1536. $processed = self::applyPayCallback($info, (string)$info->amount, '1', '1', null, $ret);
  1537. $msg['code'] = $processed ? self::YES : self::NOT;
  1538. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1539. } else {
  1540. $msg['msg'] = '支付中';
  1541. }
  1542. } else {
  1543. $msg['msg'] = '查询失败:' . $ret['message'];
  1544. }
  1545. } else {
  1546. $msg['msg'] = '该状态无法查询';
  1547. }
  1548. return $msg;
  1549. }
  1550. private static function assertJdBalanceEnough($amount, array $context = []): void
  1551. {
  1552. $ret = JdPayService::balance();
  1553. Log::channel('payment')->info('JD余额查询', $context + [
  1554. 'amount' => $amount,
  1555. 'response' => $ret,
  1556. ]);
  1557. if (($ret['code'] ?? 0) != 200) {
  1558. $logContext = $context + [
  1559. 'amount' => $amount,
  1560. 'response' => $ret,
  1561. ];
  1562. Log::channel('payment_error')->error('JD余额查询失败', $logContext);
  1563. Log::error('JD余额查询失败', $logContext);
  1564. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  1565. }
  1566. $balance = $ret['data']['balance'] ?? null;
  1567. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  1568. $logContext = $context + [
  1569. 'amount' => $amount,
  1570. 'balance' => $balance,
  1571. 'response' => $ret,
  1572. ];
  1573. Log::channel('payment_error')->error('JD商户余额不足', $logContext);
  1574. Log::error('JD商户余额不足', $logContext);
  1575. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  1576. }
  1577. }
  1578. private static function assertZimuBalanceEnough($amount, array $context = []): void
  1579. {
  1580. $ret = ZimuPayService::balance();
  1581. Log::channel('payment')->info('ZIMU余额查询', $context + [
  1582. 'amount' => $amount,
  1583. 'response' => $ret,
  1584. ]);
  1585. if (($ret['code'] ?? -1) != 0) {
  1586. $logContext = $context + [
  1587. 'amount' => $amount,
  1588. 'response' => $ret,
  1589. ];
  1590. Log::channel('payment_error')->error('ZIMU余额查询失败', $logContext);
  1591. Log::error('ZIMU余额查询失败', $logContext);
  1592. throw new Exception($ret['msg'] ?? 'ZIMU余额查询失败', HttpStatus::CUSTOM_ERROR);
  1593. }
  1594. $balance = $ret['data']['balance'] ?? null;
  1595. if ($balance === null || bccomp((string)$balance, ZimuPayService::amount($amount), 2) < 0) {
  1596. $logContext = $context + [
  1597. 'amount' => $amount,
  1598. 'balance' => $balance,
  1599. 'response' => $ret,
  1600. ];
  1601. Log::channel('payment_error')->error('ZIMU商户余额不足', $logContext);
  1602. Log::error('ZIMU商户余额不足', $logContext);
  1603. throw new Exception('ZIMU商户余额不足', HttpStatus::CUSTOM_ERROR);
  1604. }
  1605. }
  1606. private static function notifyUser($chatId, string $text): void
  1607. {
  1608. if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
  1609. return;
  1610. }
  1611. try {
  1612. self::sendMessage($chatId, $text);
  1613. } catch (\Throwable $e) {
  1614. Log::channel('payment_error')->error('支付订单用户通知失败', [
  1615. 'chat_id' => $chatId,
  1616. 'error' => $e->getMessage(),
  1617. ]);
  1618. }
  1619. }
  1620. public static function syncPayOrder()
  1621. {
  1622. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  1623. // foreach($list->toArray() as $k => $v){
  1624. // $item= [];
  1625. // if($v['status'] == self::STATUS_SUCCESS){
  1626. // $item['state'] = 1;
  1627. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1628. // }else{
  1629. // $ret = SanJinService::queryOrder($v['order_no']);
  1630. // var_dump($ret);
  1631. // if($ret['code'] == 0){
  1632. // $item['state'] = $ret['data']['state'];
  1633. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1634. // }
  1635. // }
  1636. // }
  1637. }
  1638. }