PaymentOrderService.php 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  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 = \App\Support\MemberAudience::visibleUsers(static::$MODEL::where(self::getWhere($search))
  139. ->join('users', 'users.member_id', '=', 'payment_orders.member_id'), 'users') // 后台模拟会员只在模拟管理里出现
  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. /** 模拟管理:把模拟会员的代收单按“成功回调”入账,与真实回调走同一段入账代码,不向三方发任何请求。 */
  660. public static function simulatePaySuccess(PaymentOrder $order): bool
  661. {
  662. if (!\App\Support\MemberAudience::isSimulatedMember($order->member_id)) {
  663. throw new Exception('只能对模拟会员的订单执行模拟入账', HttpStatus::CUSTOM_ERROR);
  664. }
  665. return self::applyPayCallback($order, $order->amount, 'SIM', 'SIM', null, ['simulation' => true]);
  666. }
  667. private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
  668. {
  669. return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
  670. $order = $info::query()->where('id', $info->id)->lockForUpdate()->first();
  671. if (!$order || (int)$order->type !== self::TYPE_PAY || !in_array((int)$order->status, self::PAY_OPEN_STATUSES, true)) {
  672. return false;
  673. }
  674. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  675. $order->state = $status;
  676. if ($status === $successStatus) {
  677. $order->status = self::STATUS_SUCCESS;
  678. $order->save();
  679. if ($order instanceof AgentPaymentOrder) {
  680. // 代理订单入代理钱包(合营计入保证金),不发充值优惠。
  681. app(AgentPaymentService::class)->credit($order, (string)$payAmount, 'system', null);
  682. return true;
  683. }
  684. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  685. if (!$wallet) {
  686. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  687. }
  688. $balance = $wallet->available_balance;
  689. $availableBalance = bcadd($balance, $payAmount, 10);
  690. $wallet->available_balance = $availableBalance;
  691. $wallet->save();
  692. $principal = BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
  693. RechargeBonusService::grant('payment_order', $order, $principal);
  694. // Deposit hooks can grant an immediately available first-deposit reward.
  695. $wallet->refresh();
  696. return true;
  697. }
  698. if ($failStatus === null || $status === $failStatus) {
  699. $order->status = self::STATUS_FAIL;
  700. }
  701. $order->save();
  702. return true;
  703. }, 3);
  704. }
  705. /**
  706. * 拒绝提现
  707. * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
  708. * @param int $orderId 订单ID PaymentOrder 表的ID
  709. * @param string $remark 失败原因
  710. * @return array
  711. */
  712. public static function withdrawalFailed($orderId, $remark): array
  713. {
  714. try {
  715. DB::transaction(function () use ($orderId, $remark) {
  716. $order = PaymentOrder::where('id', $orderId)
  717. ->whereIn('type', [2,4])
  718. ->where('status', self::STATUS_STAY)
  719. ->lockForUpdate()
  720. ->first();
  721. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  722. // 更新提现记录状态为失败
  723. $order->status = self::STATUS_FAIL;
  724. $order->remark = $remark;
  725. if (!$order->save()) {
  726. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  727. }
  728. // 冻结余额退回可用余额,并记录退款日志
  729. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, $order->amount, '三方提现', '提现失败退款');
  730. }, 3);
  731. } catch (Exception $e) {
  732. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  733. }
  734. return ['code' => 0, 'msg' => 'ok'];
  735. }
  736. /**
  737. * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
  738. * @param int $orderId PaymentOrder 表的ID
  739. */
  740. public static function createPayout(int $orderId): array
  741. {
  742. try {
  743. $order = PaymentOrder::where('id', $orderId)
  744. ->where('type', 2)
  745. ->where('status', self::STATUS_STAY)
  746. ->first();
  747. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  748. $ret = self::requestPayout((string)$order->channel, (string)$order->order_no, (string)$order->member_id, $order->amount,
  749. (string)$order->account, (string)$order->card_no, (string)$order->bank_name, ['order_id' => $order->id]);
  750. if ($ret['pay_no'] !== null) $order->pay_no = $ret['pay_no'];
  751. if ($ret['pay_data'] !== null) $order->pay_data = $ret['pay_data'];
  752. $order->status = self::STATUS_PROCESS;
  753. $order->save();
  754. } catch (Exception $e) {
  755. Log::channel('payment_error')->error('创建代付订单失败', [
  756. 'order_id' => $orderId,
  757. 'error' => $e->getMessage(),
  758. ]);
  759. Log::error('创建代付订单失败', [
  760. 'order_id' => $orderId,
  761. 'error' => $e->getMessage(),
  762. ]);
  763. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  764. }
  765. return ['code' => 0, 'msg' => 'ok'];
  766. }
  767. /**
  768. * 向三方发起代付(NO/808/JD/钱宝),会员提现和代理提现共用。失败抛异常;成功返回三方单号和下单返回。
  769. * $memberId:会员为 member_id,代理为 AG{代理ID};$context 只用于日志。
  770. */
  771. public static function requestPayout(string $channel, string $orderNo, string $memberId, $amount, string $accountName, string $cardNo, string $bankName, array $context = []): array
  772. {
  773. $payNo = null;
  774. $payData = null;
  775. if (!PaymentProviderService::requestEnabled($channel, 2)) {
  776. throw new Exception('支付公司已禁用', HttpStatus::CUSTOM_ERROR);
  777. }
  778. if (!RechargeChannel::query()->where('data_type', 2)->where('type', $channel)->available()->exists()) {
  779. throw new Exception('提现通道已停用或删除', HttpStatus::CUSTOM_ERROR);
  780. }
  781. $amount = number_format($amount, 2, '.', '');
  782. if (NoPayService::isWithdrawChannel($channel)) {
  783. $ret = NoPayService::withdraw($amount, $orderNo, $memberId, $accountName, $cardNo);
  784. Log::channel('payment')->info('NO提现接口调用', [
  785. 'order_id' => ($context['order_id'] ?? null),
  786. 'order_no' => $orderNo,
  787. 'member_id' => $memberId,
  788. 'amount' => $amount,
  789. 'q_account' => $cardNo,
  790. 'response' => $ret,
  791. ]);
  792. if (($ret['code'] ?? -1) != 0) {
  793. throw new Exception($ret['msg'] ?? 'NO提现失败', HttpStatus::CUSTOM_ERROR);
  794. }
  795. $payNo = $ret['data']['orderNo'] ?? '';
  796. $payData = json_encode($ret, JSON_UNESCAPED_UNICODE);
  797. } elseif (ZimuPayService::isPayoutChannel($channel)) {
  798. self::assertZimuBalanceEnough($amount, [
  799. 'order_id' => ($context['order_id'] ?? null),
  800. 'order_no' => $orderNo,
  801. 'member_id' => $memberId,
  802. 'channel' => $channel,
  803. ]);
  804. if (ZimuPayService::isCashChannel($channel)) {
  805. $ret = ZimuPayService::cash(
  806. $amount,
  807. $orderNo,
  808. $accountName,
  809. $cardNo,
  810. $bankName,
  811. ZimuPayService::cashPayMethod($bankName)
  812. );
  813. } else {
  814. $ret = ZimuPayService::withdraw($amount, $orderNo, $memberId, $cardNo, $accountName);
  815. }
  816. Log::channel('payment')->info('ZIMU提现/代付接口调用', [
  817. 'order_id' => ($context['order_id'] ?? null),
  818. 'order_no' => $orderNo,
  819. 'member_id' => $memberId,
  820. 'amount' => $amount,
  821. 'channel' => $channel,
  822. 'response' => $ret,
  823. ]);
  824. if (($ret['code'] ?? -1) != 0) {
  825. throw new Exception($ret['msg'] ?? 'ZIMU提现/代付失败', HttpStatus::CUSTOM_ERROR);
  826. }
  827. $payNo = $ret['data']['orderNo'] ?? '';
  828. $payData = json_encode($ret, JSON_UNESCAPED_UNICODE);
  829. } elseif (JdPayService::isChannel($channel)) {
  830. self::assertJdBalanceEnough($amount, [
  831. 'order_id' => ($context['order_id'] ?? null),
  832. 'order_no' => $orderNo,
  833. 'member_id' => $memberId,
  834. 'address' => $cardNo,
  835. ]);
  836. $ret = JdPayService::remit($amount, $orderNo, $cardNo);
  837. Log::channel('payment')->info('JD下发接口调用', [
  838. 'order_id' => ($context['order_id'] ?? null),
  839. 'order_no' => $orderNo,
  840. 'member_id' => $memberId,
  841. 'amount' => $amount,
  842. 'address' => $cardNo,
  843. 'response' => $ret,
  844. ]);
  845. if (($ret['code'] ?? 0) != 200) {
  846. $logContext = [
  847. 'order_id' => ($context['order_id'] ?? null),
  848. 'order_no' => $orderNo,
  849. 'member_id' => $memberId,
  850. 'amount' => $amount,
  851. 'address' => $cardNo,
  852. 'response' => $ret,
  853. ];
  854. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  855. Log::error('JD下发接口失败', $logContext);
  856. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  857. }
  858. $payNo = $ret['data']['orderNo'] ?? '';
  859. $payData = json_encode($ret, JSON_UNESCAPED_UNICODE);
  860. } else {
  861. $ret = QianBaoService::payout(
  862. $amount, $orderNo, $bankName, $accountName, $cardNo, $channel
  863. );
  864. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  865. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  866. }
  867. return ['pay_no' => $payNo, 'pay_data' => $payData];
  868. }
  869. /**
  870. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  871. * @param {*} $memberId 会员ID
  872. * @param {*} $amount 代付金额
  873. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  874. * @param {*} $bank_name 银行名称/支付宝
  875. * @param {*} $card_no 银行卡号/支付宝账号
  876. * @return {*}
  877. */
  878. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $card_no, ?string $bankBranch = null)
  879. {
  880. $default_amount = $amount;
  881. $result = [];
  882. $result['chat_id'] = $memberId;
  883. if ($channel === 'rgtx') {
  884. $result['text'] = lang('不支持此提现方式');
  885. return $result;
  886. }
  887. if (!PaymentProviderService::requestEnabled((string)$channel, 2)) {
  888. $result['text'] = '支付公司已禁用';
  889. return $result;
  890. }
  891. $user = User::query()->where('member_id', $memberId)->first();
  892. $groupId = (int)($user->recharge_channel_group_id ?? 1);
  893. $channelConfig = RechargeChannel::checkWithdrawChannel($channel, $groupId);
  894. if ($channelConfig === false) {
  895. $result['text'] = '不支持此提现方式';
  896. return $result;
  897. }
  898. $minAmount = (float)($channelConfig->min ?? 0);
  899. $maxAmount = (float)($channelConfig->max ?? 0);
  900. if ($amount < $minAmount || ($maxAmount > 0 && $amount > $maxAmount)) {
  901. $result['text'] = "提现金额范围为{$minAmount}-{$maxAmount}";
  902. return $result;
  903. }
  904. $channelRate = (float)($channelConfig->rate ?? 0);
  905. $channelFixed = $channelConfig->fee_fixed ?? 0;
  906. $feeText = RechargeChannel::feeDisplay($channelRate, $channelFixed)['fee_text'];
  907. // 在调用三方支付前开始事务
  908. DB::beginTransaction();
  909. try {
  910. $account = WithdrawalName::forPayout($user, $channel);
  911. $bankBranch = WithdrawalDestination::bankBranch($channel, $bank_name, $bankBranch);
  912. $data = [];
  913. $data['type'] = self::TYPE_PAYOUT;
  914. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  915. $data['order_no'] = $order_no;
  916. $data['member_id'] = $memberId;
  917. $data += self::feeFields($amount, $channelRate, $channelFixed);
  918. $amount = number_format($amount, 2, '.', '');
  919. $data['amount'] = $amount;
  920. $data['channel'] = $channel;
  921. $data['bank_name'] = $bank_name;
  922. if ($bankBranch !== null) {
  923. $data['bank_branch'] = $bankBranch;
  924. }
  925. $data['account'] = $account;
  926. $data['card_no'] = $card_no;
  927. if (NoPayService::isWithdrawChannel($channel)) {
  928. $data['callback_url'] = NoPayService::getWithdrawNotifyUrl();
  929. } elseif (JdPayService::isChannel($channel)) {
  930. $data['callback_url'] = JdPayService::getRemitNotifyUrl();
  931. } elseif (ZimuPayService::isPayoutChannel($channel)) {
  932. $data['callback_url'] = ZimuPayService::getPayoutNotifyUrl();
  933. } else {
  934. $data['callback_url'] = QianBaoService::getNotifyUrl();
  935. }
  936. $data['status'] = self::STATUS_STAY;
  937. $data['remark'] = '三方提现手续费:' . $feeText;
  938. // 校验打码量 → 冻结资金 → 创建待处理的提现记录 → 重置打码周期
  939. [$info, $wallet] = WithdrawFundsService::hold((string)$memberId, $default_amount, '三方提现', '三方提现手续费:' . $feeText,
  940. WithdrawFundsService::PAYMENT_ORDERS, fn () => static::$MODEL::create($data));
  941. $id = $info->id;
  942. $available_balance = $wallet->available_balance;
  943. // 提交事务,确保预扣款成功
  944. DB::commit();
  945. } //
  946. catch (Exception $e) {
  947. // 预扣款失败,回滚事务
  948. DB::rollBack();
  949. $result['text'] = $e->getCode() === HttpStatus::CUSTOM_ERROR ? $e->getMessage() : '系统繁忙,请稍后重试!';
  950. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  951. 'member_id' => $memberId,
  952. 'amount' => $amount
  953. ]);
  954. return $result;
  955. }
  956. // 调用三方支付接口(在事务外)
  957. if (NoPayService::isWithdrawChannel($channel)) {
  958. try {
  959. $ret = NoPayService::withdraw($amount, $order_no, (string)$memberId, (string)$account, (string)$card_no);
  960. Log::channel('payment')->info('NO提现接口调用', [
  961. 'order_no' => $order_no,
  962. 'member_id' => $memberId,
  963. 'amount' => $amount,
  964. 'q_account' => $card_no,
  965. 'response' => $ret,
  966. ]);
  967. $success = (($ret['code'] ?? -1) == 0);
  968. $failureMessage = $ret['msg'] ?? 'NO提现失败';
  969. } catch (Exception $e) {
  970. $ret = ['msg' => $e->getMessage()];
  971. $success = false;
  972. $failureMessage = $e->getMessage();
  973. Log::channel('payment_error')->error('NO提现接口异常', [
  974. 'order_no' => $order_no,
  975. 'member_id' => $memberId,
  976. 'amount' => $amount,
  977. 'q_account' => $card_no,
  978. 'error' => $e->getMessage(),
  979. ]);
  980. }
  981. } elseif (ZimuPayService::isPayoutChannel($channel)) {
  982. try {
  983. self::assertZimuBalanceEnough($amount, [
  984. 'order_no' => $order_no,
  985. 'member_id' => $memberId,
  986. 'channel' => $channel,
  987. ]);
  988. if (ZimuPayService::isCashChannel($channel)) {
  989. $ret = ZimuPayService::cash(
  990. $amount,
  991. $order_no,
  992. (string)$account,
  993. (string)$card_no,
  994. (string)$bank_name,
  995. ZimuPayService::cashPayMethod((string)$bank_name)
  996. );
  997. } else {
  998. $ret = ZimuPayService::withdraw($amount, $order_no, (string)$memberId, (string)$card_no, $account);
  999. }
  1000. Log::channel('payment')->info('ZIMU提现/代付接口调用', [
  1001. 'order_no' => $order_no,
  1002. 'member_id' => $memberId,
  1003. 'amount' => $amount,
  1004. 'channel' => $channel,
  1005. 'response' => $ret,
  1006. ]);
  1007. $success = (($ret['code'] ?? -1) == 0);
  1008. $failureMessage = $ret['msg'] ?? 'ZIMU提现/代付失败';
  1009. } catch (Exception $e) {
  1010. $ret = ['msg' => $e->getMessage()];
  1011. $success = false;
  1012. $failureMessage = $e->getMessage();
  1013. Log::channel('payment_error')->error('ZIMU提现/代付接口异常', [
  1014. 'order_no' => $order_no,
  1015. 'member_id' => $memberId,
  1016. 'amount' => $amount,
  1017. 'channel' => $channel,
  1018. 'error' => $e->getMessage(),
  1019. ]);
  1020. }
  1021. } elseif (JdPayService::isChannel($channel)) {
  1022. try {
  1023. self::assertJdBalanceEnough($amount, [
  1024. 'order_no' => $order_no,
  1025. 'member_id' => $memberId,
  1026. 'address' => $card_no,
  1027. ]);
  1028. $ret = JdPayService::remit($amount, $order_no, $card_no);
  1029. Log::channel('payment')->info('JD下发接口调用', [
  1030. 'order_no' => $order_no,
  1031. 'member_id' => $memberId,
  1032. 'amount' => $amount,
  1033. 'address' => $card_no,
  1034. 'response' => $ret,
  1035. ]);
  1036. $success = (($ret['code'] ?? 0) == 200);
  1037. $failureMessage = $ret['message'] ?? 'JD下发失败';
  1038. if (!$success) {
  1039. $logContext = [
  1040. 'order_no' => $order_no,
  1041. 'member_id' => $memberId,
  1042. 'amount' => $amount,
  1043. 'address' => $card_no,
  1044. 'response' => $ret,
  1045. ];
  1046. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  1047. Log::error('JD下发接口失败', $logContext);
  1048. }
  1049. } catch (Exception $e) {
  1050. $ret = ['message' => $e->getMessage()];
  1051. $success = false;
  1052. $failureMessage = $e->getMessage();
  1053. $logContext = [
  1054. 'order_no' => $order_no,
  1055. 'member_id' => $memberId,
  1056. 'amount' => $amount,
  1057. 'address' => $card_no,
  1058. 'error' => $e->getMessage(),
  1059. ];
  1060. Log::channel('payment_error')->error('JD下发接口异常', $logContext);
  1061. Log::error('JD下发接口异常', $logContext);
  1062. }
  1063. } else {
  1064. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no, $channel);
  1065. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  1066. $success = (($ret['code'] ?? 0) == 200);
  1067. $failureMessage = $ret['msg'] ?? '代付失败';
  1068. }
  1069. if ($success) {
  1070. // 更新提现记录状态为处理中
  1071. DB::beginTransaction();
  1072. try {
  1073. $info->status = self::STATUS_PROCESS;
  1074. if (NoPayService::isWithdrawChannel($channel) || JdPayService::isChannel($channel) || ZimuPayService::isPayoutChannel($channel)) {
  1075. $info->pay_no = $ret['data']['orderNo'] ?? '';
  1076. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  1077. }
  1078. $info->save();
  1079. DB::commit();
  1080. $text = "✅ 提现申请已提交!\n\n";
  1081. $text .= "钱包余额:{$available_balance} RMB\n";
  1082. $text .= "提现金额:{$default_amount} RMB\n";
  1083. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  1084. $result['text'] = $text;
  1085. } catch (Exception $e) {
  1086. DB::rollBack();
  1087. // 状态更新失败,但资金已扣款且三方支付已成功
  1088. // 这里可以记录告警,需要人工干预
  1089. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  1090. 'member_id' => $memberId,
  1091. 'order_no' => $order_no
  1092. ]);
  1093. $result['text'] = '提现申请已提交,系统处理中...';
  1094. }
  1095. } //
  1096. else {
  1097. // 三方支付失败,需要回滚之前的预扣款
  1098. DB::beginTransaction();
  1099. try {
  1100. // 更新提现记录状态为失败
  1101. $info->status = self::STATUS_FAIL;
  1102. $info->remark = $failureMessage;
  1103. $info->save();
  1104. // 冻结余额退回可用余额,并记录退款日志
  1105. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $info, $default_amount, '三方提现', '提现失败退款');
  1106. DB::commit();
  1107. $result['text'] = $failureMessage;
  1108. } catch (Exception $e) {
  1109. DB::rollBack();
  1110. // 回滚失败,需要记录告警,人工干预
  1111. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  1112. 'member_id' => $memberId,
  1113. 'order_no' => $order_no,
  1114. 'amount' => $amount
  1115. ]);
  1116. $result['text'] = '提现失败,请联系客服处理退款!';
  1117. }
  1118. }
  1119. return $result;
  1120. }
  1121. /**
  1122. * @description: 接收三方订单
  1123. * @param {*} $params
  1124. * @return {*}
  1125. */
  1126. public static function receiveOrder($params)
  1127. {
  1128. if (ZimuPayService::getAppId() !== '' && ($params['appId'] ?? '') === ZimuPayService::getAppId()) {
  1129. $info = self::findOne(['order_no' => $params['mchOrderNo'] ?? '']);
  1130. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['mchOrderNo'] ?? '')))) {
  1131. if (!ZimuPayService::verifyNotify($params)
  1132. || bccomp(ZimuPayService::amount($agentPayout->actual_amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1133. Log::error('ZIMU代理提现回调验签或金额不一致', ['mch_order_no' => $params['mchOrderNo'] ?? '']);
  1134. return false;
  1135. }
  1136. $cash = ZimuPayService::isCashChannel((string)$agentPayout->account_type);
  1137. return self::agentPayoutResult($agentPayout, (string)($params['status'] ?? ''),
  1138. $cash ? ZimuPayService::CASH_STATUS_SUCCESS : ZimuPayService::WITHDRAW_STATUS_SUCCESS,
  1139. $cash ? ZimuPayService::CASH_STATUS_FAIL : ZimuPayService::WITHDRAW_STATUS_FAIL, $params);
  1140. }
  1141. if (!$info || $info->type != self::TYPE_PAYOUT || !ZimuPayService::isPayoutChannel($info->channel)) {
  1142. Log::error('ZIMU提现/代付回调订单不存在或类型不匹配', [
  1143. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  1144. 'order_id' => $info->id ?? null,
  1145. 'order_type' => $info->type ?? null,
  1146. 'channel' => $info->channel ?? null,
  1147. ]);
  1148. return false;
  1149. }
  1150. if (!ZimuPayService::verifyNotify($params)) {
  1151. Log::error('ZIMU提现/代付回调验签失败', [
  1152. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  1153. 'app_id' => $params['appId'] ?? '',
  1154. 'signature' => ZimuPayService::notifySignatureDiagnostics($params),
  1155. ]);
  1156. return false;
  1157. }
  1158. if (bccomp(ZimuPayService::amount($info->amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1159. Log::error('ZIMU提现/代付回调金额不一致', [
  1160. 'mch_order_no' => $params['mchOrderNo'] ?? '',
  1161. 'order_amount' => $info->amount,
  1162. 'callback_amount' => $params['amount'] ?? null,
  1163. ]);
  1164. return false;
  1165. }
  1166. self::onSubmitZimuPayout($params, $info);
  1167. return true;
  1168. }
  1169. if (NoPayService::getWithdrawMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
  1170. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  1171. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['merchantOrderNo'] ?? '')))) {
  1172. if (!NoPayService::verifyWithdrawNotify($params)
  1173. || bccomp(NoPayService::amount($agentPayout->actual_amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1174. Log::error('NO代理提现回调验签或金额不一致', ['merchant_order_no' => $params['merchantOrderNo'] ?? '']);
  1175. return false;
  1176. }
  1177. return self::agentPayoutResult($agentPayout, (string)($params['state'] ?? ''),
  1178. NoPayService::STATE_SUCCESS, NoPayService::STATE_FAIL, $params);
  1179. }
  1180. if (!$info || $info->type != self::TYPE_PAYOUT || !NoPayService::isWithdrawChannel($info->channel)) {
  1181. Log::error('NO钱包提现回调订单不存在或类型不匹配', [
  1182. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  1183. 'order_id' => $info->id ?? null,
  1184. 'order_type' => $info->type ?? null,
  1185. 'channel' => $info->channel ?? null,
  1186. ]);
  1187. return false;
  1188. }
  1189. if (!NoPayService::verifyWithdrawNotify($params)) {
  1190. Log::error('NO钱包提现回调验签失败', [
  1191. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  1192. 'app_id' => $params['appId'] ?? '',
  1193. 'signature' => NoPayService::withdrawNotifySignatureDiagnostics($params),
  1194. ]);
  1195. return false;
  1196. }
  1197. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1198. Log::error('NO钱包提现回调金额不一致', [
  1199. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  1200. 'order_amount' => $info->amount,
  1201. 'callback_amount' => $params['amount'] ?? null,
  1202. ]);
  1203. return false;
  1204. }
  1205. self::onSubmitNoPayout($params, $info);
  1206. return true;
  1207. }
  1208. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  1209. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  1210. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  1211. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['customerOrderCode'] ?? ''), (string)($params['orderCode'] ?? '')))) {
  1212. if (!JdPayService::verifyRemitNotify($params)
  1213. || bccomp(JdPayService::amount($agentPayout->actual_amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1214. return false;
  1215. }
  1216. return self::agentPayoutResult($agentPayout, (string)($params['status'] ?? ''),
  1217. JdPayService::REMIT_STATUS_SUCCESS, JdPayService::REMIT_STATUS_FAIL, $params);
  1218. }
  1219. if (!$info || $info->type != self::TYPE_PAYOUT) {
  1220. return false;
  1221. }
  1222. if (!JdPayService::verifyRemitNotify($params)) {
  1223. return false;
  1224. }
  1225. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  1226. return false;
  1227. }
  1228. self::onSubmitJdPayout($params, $info);
  1229. return true;
  1230. }
  1231. // 判断商户号是否一致
  1232. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  1233. $info = self::findOne(['order_no' => $params['orderNo']]);
  1234. if (!$info && ($agentPayout = self::findAgentPayout((string)($params['orderNo'] ?? '')))) {
  1235. if (bccomp((string)$agentPayout->actual_amount, (string)($params['amount'] ?? 0), 2) !== 0
  1236. || ($params['sign'] ?? '') != QianBaoService::verifyNotifySign($params['state'] ?? '', $params['orderNo'], $params['amount'])) {
  1237. return false;
  1238. }
  1239. // 钱宝:state=1 成功,其他为失败(与会员代付一致)
  1240. $state = (string)($params['state'] ?? '');
  1241. return self::agentPayoutResult($agentPayout, $state, '1', $state === '1' ? '' : $state, $params);
  1242. }
  1243. if ($info) {
  1244. // 判断金额是不是正确认
  1245. if ($info->amount != $params['amount']) {
  1246. return false;
  1247. }
  1248. // 验证签名
  1249. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  1250. if ($params['sign'] != $sign) {
  1251. return false;
  1252. }
  1253. // 代付
  1254. if ($info->type == self::TYPE_PAYOUT) {
  1255. self::onSubmitPayout($params, $info);
  1256. }
  1257. // 代收
  1258. if ($info->type == self::TYPE_PAY) {
  1259. }
  1260. }
  1261. }
  1262. }
  1263. /** 三方代付回调的订单号不在会员订单里时,查代理提现(订单号 AW 开头;JD 也可按三方单号)。 */
  1264. private static function findAgentPayout(string $orderNo, string $payNo = ''): ?AgentWithdrawal
  1265. {
  1266. if ($orderNo === '' && $payNo === '') return null;
  1267. $order = $orderNo === '' ? null : AgentWithdrawal::query()->where('order_no', $orderNo)->first();
  1268. return $order ?: ($payNo === '' ? null : AgentWithdrawal::query()->where('pay_no', $payNo)->first());
  1269. }
  1270. /** 代理提现代付结果:成功扣冻结、失败退回代理余额;其他状态只记录回调。重复回调幂等。 */
  1271. private static function agentPayoutResult(AgentWithdrawal $withdrawal, string $status, string $success, string $fail, array $params): bool
  1272. {
  1273. $result = $status === $success ? true : ($fail !== '' && $status === $fail ? false : null);
  1274. app(AgentWithdrawalService::class)->providerResult((int)$withdrawal->id, $result, $params);
  1275. return true;
  1276. }
  1277. /**
  1278. * @description: 处理代付订单
  1279. * @param {*} $params
  1280. * @return {*}
  1281. */
  1282. public static function onSubmitJdPayout($params, $info)
  1283. {
  1284. if ($info->status != self::STATUS_PROCESS) {
  1285. return;
  1286. }
  1287. $memberId = $info->member_id;
  1288. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  1289. $data = [];
  1290. $chat_id = $info->member_id;
  1291. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1292. DB::beginTransaction();
  1293. try {
  1294. $locked = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
  1295. if (!$locked || $locked->status != self::STATUS_PROCESS) {
  1296. DB::rollBack();
  1297. return;
  1298. }
  1299. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  1300. $data['status'] = self::STATUS_SUCCESS;
  1301. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  1302. AdminRealtime::record('payment_orders', $info->id);
  1303. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $locked);
  1304. if ($res) {
  1305. $text = "✅ 提现通知 \n";
  1306. $text .= "提现平台:{$info->bank_name} \n";
  1307. $text .= "收款人:{$info->account} \n";
  1308. $text .= "收款地址:{$info->card_no} \n";
  1309. $text .= "提现金额:{$info->amount} \n";
  1310. $text .= "提现成功,金额已到账,请注意查收!";
  1311. self::notifyUser($chat_id, $text);
  1312. }
  1313. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  1314. $data['status'] = self::STATUS_FAIL;
  1315. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  1316. AdminRealtime::record('payment_orders', $info->id);
  1317. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $locked, $amount, '三方提现', '提现失败退款');
  1318. if ($res) {
  1319. $text = "❌ 提现通知 \n";
  1320. $text .= "提现平台:{$info->bank_name} \n";
  1321. $text .= "收款人:{$info->account} \n";
  1322. $text .= "收款地址:{$info->card_no} \n";
  1323. $text .= "提现金额:{$info->amount} \n";
  1324. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1325. self::notifyUser($chat_id, $text);
  1326. }
  1327. }
  1328. DB::commit();
  1329. } catch (Exception $e) {
  1330. DB::rollBack();
  1331. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  1332. }
  1333. }
  1334. public static function onSubmitNoPayout($params, $info)
  1335. {
  1336. $notification = null;
  1337. try {
  1338. DB::transaction(function () use ($params, $info, &$notification) {
  1339. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  1340. if (!$order || $order->status != self::STATUS_PROCESS) {
  1341. return;
  1342. }
  1343. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  1344. if ((string)$params['state'] === NoPayService::STATE_SUCCESS) {
  1345. $order->status = self::STATUS_SUCCESS;
  1346. $order->save();
  1347. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $order);
  1348. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  1349. } elseif ((string)$params['state'] === NoPayService::STATE_FAIL) {
  1350. $order->status = self::STATUS_FAIL;
  1351. $order->save();
  1352. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, NoPayService::amount($order->amount), '三方提现', '提现失败退款');
  1353. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  1354. } else {
  1355. $order->save();
  1356. }
  1357. }, 3);
  1358. if ($notification !== null) {
  1359. self::notifyUser($info->member_id, $notification);
  1360. }
  1361. } catch (Exception $e) {
  1362. Log::channel('payment_error')->error('NO提现回调处理异常', [
  1363. 'order_id' => $info->id,
  1364. 'params' => $params,
  1365. 'error' => $e->getMessage(),
  1366. ]);
  1367. }
  1368. }
  1369. public static function onSubmitZimuPayout($params, $info)
  1370. {
  1371. $notification = null;
  1372. $successStatus = ZimuPayService::isCashChannel($info->channel)
  1373. ? ZimuPayService::CASH_STATUS_SUCCESS
  1374. : ZimuPayService::WITHDRAW_STATUS_SUCCESS;
  1375. $failStatus = ZimuPayService::isCashChannel($info->channel)
  1376. ? ZimuPayService::CASH_STATUS_FAIL
  1377. : ZimuPayService::WITHDRAW_STATUS_FAIL;
  1378. try {
  1379. DB::transaction(function () use ($params, $info, &$notification, $successStatus, $failStatus) {
  1380. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  1381. if (!$order || $order->status != self::STATUS_PROCESS) {
  1382. return;
  1383. }
  1384. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  1385. if ((string)$params['status'] === $successStatus) {
  1386. $order->status = self::STATUS_SUCCESS;
  1387. $order->save();
  1388. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $order);
  1389. $accountLabel = ZimuPayService::isCashChannel($order->channel) ? '收款账号' : '808钱包地址';
  1390. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \n{$accountLabel}:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  1391. } elseif ((string)$params['status'] === $failStatus) {
  1392. $order->status = self::STATUS_FAIL;
  1393. $order->save();
  1394. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, ZimuPayService::amount($order->amount), '三方提现', '提现失败退款');
  1395. $accountLabel = ZimuPayService::isCashChannel($order->channel) ? '收款账号' : '808钱包地址';
  1396. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \n{$accountLabel}:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  1397. } else {
  1398. $order->save();
  1399. }
  1400. }, 3);
  1401. if ($notification !== null) {
  1402. self::notifyUser($info->member_id, $notification);
  1403. }
  1404. } catch (Exception $e) {
  1405. Log::channel('payment_error')->error('ZIMU提现/代付回调处理异常', [
  1406. 'order_id' => $info->id,
  1407. 'params' => $params,
  1408. 'error' => $e->getMessage(),
  1409. ]);
  1410. }
  1411. }
  1412. public static function onSubmitPayout($params, $info)
  1413. {
  1414. $memberId = $info->member_id;
  1415. $amount = $params['amount'];
  1416. $data = [];
  1417. $result = [];
  1418. $chat_id = $info->member_id;
  1419. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1420. DB::beginTransaction();
  1421. try {
  1422. // 只处理“处理中”的代付单,避免重复回调重复退款
  1423. $locked = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
  1424. if (!$locked || $locked->status != self::STATUS_PROCESS) {
  1425. DB::rollBack();
  1426. return;
  1427. }
  1428. if ($params['state'] == 1) {
  1429. $data['status'] = self::STATUS_SUCCESS;
  1430. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1431. AdminRealtime::record('payment_orders', $info->id);
  1432. WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $locked);
  1433. if ($res) {
  1434. $text = "✅ 提现通知 \n";
  1435. $text .= "提现平台:{$info->bank_name} \n";
  1436. $text .= "收款人:{$info->account} \n";
  1437. $text .= "收款卡号:{$info->card_no} \n";
  1438. $text .= "提现金额:{$info->amount} \n";
  1439. $text .= "提现成功,金额已到账,请注意查收!";
  1440. self::notifyUser($chat_id, $text);
  1441. }
  1442. } else {
  1443. $data['status'] = self::STATUS_FAIL;
  1444. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1445. AdminRealtime::record('payment_orders', $info->id);
  1446. // 冻结余额退回可用余额,并记录退款日志
  1447. WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $locked, $amount, '三方提现', '提现失败退款');
  1448. if ($res) {
  1449. $text = "❌ 提现通知 \n";
  1450. $text .= "提现平台:{$info->bank_name} \n";
  1451. $text .= "收款人:{$info->account} \n";
  1452. $text .= "收款卡号:{$info->card_no} \n";
  1453. $text .= "提现金额:{$info->amount} \n";
  1454. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1455. self::notifyUser($chat_id, $text);
  1456. }
  1457. }
  1458. DB::commit();
  1459. } catch (Exception $e) {
  1460. DB::rollBack();
  1461. // 回滚失败,需要记录告警,人工干预
  1462. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  1463. }
  1464. }
  1465. /**
  1466. * @description: 查询支付订单
  1467. * @param {*} $id
  1468. * @return {*}
  1469. */
  1470. public static function singlePayOrder($id)
  1471. {
  1472. return self::queryPayOrder(self::findOne(['id' => $id]));
  1473. }
  1474. /** 向三方查询在线充值订单并按结果入账。会员和代理订单共用。 */
  1475. public static function queryPayOrder(?PaymentOrder $info): array
  1476. {
  1477. $msg = [];
  1478. $msg['code'] = self::NOT;
  1479. if ($info && (int)$info->type === self::TYPE_PAY && in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
  1480. if (NoPayService::isRechargeChannel($info->channel)) {
  1481. $ret = NoPayService::queryPayOrder($info->order_no, (string)$info->member_id);
  1482. Log::channel('payment')->info('NO支付查询订单', $ret);
  1483. if (($ret['code'] ?? -1) == 0) {
  1484. $item = $ret['data'] ?? [];
  1485. if ((string)($item['state'] ?? '') === NoPayService::STATE_SUCCESS) {
  1486. $processed = self::applyPayCallback(
  1487. $info,
  1488. NoPayService::amount($info->amount),
  1489. NoPayService::STATE_SUCCESS,
  1490. NoPayService::STATE_SUCCESS,
  1491. NoPayService::STATE_FAIL,
  1492. $ret
  1493. );
  1494. $msg['code'] = $processed ? self::YES : self::NOT;
  1495. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1496. } elseif ((string)($item['state'] ?? '') === NoPayService::STATE_FAIL) {
  1497. self::applyPayCallback(
  1498. $info,
  1499. NoPayService::amount($info->amount),
  1500. NoPayService::STATE_FAIL,
  1501. NoPayService::STATE_SUCCESS,
  1502. NoPayService::STATE_FAIL,
  1503. $ret
  1504. );
  1505. $msg['msg'] = '支付失败';
  1506. } else {
  1507. $msg['msg'] = '支付中';
  1508. }
  1509. } else {
  1510. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1511. }
  1512. return $msg;
  1513. }
  1514. if (ZimuPayService::isRechargeChannel($info->channel)) {
  1515. $ret = ZimuPayService::queryPayOrder($info->order_no);
  1516. Log::channel('payment')->info('ZIMU支付查询订单', $ret);
  1517. if (($ret['code'] ?? -1) == 0) {
  1518. $item = $ret['data'] ?? [];
  1519. if ((string)($item['status'] ?? '') === ZimuPayService::PAY_STATUS_SUCCESS) {
  1520. $processed = self::applyPayCallback(
  1521. $info,
  1522. ZimuPayService::amount($info->amount),
  1523. ZimuPayService::PAY_STATUS_SUCCESS,
  1524. ZimuPayService::PAY_STATUS_SUCCESS,
  1525. ZimuPayService::PAY_STATUS_FAIL,
  1526. $ret
  1527. );
  1528. $msg['code'] = $processed ? self::YES : self::NOT;
  1529. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1530. } elseif ((string)($item['status'] ?? '') === ZimuPayService::PAY_STATUS_FAIL) {
  1531. self::applyPayCallback(
  1532. $info,
  1533. ZimuPayService::amount($info->amount),
  1534. ZimuPayService::PAY_STATUS_FAIL,
  1535. ZimuPayService::PAY_STATUS_SUCCESS,
  1536. ZimuPayService::PAY_STATUS_FAIL,
  1537. $ret
  1538. );
  1539. $msg['msg'] = '支付失败';
  1540. } else {
  1541. $msg['msg'] = '支付中';
  1542. }
  1543. } else {
  1544. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1545. }
  1546. return $msg;
  1547. }
  1548. if (JdPayService::isChannel($info->channel)) {
  1549. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  1550. Log::channel('payment')->info('JD支付查询订单', $ret);
  1551. if (($ret['code'] ?? 0) == 200) {
  1552. $item = $ret['data'] ?? [];
  1553. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  1554. $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), JdPayService::PAY_STATUS_SUCCESS,
  1555. JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $ret);
  1556. $msg['code'] = $processed ? self::YES : self::NOT;
  1557. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1558. } else {
  1559. $msg['msg'] = '支付中';
  1560. }
  1561. } else {
  1562. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  1563. }
  1564. return $msg;
  1565. }
  1566. $ret = SanJinService::queryOrder($info->order_no);
  1567. Log::error('三斤支付查询订单:', $ret);
  1568. if ($ret['code'] == 0) {
  1569. $item = [];
  1570. $item['state'] = $ret['data']['state'];
  1571. if ($ret['data']['state'] == 1) {
  1572. $processed = self::applyPayCallback($info, (string)$info->amount, '1', '1', null, $ret);
  1573. $msg['code'] = $processed ? self::YES : self::NOT;
  1574. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1575. } else {
  1576. $msg['msg'] = '支付中';
  1577. }
  1578. } else {
  1579. $msg['msg'] = '查询失败:' . $ret['message'];
  1580. }
  1581. } else {
  1582. $msg['msg'] = '该状态无法查询';
  1583. }
  1584. return $msg;
  1585. }
  1586. private static function assertJdBalanceEnough($amount, array $context = []): void
  1587. {
  1588. $ret = JdPayService::balance();
  1589. Log::channel('payment')->info('JD余额查询', $context + [
  1590. 'amount' => $amount,
  1591. 'response' => $ret,
  1592. ]);
  1593. if (($ret['code'] ?? 0) != 200) {
  1594. $logContext = $context + [
  1595. 'amount' => $amount,
  1596. 'response' => $ret,
  1597. ];
  1598. Log::channel('payment_error')->error('JD余额查询失败', $logContext);
  1599. Log::error('JD余额查询失败', $logContext);
  1600. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  1601. }
  1602. $balance = $ret['data']['balance'] ?? null;
  1603. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  1604. $logContext = $context + [
  1605. 'amount' => $amount,
  1606. 'balance' => $balance,
  1607. 'response' => $ret,
  1608. ];
  1609. Log::channel('payment_error')->error('JD商户余额不足', $logContext);
  1610. Log::error('JD商户余额不足', $logContext);
  1611. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  1612. }
  1613. }
  1614. private static function assertZimuBalanceEnough($amount, array $context = []): void
  1615. {
  1616. $ret = ZimuPayService::balance();
  1617. Log::channel('payment')->info('ZIMU余额查询', $context + [
  1618. 'amount' => $amount,
  1619. 'response' => $ret,
  1620. ]);
  1621. if (($ret['code'] ?? -1) != 0) {
  1622. $logContext = $context + [
  1623. 'amount' => $amount,
  1624. 'response' => $ret,
  1625. ];
  1626. Log::channel('payment_error')->error('ZIMU余额查询失败', $logContext);
  1627. Log::error('ZIMU余额查询失败', $logContext);
  1628. throw new Exception($ret['msg'] ?? 'ZIMU余额查询失败', HttpStatus::CUSTOM_ERROR);
  1629. }
  1630. $balance = $ret['data']['balance'] ?? null;
  1631. if ($balance === null || bccomp((string)$balance, ZimuPayService::amount($amount), 2) < 0) {
  1632. $logContext = $context + [
  1633. 'amount' => $amount,
  1634. 'balance' => $balance,
  1635. 'response' => $ret,
  1636. ];
  1637. Log::channel('payment_error')->error('ZIMU商户余额不足', $logContext);
  1638. Log::error('ZIMU商户余额不足', $logContext);
  1639. throw new Exception('ZIMU商户余额不足', HttpStatus::CUSTOM_ERROR);
  1640. }
  1641. }
  1642. private static function notifyUser($chatId, string $text): void
  1643. {
  1644. if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
  1645. return;
  1646. }
  1647. try {
  1648. self::sendMessage($chatId, $text);
  1649. } catch (\Throwable $e) {
  1650. Log::channel('payment_error')->error('支付订单用户通知失败', [
  1651. 'chat_id' => $chatId,
  1652. 'error' => $e->getMessage(),
  1653. ]);
  1654. }
  1655. }
  1656. public static function syncPayOrder()
  1657. {
  1658. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  1659. // foreach($list->toArray() as $k => $v){
  1660. // $item= [];
  1661. // if($v['status'] == self::STATUS_SUCCESS){
  1662. // $item['state'] = 1;
  1663. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1664. // }else{
  1665. // $ret = SanJinService::queryOrder($v['order_no']);
  1666. // var_dump($ret);
  1667. // if($ret['code'] == 0){
  1668. // $item['state'] = $ret['data']['state'];
  1669. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1670. // }
  1671. // }
  1672. // }
  1673. }
  1674. }