PaymentOrderService.php 83 KB

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