PaymentOrderService.php 81 KB

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