PaymentOrderService.php 75 KB

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