PaymentOrderService.php 75 KB

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