PaymentOrderService.php 75 KB

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