PaymentOrderService.php 73 KB

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