PaymentOrderService.php 75 KB

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