PaymentOrderService.php 74 KB

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