PaymentOrderService.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Models\PaymentOrder;
  5. use App\Models\User;
  6. use App\Models\Wallet as WalletModel;
  7. use Exception;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Services\Payment\JdPayService;
  11. use App\Services\Payment\NoPayService;
  12. use App\Services\Payment\QianBaoService;
  13. use App\Services\Payment\SanJinService;
  14. use App\Services\ConfigService;
  15. /**
  16. * 投注
  17. */
  18. class PaymentOrderService extends BaseService
  19. {
  20. const TYPE_PAY = 1; // 代收
  21. const TYPE_PAYOUT = 2; // 代付
  22. const TYPE_SELF_PAY = 3; // 手动充值
  23. const TYPE_SELF_PAYOUT = 4; // 手动提现打款
  24. const STATUS_STAY = 0; // 待处理
  25. const STATUS_PROCESS = 1; // 处理中
  26. const STATUS_SUCCESS = 2; // 成功
  27. const STATUS_FAIL = 3; // 失败
  28. const STATUS_USER = 4; // 待用户提交凭证
  29. const STATUS_AUDIT = 5; //待人工审核
  30. const STATUS_CANCEL = 6; //已撤回
  31. public static string $MODEL = PaymentOrder::class;
  32. /**
  33. * @description: 模型
  34. * @return {string}
  35. */
  36. public static function model(): string
  37. {
  38. return PaymentOrder::class;
  39. }
  40. /**
  41. * @description: 枚举
  42. * @return {*}
  43. */
  44. public static function enum(): string
  45. {
  46. return '';
  47. }
  48. /**
  49. * @description: 获取查询条件
  50. * @param {array} $search 查询内容
  51. * @return {array}
  52. */
  53. public static function getWhere(array $search = []): array
  54. {
  55. $where = [];
  56. if (isset($search['member_id']) && !empty($search['member_id'])) {
  57. $where[] = ['payment_orders.member_id', '=', $search['member_id']];
  58. }
  59. if (isset($search['channel']) && !empty($search['channel'])) {
  60. if ($search['channel'] == 'rgcz') {
  61. $search['type'] = 3;
  62. }
  63. $where[] = ['payment_orders.channel', '=', $search['channel']];
  64. }
  65. if (isset($search['type']) && !empty($search['type'])) {
  66. $where[] = ['payment_orders.type', '=', $search['type']];
  67. }
  68. if (isset($search['order_no']) && !empty($search['order_no'])) {
  69. $where[] = ['payment_orders.order_no', '=', $search['order_no']];
  70. }
  71. if (isset($search['id']) && !empty($search['id'])) {
  72. $where[] = ['payment_orders.id', '=', $search['id']];
  73. }
  74. if (isset($search['status']) && $search['status'] != '') {
  75. $where[] = ['payment_orders.status', '=', $search['status']];
  76. }
  77. if (isset($search['first_name']) && !empty($search['first_name'])) {
  78. $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
  79. }
  80. if (isset($search['payment_type']) && $search['payment_type'] != '') {
  81. $where[] = ['payment_orders.payment_type', '=', $search['payment_type']];
  82. }
  83. return $where;
  84. }
  85. /**
  86. * @description: 查询单条数据
  87. * @param array $search
  88. * @return \App\Models\Coin|null
  89. */
  90. public static function findOne(array $search): ?PaymentOrder
  91. {
  92. return static::$MODEL::where(self::getWhere($search))->first();
  93. }
  94. /**
  95. * @description: 查询所有数据
  96. * @param array $search
  97. * @return \Illuminate\Database\Eloquent\Collection
  98. */
  99. public static function findAll(array $search = [])
  100. {
  101. return static::$MODEL::where(self::getWhere($search))->get();
  102. }
  103. /**
  104. * @description: 分页查询
  105. * @param array $search
  106. * @return array
  107. */
  108. public static function paginate(array $search = [])
  109. {
  110. $limit = isset($search['limit']) ? $search['limit'] : 15;
  111. $paginator = static::$MODEL::where(self::getWhere($search))
  112. ->join('users', 'users.member_id', '=', 'payment_orders.member_id')
  113. ->select("payment_orders.*", "users.first_name","users.admin_note as user_admin_note") // 提前查好需要的字段
  114. ->orderByDesc('payment_orders.created_at')
  115. ->paginate($limit);
  116. $totalAmount = 0;
  117. $totalSuccess = 0;
  118. $totalFail = 0;
  119. $list = $paginator->items();
  120. foreach ($list as $item) {
  121. $item['amount'] = floatval($item['amount']);
  122. $totalAmount += $item['amount'];
  123. if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
  124. if ($item['status'] == 3) $totalFail += $item['amount'];
  125. }
  126. return [
  127. 'total' => $paginator->total(),
  128. 'total_amount' => $totalAmount,
  129. 'total_success' => $totalSuccess,
  130. 'total_fail' => $totalFail,
  131. 'data' => $list
  132. ];
  133. }
  134. /**
  135. * @description:
  136. * @param {*} $params
  137. * @return {*}
  138. */
  139. public static function submit($params = [])
  140. {
  141. $result = false;
  142. $msg['code'] = self::NOT;
  143. $msg['msg'] = '';
  144. // 2. 判断是否是更新
  145. if (!empty($params['id'])) {
  146. // 更新
  147. $info = self::findOne(['id' => $params['id']]);
  148. if (!$info) {
  149. $msg['msg'] = '数据不存在!';
  150. } else {
  151. $result = $info->update($params);
  152. $id = $params['id'];
  153. }
  154. } else {
  155. // 创建
  156. $result = $info = static::$MODEL::create($params);
  157. $id = $result->id;
  158. }
  159. if ($result) {
  160. $msg['code'] = self::YES;
  161. $msg['msg'] = '设置成功';
  162. $msg['key'] = $id;
  163. } else {
  164. $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
  165. }
  166. return $msg;
  167. }
  168. /**
  169. * @description: 创建代收订单
  170. * @param {*} $memberId
  171. * @param {*} $amount
  172. * @param {*} $paymentType 支付类型:支付宝、数字人民币
  173. * @return {*}
  174. */
  175. public static function createPay($memberId, $amount, $paymentType)
  176. {
  177. $result = [];
  178. $result['chat_id'] = $memberId;
  179. $result['code'] = 0;
  180. $result['url'] = '';
  181. $channel = ''; // 支付的通道
  182. $product = SanJinService::product();
  183. $max = 0;
  184. $min = 0;
  185. $rate = 0;
  186. $selectedProduct = null;
  187. $geText = '';
  188. foreach ($product as $k => $v) {
  189. if ($v['type'] == $paymentType) {
  190. $selectedProduct = $v;
  191. if ($v['type'] == 'zfbge') {
  192. if (in_array($amount, $v['fixed'])) {
  193. $channel = $k;
  194. } else {
  195. $geText .= "❌ 此充值通道固定充值金额为" . implode(',', $v['fixed']) . "请务必输入区间金额!";
  196. }
  197. } else {
  198. if ($amount >= $v['min'] && $amount <= $v['max']) {
  199. $channel = $k;
  200. $rate = $v['rate'];
  201. }
  202. if ($min == 0) {
  203. $min = $v['min'];
  204. }
  205. if ($max == 0) {
  206. $max = $v['max'];
  207. }
  208. if ($min > $v['min']) {
  209. $min = $v['min'];
  210. }
  211. if ($max < $v['max']) {
  212. $max = $v['max'];
  213. }
  214. }
  215. }
  216. }
  217. // 没有找到支付通道
  218. if (empty($channel) && !JdPayService::isChannel($paymentType) && !NoPayService::isRechargeChannel($paymentType)) {
  219. // $text = "发起充值失败 \n";
  220. // $text .= "最低充值:" . $min . " \n";
  221. // $text .= "最高充值:" . $max . " \n";
  222. // $text .= "请重新填写充值的金额!";
  223. $text = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
  224. $result['text'] = $text;
  225. if ($geText) {
  226. $result['text'] = $geText;
  227. }
  228. $result['code'] = 20001;
  229. return $result;
  230. }
  231. if (NoPayService::isRechargeChannel($paymentType) || NoPayService::isRechargeChannel($channel)) {
  232. $channel = NoPayService::isRechargeChannel($paymentType) ? $paymentType : $channel;
  233. $bankName = $selectedProduct['name'] ?? 'NO快捷充值';
  234. $data = [];
  235. $data['type'] = self::TYPE_PAY;
  236. $data['member_id'] = $memberId;
  237. $data['amount'] = NoPayService::amount($amount);
  238. $data['channel'] = $channel;
  239. $data['fee'] = $amount * $rate;
  240. $data['bank_name'] = $bankName;
  241. $order_no = self::createOrderNo('no' . $data['type'] . '_', $memberId);
  242. $data['order_no'] = $order_no;
  243. $data['callback_url'] = NoPayService::getDepositNotifyUrl();
  244. $data['remark'] = '充值费率:' . $rate;
  245. $data['status'] = self::STATUS_STAY;
  246. $ret = NoPayService::pay($amount, $order_no, (string)$memberId, $channel);
  247. Log::channel('payment')->info('NO支付发起', [
  248. 'order_no' => $order_no,
  249. 'member_id' => $memberId,
  250. 'amount' => $data['amount'],
  251. 'channel' => $channel,
  252. 'response' => $ret,
  253. ]);
  254. if (($ret['code'] ?? -1) == 0) {
  255. $payUrl = $ret['data']['url'] ?? '';
  256. $data['status'] = self::STATUS_PROCESS;
  257. $data['pay_url'] = $payUrl;
  258. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  259. static::$MODEL::create($data);
  260. if ($payUrl) {
  261. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  262. }
  263. $result['text'] = "{$bankName}充值确认 \n";
  264. $result['text'] .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  265. $result['text'] .= "支付地址:{$payUrl}\n";
  266. $result['text'] .= "支付金额:" . $amount . " RMB \n";
  267. $result['text'] .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  268. $result['url'] = $payUrl;
  269. } else {
  270. $result['text'] = $ret['msg'] ?? 'NO支付发起失败';
  271. $result['code'] = 20002;
  272. }
  273. return $result;
  274. }
  275. if (JdPayService::isChannel($paymentType) || JdPayService::isChannel($channel)) {
  276. $channel = JdPayService::CHANNEL;
  277. $bankName = $selectedProduct['name'] ?? 'JD钱包';
  278. $data = [];
  279. $data['type'] = self::TYPE_PAY;
  280. $data['member_id'] = $memberId;
  281. $data['amount'] = JdPayService::amount($amount);
  282. $data['channel'] = $channel;
  283. $data['fee'] = $amount * $rate;
  284. $data['bank_name'] = $bankName;
  285. $order_no = self::createOrderNo('jd' . $data['type'] . '_', $memberId);
  286. $data['order_no'] = $order_no;
  287. $data['callback_url'] = JdPayService::getNotifyUrl();
  288. $data['remark'] = '充值费率:' . $rate;
  289. $data['status'] = self::STATUS_STAY;
  290. $ret = JdPayService::pay($amount, $order_no);
  291. Log::channel('payment')->info('JD支付发起', $ret);
  292. if (($ret['code'] ?? 0) == 200) {
  293. $item = $ret['data'] ?? [];
  294. $payUrl = $item['url'] ?? '';
  295. $data['status'] = self::STATUS_PROCESS;
  296. $data['pay_no'] = $item['orderNo'] ?? '';
  297. $data['pay_url'] = $payUrl;
  298. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  299. static::$MODEL::create($data);
  300. if ($payUrl) {
  301. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  302. }
  303. $text = "{$bankName}充值确认 \n";
  304. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  305. $text .= "支付地址:{$payUrl}\n";
  306. $text .= "支付金额:" . $amount . " RMB \n";
  307. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  308. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  309. $result['text'] = $text;
  310. $result['url'] = $payUrl;
  311. } else {
  312. $result['text'] = $ret['message'] ?? 'JD支付发起失败';
  313. $result['code'] = 20002;
  314. }
  315. return $result;
  316. }
  317. $data = [];
  318. $data['type'] = self::TYPE_PAY;
  319. $data['member_id'] = $memberId;
  320. $data['amount'] = $amount;
  321. $data['channel'] = $channel;
  322. $data['fee'] = $amount * $rate;
  323. $data['bank_name'] = SanJinService::getChannel($paymentType) ?? '';
  324. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  325. $data['order_no'] = $order_no;
  326. $data['callback_url'] = SanJinService::getNotifyUrl();
  327. $data['remark'] = '充值费率:' . $rate;
  328. $data['status'] = self::STATUS_STAY;
  329. $ret = SanJinService::pay(($amount * 100), $order_no, $channel);
  330. Log::error('三斤支付发起:', $ret);
  331. if ($ret['code'] == 0) {
  332. $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
  333. $result['image'] = $qrCode;
  334. $item = $ret['data'];
  335. $data['status'] = self::STATUS_PROCESS;
  336. $data['pay_no'] = $item['tradeNo'];
  337. $data['pay_url'] = $item['payUrl'];
  338. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  339. $info = static::$MODEL::create($data);
  340. // $text = "✅ 支付提示 \n";
  341. $text = "{$data['bank_name']}充值确认 \n";
  342. // $text .= "支付方式:{$data['bank_name']} \n";
  343. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  344. $text .= "支付地址:{$ret['data']['payUrl']}\n";
  345. $text .= "支付金额:" . $amount . " RMB \n";
  346. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  347. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  348. $result['text'] = $text;
  349. $result['url'] = $ret['data']['payUrl'];
  350. } else {
  351. $result['text'] = $ret['message'];
  352. $result['code'] = 20002;
  353. }
  354. return $result;
  355. }
  356. /**
  357. * @description: 接收支付的通知
  358. * @param {*} $params
  359. * @return {*}
  360. */
  361. public static function receivePay($params)
  362. {
  363. if (NoPayService::getDepositMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getDepositMerchantId()) {
  364. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  365. if (!$info || $info->type != self::TYPE_PAY || !NoPayService::isRechargeChannel($info->channel)) {
  366. return false;
  367. }
  368. if (!NoPayService::verifyDepositNotify($params)) {
  369. return false;
  370. }
  371. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  372. return false;
  373. }
  374. if ($info->status != self::STATUS_PROCESS) {
  375. return true;
  376. }
  377. $processed = self::applyPayCallback(
  378. $info,
  379. NoPayService::amount($info->amount),
  380. (string)$params['state'],
  381. NoPayService::STATE_SUCCESS,
  382. NoPayService::STATE_FAIL,
  383. $params
  384. );
  385. if ($processed && (string)$params['state'] === NoPayService::STATE_SUCCESS) {
  386. self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
  387. }
  388. return true;
  389. }
  390. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  391. $info = self::findOne(['order_no' => $params['orderCode'] ?? ''])
  392. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  393. if (!$info || $info->type != self::TYPE_PAY) {
  394. return false;
  395. }
  396. if (!JdPayService::verifyPayNotify($params)) {
  397. return false;
  398. }
  399. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  400. return false;
  401. }
  402. if ($info->status != self::STATUS_PROCESS) {
  403. return true;
  404. }
  405. $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), (string)$params['status'], JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $params);
  406. if ($processed && (string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
  407. $text = "✅ 支付成功 \n";
  408. $text .= "充值金额:{$info->amount} RMB \n";
  409. $text .= "订单号:{$info->order_no} \n";
  410. $text .= "您充值的金额已到账,请注意查收!";
  411. self::notifyUser($info->member_id, $text);
  412. }
  413. return true;
  414. }
  415. // 判断商户号
  416. if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
  417. $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
  418. $info = self::findOne(['order_no' => $params['outTradeNo']]);
  419. if ($info) {
  420. // 平台以分计算转成元
  421. $payAmount = $params['payAmount'] / 100;
  422. // 判断金额是不是正确认
  423. if ($info->amount != $payAmount) {
  424. $text = '❌ 支付失败提醒 \n';
  425. $text .= "订单金额:{$info->amount} \n";
  426. $text .= "实际支付:{$payAmount} \n";
  427. $text .= "订单号:{$params['outTradeNo']} \n";
  428. $text .= "失败原因:支付金额与订单金额不一致 \n";
  429. $text .= "请联系客服处理!";
  430. self::notifyUser($info->member_id, $text);
  431. return false;
  432. }
  433. if ($params['sign'] != SanJinService::signature($params, $must)) {
  434. return false;
  435. }
  436. if ($info->status != self::STATUS_PROCESS) {
  437. return false;
  438. }
  439. // 付款
  440. if ($info->type == self::TYPE_PAY) {
  441. $processed = self::applyPayCallback($info, $payAmount, (string)$params['state'], '1', null, $params);
  442. if ($processed && $params['state'] == 1) {
  443. $text = "✅ 支付成功 \n";
  444. $text .= "充值金额:{$payAmount} RMB \n";
  445. $text .= "订单号:{$params['outTradeNo']} \n";
  446. $text .= "您充值的金额已到账,请注意查收!";
  447. self::notifyUser($info->member_id, $text);
  448. } else {
  449. $text = "❌ 支付失败 \n";
  450. $text .= "充值金额:{$payAmount} RMB \n";
  451. $text .= "订单号:{$params['outTradeNo']} \n";
  452. }
  453. return true;
  454. }
  455. }
  456. }
  457. }
  458. // 充值笔笔返
  459. public static function rechargesBibiReturn($memberId,$payAmount,$info_id)
  460. {
  461. $rate = ConfigService::getVal('recharges_bibi_return');
  462. $amount = $payAmount * $rate;
  463. if($rate > 0){
  464. $wallet = WalletService::findOne(['member_id' => $memberId]);
  465. $balance = $wallet->available_balance;
  466. $available_balance = bcadd($balance, $amount, 10);
  467. $wallet->available_balance = $available_balance;
  468. $wallet->save();
  469. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '优惠活动', $info_id, '充值笔笔返');
  470. }
  471. }
  472. private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
  473. {
  474. return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
  475. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  476. if (!$order || $order->status != self::STATUS_PROCESS) {
  477. return false;
  478. }
  479. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  480. $order->state = $status;
  481. if ($status === $successStatus) {
  482. $order->status = self::STATUS_SUCCESS;
  483. $order->save();
  484. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  485. if (!$wallet) {
  486. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  487. }
  488. $balance = $wallet->available_balance;
  489. $availableBalance = bcadd($balance, $payAmount, 10);
  490. $wallet->available_balance = $availableBalance;
  491. $wallet->save();
  492. BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
  493. $rate = ConfigService::getVal('recharges_bibi_return');
  494. $bonusAmount = $payAmount * $rate;
  495. if ($rate > 0 && $bonusAmount > 0) {
  496. $bonusBeforeBalance = $wallet->available_balance;
  497. $bonusAfterBalance = bcadd($bonusBeforeBalance, $bonusAmount, 10);
  498. $wallet->available_balance = $bonusAfterBalance;
  499. $wallet->save();
  500. BalanceLogService::addLog($order->member_id, $bonusAmount, $bonusBeforeBalance, $bonusAfterBalance, '优惠活动', $order->id, '充值笔笔返');
  501. }
  502. return true;
  503. }
  504. if ($failStatus === null || $status === $failStatus) {
  505. $order->status = self::STATUS_FAIL;
  506. }
  507. $order->save();
  508. return true;
  509. }, 3);
  510. }
  511. /**
  512. * 拒绝提现
  513. * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
  514. * @param int $orderId 订单ID PaymentOrder 表的ID
  515. * @param string $remark 失败原因
  516. * @return array
  517. */
  518. public static function withdrawalFailed($orderId, $remark): array
  519. {
  520. try {
  521. $order = PaymentOrder::where('id', $orderId)
  522. ->whereIn('type', [2,4])
  523. ->where('status', self::STATUS_STAY)
  524. ->first();
  525. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  526. // 更新提现记录状态为失败
  527. $order->status = self::STATUS_FAIL;
  528. $order->remark = $remark;
  529. if (!$order->save()) {
  530. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  531. }
  532. //钱包余额增加
  533. $wallet = WalletService::findOne(['member_id' => $order->member_id]);
  534. $beforeBalance = $wallet->available_balance;
  535. $availableBalance = bcadd($wallet->available_balance, $order->amount, 10);
  536. $wallet->available_balance = $availableBalance;
  537. if (!$wallet->save()) {
  538. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  539. }
  540. // 记录退款日志
  541. BalanceLogService::addLog($order->member_id, $order->amount, $beforeBalance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  542. } catch (Exception $e) {
  543. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  544. }
  545. return ['code' => 0, 'msg' => 'ok'];
  546. }
  547. /**
  548. * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
  549. * @param int $orderId PaymentOrder 表的ID
  550. */
  551. public static function createPayout(int $orderId): array
  552. {
  553. try {
  554. $order = PaymentOrder::where('id', $orderId)
  555. ->where('type', 2)
  556. ->where('status', self::STATUS_STAY)
  557. ->first();
  558. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  559. $amount = $order->amount;
  560. $amount = number_format($amount, 2, '.', '');
  561. if (NoPayService::isWithdrawChannel($order->channel)) {
  562. $ret = NoPayService::withdraw($amount, $order->order_no, (string)$order->member_id, (string)$order->account, (string)$order->card_no);
  563. Log::channel('payment')->info('NO提现接口调用', [
  564. 'order_id' => $order->id,
  565. 'order_no' => $order->order_no,
  566. 'member_id' => $order->member_id,
  567. 'amount' => $amount,
  568. 'q_account' => $order->card_no,
  569. 'response' => $ret,
  570. ]);
  571. if (($ret['code'] ?? -1) != 0) {
  572. throw new Exception($ret['msg'] ?? 'NO提现失败', HttpStatus::CUSTOM_ERROR);
  573. }
  574. $order->pay_no = $ret['data']['orderNo'] ?? '';
  575. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  576. } elseif (JdPayService::isChannel($order->channel)) {
  577. self::assertJdBalanceEnough($amount, [
  578. 'order_id' => $order->id,
  579. 'order_no' => $order->order_no,
  580. 'member_id' => $order->member_id,
  581. 'address' => $order->card_no,
  582. ]);
  583. $ret = JdPayService::remit($amount, $order->order_no, $order->card_no);
  584. Log::channel('payment')->info('JD下发接口调用', [
  585. 'order_id' => $order->id,
  586. 'order_no' => $order->order_no,
  587. 'member_id' => $order->member_id,
  588. 'amount' => $amount,
  589. 'address' => $order->card_no,
  590. 'response' => $ret,
  591. ]);
  592. if (($ret['code'] ?? 0) != 200) {
  593. $logContext = [
  594. 'order_id' => $order->id,
  595. 'order_no' => $order->order_no,
  596. 'member_id' => $order->member_id,
  597. 'amount' => $amount,
  598. 'address' => $order->card_no,
  599. 'response' => $ret,
  600. ];
  601. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  602. Log::error('JD下发接口失败', $logContext);
  603. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  604. }
  605. $order->pay_no = $ret['data']['orderNo'] ?? '';
  606. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  607. } else {
  608. $ret = QianBaoService::payout($amount, $order->order_no, $order->bank_name, $order->account, $order->card_no);
  609. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  610. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  611. }
  612. $order->status = self::STATUS_PROCESS;
  613. $order->save();
  614. } catch (Exception $e) {
  615. Log::channel('payment_error')->error('创建代付订单失败', [
  616. 'order_id' => $orderId,
  617. 'error' => $e->getMessage(),
  618. ]);
  619. Log::error('创建代付订单失败', [
  620. 'order_id' => $orderId,
  621. 'error' => $e->getMessage(),
  622. ]);
  623. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  624. }
  625. return ['code' => 0, 'msg' => 'ok'];
  626. }
  627. /**
  628. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  629. * @param {*} $memberId 会员ID
  630. * @param {*} $amount 代付金额
  631. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  632. * @param {*} $bank_name 银行名称/支付宝
  633. * @param {*} $account 姓名
  634. * @param {*} $card_no 银行卡号/支付宝账号
  635. * @return {*}
  636. */
  637. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  638. {
  639. $default_amount = $amount;
  640. $result = [];
  641. $result['chat_id'] = $memberId;
  642. if ($amount < 100) {
  643. $result['text'] = '提现金额最少100';
  644. return $result;
  645. }
  646. if ($amount > 49999) {
  647. $result['text'] = '提现金额最多49999';
  648. return $result;
  649. }
  650. // 在调用三方支付前开始事务
  651. DB::beginTransaction();
  652. try {
  653. $wallet = WalletService::findOne(['member_id' => $memberId]);
  654. if (!$wallet) {
  655. $result['text'] = '钱包不存在!';
  656. return $result;
  657. }
  658. $balance = $wallet->available_balance;
  659. if (bccomp($balance, $amount, 2) < 0) {
  660. $result['text'] = '您的钱包余额不足!';
  661. return $result;
  662. }
  663. $available_balance = bcsub($balance, $amount, 10);
  664. $data = [];
  665. $data['type'] = self::TYPE_PAYOUT;
  666. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  667. $data['order_no'] = $order_no;
  668. $data['member_id'] = $memberId;
  669. $data['fee'] = $amount * 0.002 + 2;
  670. $amount = number_format($amount, 2, '.', '');
  671. $data['amount'] = $amount;
  672. $data['channel'] = $channel;
  673. $data['bank_name'] = $bank_name;
  674. $data['account'] = $account;
  675. $data['card_no'] = $card_no;
  676. if (NoPayService::isWithdrawChannel($channel)) {
  677. $data['callback_url'] = NoPayService::getWithdrawNotifyUrl();
  678. } elseif (JdPayService::isChannel($channel)) {
  679. $data['callback_url'] = JdPayService::getRemitNotifyUrl();
  680. } else {
  681. $data['callback_url'] = QianBaoService::getNotifyUrl();
  682. }
  683. $data['status'] = self::STATUS_STAY;
  684. $data['remark'] = '提现费率:0.2%+2';
  685. // 先预扣款(锁定资金)
  686. $wallet->available_balance = $available_balance;
  687. if (!$wallet->save()) {
  688. DB::rollBack();
  689. $result['text'] = '钱包更新失败!';
  690. return $result;
  691. }
  692. // 创建待处理状态的提现记录
  693. $info = static::$MODEL::create($data);
  694. $id = $info->id;
  695. // 记录余额变动日志
  696. BalanceLogService::addLog($memberId, $default_amount * -1, $balance, $available_balance, '三方提现', $id, '钱宝提现费率:0.2%+2');
  697. // 提交事务,确保预扣款成功
  698. DB::commit();
  699. } //
  700. catch (Exception $e) {
  701. // 预扣款失败,回滚事务
  702. DB::rollBack();
  703. $result['text'] = '系统繁忙,请稍后重试!';
  704. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  705. 'member_id' => $memberId,
  706. 'amount' => $amount
  707. ]);
  708. return $result;
  709. }
  710. // 调用三方支付接口(在事务外)
  711. if (NoPayService::isWithdrawChannel($channel)) {
  712. try {
  713. $ret = NoPayService::withdraw($amount, $order_no, (string)$memberId, (string)$account, (string)$card_no);
  714. Log::channel('payment')->info('NO提现接口调用', [
  715. 'order_no' => $order_no,
  716. 'member_id' => $memberId,
  717. 'amount' => $amount,
  718. 'q_account' => $card_no,
  719. 'response' => $ret,
  720. ]);
  721. $success = (($ret['code'] ?? -1) == 0);
  722. $failureMessage = $ret['msg'] ?? 'NO提现失败';
  723. } catch (Exception $e) {
  724. $ret = ['msg' => $e->getMessage()];
  725. $success = false;
  726. $failureMessage = $e->getMessage();
  727. Log::channel('payment_error')->error('NO提现接口异常', [
  728. 'order_no' => $order_no,
  729. 'member_id' => $memberId,
  730. 'amount' => $amount,
  731. 'q_account' => $card_no,
  732. 'error' => $e->getMessage(),
  733. ]);
  734. }
  735. } elseif (JdPayService::isChannel($channel)) {
  736. try {
  737. self::assertJdBalanceEnough($amount, [
  738. 'order_no' => $order_no,
  739. 'member_id' => $memberId,
  740. 'address' => $card_no,
  741. ]);
  742. $ret = JdPayService::remit($amount, $order_no, $card_no);
  743. Log::channel('payment')->info('JD下发接口调用', [
  744. 'order_no' => $order_no,
  745. 'member_id' => $memberId,
  746. 'amount' => $amount,
  747. 'address' => $card_no,
  748. 'response' => $ret,
  749. ]);
  750. $success = (($ret['code'] ?? 0) == 200);
  751. $failureMessage = $ret['message'] ?? 'JD下发失败';
  752. if (!$success) {
  753. $logContext = [
  754. 'order_no' => $order_no,
  755. 'member_id' => $memberId,
  756. 'amount' => $amount,
  757. 'address' => $card_no,
  758. 'response' => $ret,
  759. ];
  760. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  761. Log::error('JD下发接口失败', $logContext);
  762. }
  763. } catch (Exception $e) {
  764. $ret = ['message' => $e->getMessage()];
  765. $success = false;
  766. $failureMessage = $e->getMessage();
  767. $logContext = [
  768. 'order_no' => $order_no,
  769. 'member_id' => $memberId,
  770. 'amount' => $amount,
  771. 'address' => $card_no,
  772. 'error' => $e->getMessage(),
  773. ];
  774. Log::channel('payment_error')->error('JD下发接口异常', $logContext);
  775. Log::error('JD下发接口异常', $logContext);
  776. }
  777. } else {
  778. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  779. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  780. $success = (($ret['code'] ?? 0) == 200);
  781. $failureMessage = $ret['msg'] ?? '代付失败';
  782. }
  783. if ($success) {
  784. // 更新提现记录状态为处理中
  785. DB::beginTransaction();
  786. try {
  787. $info->status = self::STATUS_PROCESS;
  788. if (NoPayService::isWithdrawChannel($channel) || JdPayService::isChannel($channel)) {
  789. $info->pay_no = $ret['data']['orderNo'] ?? '';
  790. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  791. }
  792. $info->save();
  793. DB::commit();
  794. $text = "✅ 提现申请已提交!\n\n";
  795. $text .= "钱包余额:{$available_balance} RMB\n";
  796. $text .= "提现金额:{$default_amount} RMB\n";
  797. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  798. $result['text'] = $text;
  799. } catch (Exception $e) {
  800. DB::rollBack();
  801. // 状态更新失败,但资金已扣款且三方支付已成功
  802. // 这里可以记录告警,需要人工干预
  803. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  804. 'member_id' => $memberId,
  805. 'order_no' => $order_no
  806. ]);
  807. $result['text'] = '提现申请已提交,系统处理中...';
  808. }
  809. } //
  810. else {
  811. // 三方支付失败,需要回滚之前的预扣款
  812. DB::beginTransaction();
  813. try {
  814. // 恢复钱包余额
  815. $wallet->available_balance = $balance;
  816. $wallet->save();
  817. // 更新提现记录状态为失败
  818. $info->status = self::STATUS_FAIL;
  819. $info->remark = $failureMessage;
  820. $info->save();
  821. // 记录退款日志
  822. BalanceLogService::addLog($memberId, $default_amount, $available_balance, $balance, '三方提现', $id, '提现失败退款');
  823. DB::commit();
  824. $result['text'] = $failureMessage;
  825. } catch (Exception $e) {
  826. DB::rollBack();
  827. // 回滚失败,需要记录告警,人工干预
  828. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  829. 'member_id' => $memberId,
  830. 'order_no' => $order_no,
  831. 'amount' => $amount
  832. ]);
  833. $result['text'] = '提现失败,请联系客服处理退款!';
  834. }
  835. }
  836. return $result;
  837. }
  838. /**
  839. * @description: 接收三方订单
  840. * @param {*} $params
  841. * @return {*}
  842. */
  843. public static function receiveOrder($params)
  844. {
  845. if (NoPayService::getWithdrawMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
  846. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  847. if (!$info || $info->type != self::TYPE_PAYOUT || !NoPayService::isWithdrawChannel($info->channel)) {
  848. return false;
  849. }
  850. if (!NoPayService::verifyWithdrawNotify($params)) {
  851. return false;
  852. }
  853. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  854. return false;
  855. }
  856. self::onSubmitNoPayout($params, $info);
  857. return true;
  858. }
  859. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  860. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  861. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  862. if (!$info || $info->type != self::TYPE_PAYOUT) {
  863. return false;
  864. }
  865. if (!JdPayService::verifyRemitNotify($params)) {
  866. return false;
  867. }
  868. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  869. return false;
  870. }
  871. self::onSubmitJdPayout($params, $info);
  872. return true;
  873. }
  874. // 判断商户号是否一致
  875. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  876. $info = self::findOne(['order_no' => $params['orderNo']]);
  877. if ($info) {
  878. // 判断金额是不是正确认
  879. if ($info->amount != $params['amount']) {
  880. return false;
  881. }
  882. // 验证签名
  883. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  884. if ($params['sign'] != $sign) {
  885. return false;
  886. }
  887. // 代付
  888. if ($info->type == self::TYPE_PAYOUT) {
  889. self::onSubmitPayout($params, $info);
  890. }
  891. // 代收
  892. if ($info->type == self::TYPE_PAY) {
  893. }
  894. }
  895. }
  896. }
  897. /**
  898. * @description: 处理代付订单
  899. * @param {*} $params
  900. * @return {*}
  901. */
  902. public static function onSubmitJdPayout($params, $info)
  903. {
  904. if ($info->status != self::STATUS_PROCESS) {
  905. return;
  906. }
  907. $memberId = $info->member_id;
  908. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  909. $data = [];
  910. $chat_id = $info->member_id;
  911. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  912. DB::beginTransaction();
  913. try {
  914. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  915. $data['status'] = self::STATUS_SUCCESS;
  916. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  917. if ($res) {
  918. $text = "✅ 提现通知 \n";
  919. $text .= "提现平台:{$info->bank_name} \n";
  920. $text .= "收款人:{$info->account} \n";
  921. $text .= "收款地址:{$info->card_no} \n";
  922. $text .= "提现金额:{$info->amount} \n";
  923. $text .= "提现成功,金额已到账,请注意查收!";
  924. self::notifyUser($chat_id, $text);
  925. }
  926. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  927. $data['status'] = self::STATUS_FAIL;
  928. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  929. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  930. $balance = $wallet->available_balance;
  931. $available_balance = bcadd($balance, $amount, 10);
  932. $wallet->available_balance = $available_balance;
  933. $wallet->save();
  934. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  935. if ($res) {
  936. $text = "❌ 提现通知 \n";
  937. $text .= "提现平台:{$info->bank_name} \n";
  938. $text .= "收款人:{$info->account} \n";
  939. $text .= "收款地址:{$info->card_no} \n";
  940. $text .= "提现金额:{$info->amount} \n";
  941. $text .= "提现失败,金额已返回钱包,请注意查收!";
  942. self::notifyUser($chat_id, $text);
  943. }
  944. }
  945. DB::commit();
  946. } catch (Exception $e) {
  947. DB::rollBack();
  948. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  949. }
  950. }
  951. public static function onSubmitNoPayout($params, $info)
  952. {
  953. $notification = null;
  954. try {
  955. DB::transaction(function () use ($params, $info, &$notification) {
  956. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  957. if (!$order || $order->status != self::STATUS_PROCESS) {
  958. return;
  959. }
  960. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  961. if ((string)$params['state'] === NoPayService::STATE_SUCCESS) {
  962. $order->status = self::STATUS_SUCCESS;
  963. $order->save();
  964. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  965. } elseif ((string)$params['state'] === NoPayService::STATE_FAIL) {
  966. $order->status = self::STATUS_FAIL;
  967. $order->save();
  968. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  969. if (!$wallet) {
  970. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  971. }
  972. $balance = $wallet->available_balance;
  973. $availableBalance = bcadd($balance, NoPayService::amount($order->amount), 10);
  974. $wallet->available_balance = $availableBalance;
  975. $wallet->save();
  976. BalanceLogService::addLog($order->member_id, $order->amount, $balance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  977. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  978. } else {
  979. $order->save();
  980. }
  981. }, 3);
  982. if ($notification !== null) {
  983. self::notifyUser($info->member_id, $notification);
  984. }
  985. } catch (Exception $e) {
  986. Log::channel('payment_error')->error('NO提现回调处理异常', [
  987. 'order_id' => $info->id,
  988. 'params' => $params,
  989. 'error' => $e->getMessage(),
  990. ]);
  991. }
  992. }
  993. public static function onSubmitPayout($params, $info)
  994. {
  995. $memberId = $info->member_id;
  996. $amount = $params['amount'];
  997. $data = [];
  998. $result = [];
  999. $chat_id = $info->member_id;
  1000. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1001. DB::beginTransaction();
  1002. try {
  1003. if ($params['state'] == 1) {
  1004. $data['status'] = self::STATUS_SUCCESS;
  1005. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1006. if ($res) {
  1007. $text = "✅ 提现通知 \n";
  1008. $text .= "提现平台:{$info->bank_name} \n";
  1009. $text .= "收款人:{$info->account} \n";
  1010. $text .= "收款卡号:{$info->card_no} \n";
  1011. $text .= "提现金额:{$info->amount} \n";
  1012. $text .= "提现成功,金额已到账,请注意查收!";
  1013. self::notifyUser($chat_id, $text);
  1014. }
  1015. } else {
  1016. $data['status'] = self::STATUS_FAIL;
  1017. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1018. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1019. $balance = $wallet->available_balance; // 钱包当前余额
  1020. $available_balance = bcadd($balance, $params['amount'], 10);
  1021. $wallet->available_balance = $available_balance;
  1022. $wallet->save();
  1023. // 记录退款日志
  1024. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  1025. if ($res) {
  1026. $text = "❌ 提现通知 \n";
  1027. $text .= "提现平台:{$info->bank_name} \n";
  1028. $text .= "收款人:{$info->account} \n";
  1029. $text .= "收款卡号:{$info->card_no} \n";
  1030. $text .= "提现金额:{$info->amount} \n";
  1031. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1032. self::notifyUser($chat_id, $text);
  1033. }
  1034. }
  1035. DB::commit();
  1036. } catch (Exception $e) {
  1037. DB::rollBack();
  1038. // 回滚失败,需要记录告警,人工干预
  1039. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  1040. }
  1041. }
  1042. /**
  1043. * @description: 查询支付订单
  1044. * @param {*} $id
  1045. * @return {*}
  1046. */
  1047. public static function singlePayOrder($id)
  1048. {
  1049. $msg = [];
  1050. $msg['code'] = self::NOT;
  1051. $info = self::findOne(['id' => $id]);
  1052. if ($info && $info->status == self::STATUS_PROCESS) {
  1053. if (NoPayService::isRechargeChannel($info->channel)) {
  1054. $ret = NoPayService::queryPayOrder($info->order_no, (string)$info->member_id);
  1055. Log::channel('payment')->info('NO支付查询订单', $ret);
  1056. if (($ret['code'] ?? -1) == 0) {
  1057. $item = $ret['data'] ?? [];
  1058. if ((string)($item['state'] ?? '') === NoPayService::STATE_SUCCESS) {
  1059. $processed = self::applyPayCallback(
  1060. $info,
  1061. NoPayService::amount($info->amount),
  1062. NoPayService::STATE_SUCCESS,
  1063. NoPayService::STATE_SUCCESS,
  1064. NoPayService::STATE_FAIL,
  1065. $ret
  1066. );
  1067. $msg['code'] = $processed ? self::YES : self::NOT;
  1068. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1069. } elseif ((string)($item['state'] ?? '') === NoPayService::STATE_FAIL) {
  1070. self::applyPayCallback(
  1071. $info,
  1072. NoPayService::amount($info->amount),
  1073. NoPayService::STATE_FAIL,
  1074. NoPayService::STATE_SUCCESS,
  1075. NoPayService::STATE_FAIL,
  1076. $ret
  1077. );
  1078. $msg['msg'] = '支付失败';
  1079. } else {
  1080. $msg['msg'] = '支付中';
  1081. }
  1082. } else {
  1083. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1084. }
  1085. return $msg;
  1086. }
  1087. if (JdPayService::isChannel($info->channel)) {
  1088. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  1089. Log::channel('payment')->info('JD支付查询订单', $ret);
  1090. if (($ret['code'] ?? 0) == 200) {
  1091. $item = $ret['data'] ?? [];
  1092. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  1093. $info->status = self::STATUS_SUCCESS;
  1094. $info->state = $item['status'];
  1095. $info->callback_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  1096. $info->save();
  1097. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1098. $balance = $wallet->available_balance;
  1099. $available_balance = bcadd($balance, $info->amount, 10);
  1100. $wallet->available_balance = $available_balance;
  1101. $wallet->save();
  1102. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  1103. self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
  1104. $msg['code'] = self::YES;
  1105. $msg['msg'] = '支付成功';
  1106. } else {
  1107. $msg['msg'] = '支付中';
  1108. }
  1109. } else {
  1110. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  1111. }
  1112. return $msg;
  1113. }
  1114. $ret = SanJinService::queryOrder($info->order_no);
  1115. Log::error('三斤支付查询订单:', $ret);
  1116. if ($ret['code'] == 0) {
  1117. $item = [];
  1118. $item['state'] = $ret['data']['state'];
  1119. if ($ret['data']['state'] == 1) {
  1120. $item['status'] = self::STATUS_SUCCESS;
  1121. $info->update($item);
  1122. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1123. $balance = $wallet->available_balance;
  1124. $available_balance = bcadd($balance, $info->amount, 10);
  1125. $wallet->available_balance = $available_balance;
  1126. $wallet->save();
  1127. // 记录余额变动日志
  1128. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  1129. $msg['code'] = self::YES;
  1130. $msg['msg'] = '支付成功';
  1131. } else {
  1132. $msg['msg'] = '支付中';
  1133. }
  1134. } else {
  1135. $msg['msg'] = '查询失败:' . $ret['message'];
  1136. }
  1137. } else {
  1138. $msg['msg'] = '该状态无法查询';
  1139. }
  1140. return $msg;
  1141. }
  1142. private static function assertJdBalanceEnough($amount, array $context = []): void
  1143. {
  1144. $ret = JdPayService::balance();
  1145. Log::channel('payment')->info('JD余额查询', $context + [
  1146. 'amount' => $amount,
  1147. 'response' => $ret,
  1148. ]);
  1149. if (($ret['code'] ?? 0) != 200) {
  1150. $logContext = $context + [
  1151. 'amount' => $amount,
  1152. 'response' => $ret,
  1153. ];
  1154. Log::channel('payment_error')->error('JD余额查询失败', $logContext);
  1155. Log::error('JD余额查询失败', $logContext);
  1156. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  1157. }
  1158. $balance = $ret['data']['balance'] ?? null;
  1159. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  1160. $logContext = $context + [
  1161. 'amount' => $amount,
  1162. 'balance' => $balance,
  1163. 'response' => $ret,
  1164. ];
  1165. Log::channel('payment_error')->error('JD商户余额不足', $logContext);
  1166. Log::error('JD商户余额不足', $logContext);
  1167. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  1168. }
  1169. }
  1170. private static function notifyUser($chatId, string $text): void
  1171. {
  1172. if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
  1173. return;
  1174. }
  1175. try {
  1176. self::sendMessage($chatId, $text);
  1177. } catch (\Throwable $e) {
  1178. Log::channel('payment_error')->error('支付订单用户通知失败', [
  1179. 'chat_id' => $chatId,
  1180. 'error' => $e->getMessage(),
  1181. ]);
  1182. }
  1183. }
  1184. public static function syncPayOrder()
  1185. {
  1186. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  1187. // foreach($list->toArray() as $k => $v){
  1188. // $item= [];
  1189. // if($v['status'] == self::STATUS_SUCCESS){
  1190. // $item['state'] = 1;
  1191. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1192. // }else{
  1193. // $ret = SanJinService::queryOrder($v['order_no']);
  1194. // var_dump($ret);
  1195. // if($ret['code'] == 0){
  1196. // $item['state'] = $ret['data']['state'];
  1197. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1198. // }
  1199. // }
  1200. // }
  1201. }
  1202. }