PaymentOrderService.php 72 KB

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