PaymentOrderService.php 84 KB

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