PaymentOrderService.php 81 KB

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