PaymentOrderService.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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. Log::error('NO钱包充值回调订单不存在或类型不匹配', [
  367. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  368. 'order_id' => $info->id ?? null,
  369. 'order_type' => $info->type ?? null,
  370. 'channel' => $info->channel ?? null,
  371. ]);
  372. return false;
  373. }
  374. if (!NoPayService::verifyDepositNotify($params)) {
  375. Log::error('NO钱包充值回调验签失败', [
  376. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  377. 'app_id' => $params['appId'] ?? '',
  378. ]);
  379. return false;
  380. }
  381. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  382. Log::error('NO钱包充值回调金额不一致', [
  383. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  384. 'order_amount' => $info->amount,
  385. 'callback_amount' => $params['amount'] ?? null,
  386. ]);
  387. return false;
  388. }
  389. if ($info->status != self::STATUS_PROCESS) {
  390. return true;
  391. }
  392. $processed = self::applyPayCallback(
  393. $info,
  394. NoPayService::amount($info->amount),
  395. (string)$params['state'],
  396. NoPayService::STATE_SUCCESS,
  397. NoPayService::STATE_FAIL,
  398. $params
  399. );
  400. if ($processed && (string)$params['state'] === NoPayService::STATE_SUCCESS) {
  401. self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
  402. }
  403. return true;
  404. }
  405. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  406. $info = self::findOne(['order_no' => $params['orderCode'] ?? ''])
  407. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  408. if (!$info || $info->type != self::TYPE_PAY) {
  409. return false;
  410. }
  411. if (!JdPayService::verifyPayNotify($params)) {
  412. return false;
  413. }
  414. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  415. return false;
  416. }
  417. if ($info->status != self::STATUS_PROCESS) {
  418. return true;
  419. }
  420. $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), (string)$params['status'], JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $params);
  421. if ($processed && (string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
  422. $text = "✅ 支付成功 \n";
  423. $text .= "充值金额:{$info->amount} RMB \n";
  424. $text .= "订单号:{$info->order_no} \n";
  425. $text .= "您充值的金额已到账,请注意查收!";
  426. self::notifyUser($info->member_id, $text);
  427. }
  428. return true;
  429. }
  430. // 判断商户号
  431. if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
  432. $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
  433. $info = self::findOne(['order_no' => $params['outTradeNo']]);
  434. if ($info) {
  435. // 平台以分计算转成元
  436. $payAmount = $params['payAmount'] / 100;
  437. // 判断金额是不是正确认
  438. if ($info->amount != $payAmount) {
  439. $text = '❌ 支付失败提醒 \n';
  440. $text .= "订单金额:{$info->amount} \n";
  441. $text .= "实际支付:{$payAmount} \n";
  442. $text .= "订单号:{$params['outTradeNo']} \n";
  443. $text .= "失败原因:支付金额与订单金额不一致 \n";
  444. $text .= "请联系客服处理!";
  445. self::notifyUser($info->member_id, $text);
  446. return false;
  447. }
  448. if ($params['sign'] != SanJinService::signature($params, $must)) {
  449. return false;
  450. }
  451. if ($info->status != self::STATUS_PROCESS) {
  452. return false;
  453. }
  454. // 付款
  455. if ($info->type == self::TYPE_PAY) {
  456. $processed = self::applyPayCallback($info, $payAmount, (string)$params['state'], '1', null, $params);
  457. if ($processed && $params['state'] == 1) {
  458. $text = "✅ 支付成功 \n";
  459. $text .= "充值金额:{$payAmount} RMB \n";
  460. $text .= "订单号:{$params['outTradeNo']} \n";
  461. $text .= "您充值的金额已到账,请注意查收!";
  462. self::notifyUser($info->member_id, $text);
  463. } else {
  464. $text = "❌ 支付失败 \n";
  465. $text .= "充值金额:{$payAmount} RMB \n";
  466. $text .= "订单号:{$params['outTradeNo']} \n";
  467. }
  468. return true;
  469. }
  470. }
  471. }
  472. }
  473. // 充值笔笔返
  474. public static function rechargesBibiReturn($memberId,$payAmount,$info_id)
  475. {
  476. $rate = ConfigService::getVal('recharges_bibi_return');
  477. $amount = $payAmount * $rate;
  478. if($rate > 0){
  479. $wallet = WalletService::findOne(['member_id' => $memberId]);
  480. $balance = $wallet->available_balance;
  481. $available_balance = bcadd($balance, $amount, 10);
  482. $wallet->available_balance = $available_balance;
  483. $wallet->save();
  484. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '优惠活动', $info_id, '充值笔笔返');
  485. }
  486. }
  487. private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
  488. {
  489. return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
  490. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  491. if (!$order || $order->status != self::STATUS_PROCESS) {
  492. return false;
  493. }
  494. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  495. $order->state = $status;
  496. if ($status === $successStatus) {
  497. $order->status = self::STATUS_SUCCESS;
  498. $order->save();
  499. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  500. if (!$wallet) {
  501. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  502. }
  503. $balance = $wallet->available_balance;
  504. $availableBalance = bcadd($balance, $payAmount, 10);
  505. $wallet->available_balance = $availableBalance;
  506. $wallet->save();
  507. BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
  508. $rate = ConfigService::getVal('recharges_bibi_return');
  509. $bonusAmount = $payAmount * $rate;
  510. if ($rate > 0 && $bonusAmount > 0) {
  511. $bonusBeforeBalance = $wallet->available_balance;
  512. $bonusAfterBalance = bcadd($bonusBeforeBalance, $bonusAmount, 10);
  513. $wallet->available_balance = $bonusAfterBalance;
  514. $wallet->save();
  515. BalanceLogService::addLog($order->member_id, $bonusAmount, $bonusBeforeBalance, $bonusAfterBalance, '优惠活动', $order->id, '充值笔笔返');
  516. }
  517. return true;
  518. }
  519. if ($failStatus === null || $status === $failStatus) {
  520. $order->status = self::STATUS_FAIL;
  521. }
  522. $order->save();
  523. return true;
  524. }, 3);
  525. }
  526. /**
  527. * 拒绝提现
  528. * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
  529. * @param int $orderId 订单ID PaymentOrder 表的ID
  530. * @param string $remark 失败原因
  531. * @return array
  532. */
  533. public static function withdrawalFailed($orderId, $remark): array
  534. {
  535. try {
  536. $order = PaymentOrder::where('id', $orderId)
  537. ->whereIn('type', [2,4])
  538. ->where('status', self::STATUS_STAY)
  539. ->first();
  540. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  541. // 更新提现记录状态为失败
  542. $order->status = self::STATUS_FAIL;
  543. $order->remark = $remark;
  544. if (!$order->save()) {
  545. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  546. }
  547. //钱包余额增加
  548. $wallet = WalletService::findOne(['member_id' => $order->member_id]);
  549. $beforeBalance = $wallet->available_balance;
  550. $availableBalance = bcadd($wallet->available_balance, $order->amount, 10);
  551. $wallet->available_balance = $availableBalance;
  552. if (!$wallet->save()) {
  553. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  554. }
  555. // 记录退款日志
  556. BalanceLogService::addLog($order->member_id, $order->amount, $beforeBalance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  557. } catch (Exception $e) {
  558. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  559. }
  560. return ['code' => 0, 'msg' => 'ok'];
  561. }
  562. /**
  563. * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
  564. * @param int $orderId PaymentOrder 表的ID
  565. */
  566. public static function createPayout(int $orderId): array
  567. {
  568. try {
  569. $order = PaymentOrder::where('id', $orderId)
  570. ->where('type', 2)
  571. ->where('status', self::STATUS_STAY)
  572. ->first();
  573. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  574. $amount = $order->amount;
  575. $amount = number_format($amount, 2, '.', '');
  576. if (NoPayService::isWithdrawChannel($order->channel)) {
  577. $ret = NoPayService::withdraw($amount, $order->order_no, (string)$order->member_id, (string)$order->account, (string)$order->card_no);
  578. Log::channel('payment')->info('NO提现接口调用', [
  579. 'order_id' => $order->id,
  580. 'order_no' => $order->order_no,
  581. 'member_id' => $order->member_id,
  582. 'amount' => $amount,
  583. 'q_account' => $order->card_no,
  584. 'response' => $ret,
  585. ]);
  586. if (($ret['code'] ?? -1) != 0) {
  587. throw new Exception($ret['msg'] ?? 'NO提现失败', HttpStatus::CUSTOM_ERROR);
  588. }
  589. $order->pay_no = $ret['data']['orderNo'] ?? '';
  590. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  591. } elseif (JdPayService::isChannel($order->channel)) {
  592. self::assertJdBalanceEnough($amount, [
  593. 'order_id' => $order->id,
  594. 'order_no' => $order->order_no,
  595. 'member_id' => $order->member_id,
  596. 'address' => $order->card_no,
  597. ]);
  598. $ret = JdPayService::remit($amount, $order->order_no, $order->card_no);
  599. Log::channel('payment')->info('JD下发接口调用', [
  600. 'order_id' => $order->id,
  601. 'order_no' => $order->order_no,
  602. 'member_id' => $order->member_id,
  603. 'amount' => $amount,
  604. 'address' => $order->card_no,
  605. 'response' => $ret,
  606. ]);
  607. if (($ret['code'] ?? 0) != 200) {
  608. $logContext = [
  609. 'order_id' => $order->id,
  610. 'order_no' => $order->order_no,
  611. 'member_id' => $order->member_id,
  612. 'amount' => $amount,
  613. 'address' => $order->card_no,
  614. 'response' => $ret,
  615. ];
  616. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  617. Log::error('JD下发接口失败', $logContext);
  618. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  619. }
  620. $order->pay_no = $ret['data']['orderNo'] ?? '';
  621. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  622. } else {
  623. $ret = QianBaoService::payout($amount, $order->order_no, $order->bank_name, $order->account, $order->card_no);
  624. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  625. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  626. }
  627. $order->status = self::STATUS_PROCESS;
  628. $order->save();
  629. } catch (Exception $e) {
  630. Log::channel('payment_error')->error('创建代付订单失败', [
  631. 'order_id' => $orderId,
  632. 'error' => $e->getMessage(),
  633. ]);
  634. Log::error('创建代付订单失败', [
  635. 'order_id' => $orderId,
  636. 'error' => $e->getMessage(),
  637. ]);
  638. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  639. }
  640. return ['code' => 0, 'msg' => 'ok'];
  641. }
  642. /**
  643. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  644. * @param {*} $memberId 会员ID
  645. * @param {*} $amount 代付金额
  646. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  647. * @param {*} $bank_name 银行名称/支付宝
  648. * @param {*} $account 姓名
  649. * @param {*} $card_no 银行卡号/支付宝账号
  650. * @return {*}
  651. */
  652. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  653. {
  654. $default_amount = $amount;
  655. $result = [];
  656. $result['chat_id'] = $memberId;
  657. if ($amount < 100) {
  658. $result['text'] = '提现金额最少100';
  659. return $result;
  660. }
  661. if ($amount > 49999) {
  662. $result['text'] = '提现金额最多49999';
  663. return $result;
  664. }
  665. // 在调用三方支付前开始事务
  666. DB::beginTransaction();
  667. try {
  668. $wallet = WalletService::findOne(['member_id' => $memberId]);
  669. if (!$wallet) {
  670. $result['text'] = '钱包不存在!';
  671. return $result;
  672. }
  673. $balance = $wallet->available_balance;
  674. if (bccomp($balance, $amount, 2) < 0) {
  675. $result['text'] = '您的钱包余额不足!';
  676. return $result;
  677. }
  678. $available_balance = bcsub($balance, $amount, 10);
  679. $data = [];
  680. $data['type'] = self::TYPE_PAYOUT;
  681. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  682. $data['order_no'] = $order_no;
  683. $data['member_id'] = $memberId;
  684. $data['fee'] = $amount * 0.002 + 2;
  685. $amount = number_format($amount, 2, '.', '');
  686. $data['amount'] = $amount;
  687. $data['channel'] = $channel;
  688. $data['bank_name'] = $bank_name;
  689. $data['account'] = $account;
  690. $data['card_no'] = $card_no;
  691. if (NoPayService::isWithdrawChannel($channel)) {
  692. $data['callback_url'] = NoPayService::getWithdrawNotifyUrl();
  693. } elseif (JdPayService::isChannel($channel)) {
  694. $data['callback_url'] = JdPayService::getRemitNotifyUrl();
  695. } else {
  696. $data['callback_url'] = QianBaoService::getNotifyUrl();
  697. }
  698. $data['status'] = self::STATUS_STAY;
  699. $data['remark'] = '提现费率:0.2%+2';
  700. // 先预扣款(锁定资金)
  701. $wallet->available_balance = $available_balance;
  702. if (!$wallet->save()) {
  703. DB::rollBack();
  704. $result['text'] = '钱包更新失败!';
  705. return $result;
  706. }
  707. // 创建待处理状态的提现记录
  708. $info = static::$MODEL::create($data);
  709. $id = $info->id;
  710. // 记录余额变动日志
  711. BalanceLogService::addLog($memberId, $default_amount * -1, $balance, $available_balance, '三方提现', $id, '钱宝提现费率:0.2%+2');
  712. // 提交事务,确保预扣款成功
  713. DB::commit();
  714. } //
  715. catch (Exception $e) {
  716. // 预扣款失败,回滚事务
  717. DB::rollBack();
  718. $result['text'] = '系统繁忙,请稍后重试!';
  719. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  720. 'member_id' => $memberId,
  721. 'amount' => $amount
  722. ]);
  723. return $result;
  724. }
  725. // 调用三方支付接口(在事务外)
  726. if (NoPayService::isWithdrawChannel($channel)) {
  727. try {
  728. $ret = NoPayService::withdraw($amount, $order_no, (string)$memberId, (string)$account, (string)$card_no);
  729. Log::channel('payment')->info('NO提现接口调用', [
  730. 'order_no' => $order_no,
  731. 'member_id' => $memberId,
  732. 'amount' => $amount,
  733. 'q_account' => $card_no,
  734. 'response' => $ret,
  735. ]);
  736. $success = (($ret['code'] ?? -1) == 0);
  737. $failureMessage = $ret['msg'] ?? 'NO提现失败';
  738. } catch (Exception $e) {
  739. $ret = ['msg' => $e->getMessage()];
  740. $success = false;
  741. $failureMessage = $e->getMessage();
  742. Log::channel('payment_error')->error('NO提现接口异常', [
  743. 'order_no' => $order_no,
  744. 'member_id' => $memberId,
  745. 'amount' => $amount,
  746. 'q_account' => $card_no,
  747. 'error' => $e->getMessage(),
  748. ]);
  749. }
  750. } elseif (JdPayService::isChannel($channel)) {
  751. try {
  752. self::assertJdBalanceEnough($amount, [
  753. 'order_no' => $order_no,
  754. 'member_id' => $memberId,
  755. 'address' => $card_no,
  756. ]);
  757. $ret = JdPayService::remit($amount, $order_no, $card_no);
  758. Log::channel('payment')->info('JD下发接口调用', [
  759. 'order_no' => $order_no,
  760. 'member_id' => $memberId,
  761. 'amount' => $amount,
  762. 'address' => $card_no,
  763. 'response' => $ret,
  764. ]);
  765. $success = (($ret['code'] ?? 0) == 200);
  766. $failureMessage = $ret['message'] ?? 'JD下发失败';
  767. if (!$success) {
  768. $logContext = [
  769. 'order_no' => $order_no,
  770. 'member_id' => $memberId,
  771. 'amount' => $amount,
  772. 'address' => $card_no,
  773. 'response' => $ret,
  774. ];
  775. Log::channel('payment_error')->error('JD下发接口失败', $logContext);
  776. Log::error('JD下发接口失败', $logContext);
  777. }
  778. } catch (Exception $e) {
  779. $ret = ['message' => $e->getMessage()];
  780. $success = false;
  781. $failureMessage = $e->getMessage();
  782. $logContext = [
  783. 'order_no' => $order_no,
  784. 'member_id' => $memberId,
  785. 'amount' => $amount,
  786. 'address' => $card_no,
  787. 'error' => $e->getMessage(),
  788. ];
  789. Log::channel('payment_error')->error('JD下发接口异常', $logContext);
  790. Log::error('JD下发接口异常', $logContext);
  791. }
  792. } else {
  793. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  794. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  795. $success = (($ret['code'] ?? 0) == 200);
  796. $failureMessage = $ret['msg'] ?? '代付失败';
  797. }
  798. if ($success) {
  799. // 更新提现记录状态为处理中
  800. DB::beginTransaction();
  801. try {
  802. $info->status = self::STATUS_PROCESS;
  803. if (NoPayService::isWithdrawChannel($channel) || JdPayService::isChannel($channel)) {
  804. $info->pay_no = $ret['data']['orderNo'] ?? '';
  805. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  806. }
  807. $info->save();
  808. DB::commit();
  809. $text = "✅ 提现申请已提交!\n\n";
  810. $text .= "钱包余额:{$available_balance} RMB\n";
  811. $text .= "提现金额:{$default_amount} RMB\n";
  812. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  813. $result['text'] = $text;
  814. } catch (Exception $e) {
  815. DB::rollBack();
  816. // 状态更新失败,但资金已扣款且三方支付已成功
  817. // 这里可以记录告警,需要人工干预
  818. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  819. 'member_id' => $memberId,
  820. 'order_no' => $order_no
  821. ]);
  822. $result['text'] = '提现申请已提交,系统处理中...';
  823. }
  824. } //
  825. else {
  826. // 三方支付失败,需要回滚之前的预扣款
  827. DB::beginTransaction();
  828. try {
  829. // 恢复钱包余额
  830. $wallet->available_balance = $balance;
  831. $wallet->save();
  832. // 更新提现记录状态为失败
  833. $info->status = self::STATUS_FAIL;
  834. $info->remark = $failureMessage;
  835. $info->save();
  836. // 记录退款日志
  837. BalanceLogService::addLog($memberId, $default_amount, $available_balance, $balance, '三方提现', $id, '提现失败退款');
  838. DB::commit();
  839. $result['text'] = $failureMessage;
  840. } catch (Exception $e) {
  841. DB::rollBack();
  842. // 回滚失败,需要记录告警,人工干预
  843. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  844. 'member_id' => $memberId,
  845. 'order_no' => $order_no,
  846. 'amount' => $amount
  847. ]);
  848. $result['text'] = '提现失败,请联系客服处理退款!';
  849. }
  850. }
  851. return $result;
  852. }
  853. /**
  854. * @description: 接收三方订单
  855. * @param {*} $params
  856. * @return {*}
  857. */
  858. public static function receiveOrder($params)
  859. {
  860. if (NoPayService::getWithdrawMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
  861. $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
  862. if (!$info || $info->type != self::TYPE_PAYOUT || !NoPayService::isWithdrawChannel($info->channel)) {
  863. Log::error('NO钱包提现回调订单不存在或类型不匹配', [
  864. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  865. 'order_id' => $info->id ?? null,
  866. 'order_type' => $info->type ?? null,
  867. 'channel' => $info->channel ?? null,
  868. ]);
  869. return false;
  870. }
  871. if (!NoPayService::verifyWithdrawNotify($params)) {
  872. Log::error('NO钱包提现回调验签失败', [
  873. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  874. 'app_id' => $params['appId'] ?? '',
  875. ]);
  876. return false;
  877. }
  878. if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  879. Log::error('NO钱包提现回调金额不一致', [
  880. 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
  881. 'order_amount' => $info->amount,
  882. 'callback_amount' => $params['amount'] ?? null,
  883. ]);
  884. return false;
  885. }
  886. self::onSubmitNoPayout($params, $info);
  887. return true;
  888. }
  889. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  890. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  891. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  892. if (!$info || $info->type != self::TYPE_PAYOUT) {
  893. return false;
  894. }
  895. if (!JdPayService::verifyRemitNotify($params)) {
  896. return false;
  897. }
  898. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  899. return false;
  900. }
  901. self::onSubmitJdPayout($params, $info);
  902. return true;
  903. }
  904. // 判断商户号是否一致
  905. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  906. $info = self::findOne(['order_no' => $params['orderNo']]);
  907. if ($info) {
  908. // 判断金额是不是正确认
  909. if ($info->amount != $params['amount']) {
  910. return false;
  911. }
  912. // 验证签名
  913. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  914. if ($params['sign'] != $sign) {
  915. return false;
  916. }
  917. // 代付
  918. if ($info->type == self::TYPE_PAYOUT) {
  919. self::onSubmitPayout($params, $info);
  920. }
  921. // 代收
  922. if ($info->type == self::TYPE_PAY) {
  923. }
  924. }
  925. }
  926. }
  927. /**
  928. * @description: 处理代付订单
  929. * @param {*} $params
  930. * @return {*}
  931. */
  932. public static function onSubmitJdPayout($params, $info)
  933. {
  934. if ($info->status != self::STATUS_PROCESS) {
  935. return;
  936. }
  937. $memberId = $info->member_id;
  938. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  939. $data = [];
  940. $chat_id = $info->member_id;
  941. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  942. DB::beginTransaction();
  943. try {
  944. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  945. $data['status'] = self::STATUS_SUCCESS;
  946. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  947. if ($res) {
  948. $text = "✅ 提现通知 \n";
  949. $text .= "提现平台:{$info->bank_name} \n";
  950. $text .= "收款人:{$info->account} \n";
  951. $text .= "收款地址:{$info->card_no} \n";
  952. $text .= "提现金额:{$info->amount} \n";
  953. $text .= "提现成功,金额已到账,请注意查收!";
  954. self::notifyUser($chat_id, $text);
  955. }
  956. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  957. $data['status'] = self::STATUS_FAIL;
  958. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  959. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  960. $balance = $wallet->available_balance;
  961. $available_balance = bcadd($balance, $amount, 10);
  962. $wallet->available_balance = $available_balance;
  963. $wallet->save();
  964. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  965. if ($res) {
  966. $text = "❌ 提现通知 \n";
  967. $text .= "提现平台:{$info->bank_name} \n";
  968. $text .= "收款人:{$info->account} \n";
  969. $text .= "收款地址:{$info->card_no} \n";
  970. $text .= "提现金额:{$info->amount} \n";
  971. $text .= "提现失败,金额已返回钱包,请注意查收!";
  972. self::notifyUser($chat_id, $text);
  973. }
  974. }
  975. DB::commit();
  976. } catch (Exception $e) {
  977. DB::rollBack();
  978. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  979. }
  980. }
  981. public static function onSubmitNoPayout($params, $info)
  982. {
  983. $notification = null;
  984. try {
  985. DB::transaction(function () use ($params, $info, &$notification) {
  986. $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
  987. if (!$order || $order->status != self::STATUS_PROCESS) {
  988. return;
  989. }
  990. $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  991. if ((string)$params['state'] === NoPayService::STATE_SUCCESS) {
  992. $order->status = self::STATUS_SUCCESS;
  993. $order->save();
  994. $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
  995. } elseif ((string)$params['state'] === NoPayService::STATE_FAIL) {
  996. $order->status = self::STATUS_FAIL;
  997. $order->save();
  998. $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
  999. if (!$wallet) {
  1000. throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
  1001. }
  1002. $balance = $wallet->available_balance;
  1003. $availableBalance = bcadd($balance, NoPayService::amount($order->amount), 10);
  1004. $wallet->available_balance = $availableBalance;
  1005. $wallet->save();
  1006. BalanceLogService::addLog($order->member_id, $order->amount, $balance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  1007. $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
  1008. } else {
  1009. $order->save();
  1010. }
  1011. }, 3);
  1012. if ($notification !== null) {
  1013. self::notifyUser($info->member_id, $notification);
  1014. }
  1015. } catch (Exception $e) {
  1016. Log::channel('payment_error')->error('NO提现回调处理异常', [
  1017. 'order_id' => $info->id,
  1018. 'params' => $params,
  1019. 'error' => $e->getMessage(),
  1020. ]);
  1021. }
  1022. }
  1023. public static function onSubmitPayout($params, $info)
  1024. {
  1025. $memberId = $info->member_id;
  1026. $amount = $params['amount'];
  1027. $data = [];
  1028. $result = [];
  1029. $chat_id = $info->member_id;
  1030. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  1031. DB::beginTransaction();
  1032. try {
  1033. if ($params['state'] == 1) {
  1034. $data['status'] = self::STATUS_SUCCESS;
  1035. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1036. if ($res) {
  1037. $text = "✅ 提现通知 \n";
  1038. $text .= "提现平台:{$info->bank_name} \n";
  1039. $text .= "收款人:{$info->account} \n";
  1040. $text .= "收款卡号:{$info->card_no} \n";
  1041. $text .= "提现金额:{$info->amount} \n";
  1042. $text .= "提现成功,金额已到账,请注意查收!";
  1043. self::notifyUser($chat_id, $text);
  1044. }
  1045. } else {
  1046. $data['status'] = self::STATUS_FAIL;
  1047. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  1048. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1049. $balance = $wallet->available_balance; // 钱包当前余额
  1050. $available_balance = bcadd($balance, $params['amount'], 10);
  1051. $wallet->available_balance = $available_balance;
  1052. $wallet->save();
  1053. // 记录退款日志
  1054. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  1055. if ($res) {
  1056. $text = "❌ 提现通知 \n";
  1057. $text .= "提现平台:{$info->bank_name} \n";
  1058. $text .= "收款人:{$info->account} \n";
  1059. $text .= "收款卡号:{$info->card_no} \n";
  1060. $text .= "提现金额:{$info->amount} \n";
  1061. $text .= "提现失败,金额已返回钱包,请注意查收!";
  1062. self::notifyUser($chat_id, $text);
  1063. }
  1064. }
  1065. DB::commit();
  1066. } catch (Exception $e) {
  1067. DB::rollBack();
  1068. // 回滚失败,需要记录告警,人工干预
  1069. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  1070. }
  1071. }
  1072. /**
  1073. * @description: 查询支付订单
  1074. * @param {*} $id
  1075. * @return {*}
  1076. */
  1077. public static function singlePayOrder($id)
  1078. {
  1079. $msg = [];
  1080. $msg['code'] = self::NOT;
  1081. $info = self::findOne(['id' => $id]);
  1082. if ($info && $info->status == self::STATUS_PROCESS) {
  1083. if (NoPayService::isRechargeChannel($info->channel)) {
  1084. $ret = NoPayService::queryPayOrder($info->order_no, (string)$info->member_id);
  1085. Log::channel('payment')->info('NO支付查询订单', $ret);
  1086. if (($ret['code'] ?? -1) == 0) {
  1087. $item = $ret['data'] ?? [];
  1088. if ((string)($item['state'] ?? '') === NoPayService::STATE_SUCCESS) {
  1089. $processed = self::applyPayCallback(
  1090. $info,
  1091. NoPayService::amount($info->amount),
  1092. NoPayService::STATE_SUCCESS,
  1093. NoPayService::STATE_SUCCESS,
  1094. NoPayService::STATE_FAIL,
  1095. $ret
  1096. );
  1097. $msg['code'] = $processed ? self::YES : self::NOT;
  1098. $msg['msg'] = $processed ? '支付成功' : '订单已处理';
  1099. } elseif ((string)($item['state'] ?? '') === NoPayService::STATE_FAIL) {
  1100. self::applyPayCallback(
  1101. $info,
  1102. NoPayService::amount($info->amount),
  1103. NoPayService::STATE_FAIL,
  1104. NoPayService::STATE_SUCCESS,
  1105. NoPayService::STATE_FAIL,
  1106. $ret
  1107. );
  1108. $msg['msg'] = '支付失败';
  1109. } else {
  1110. $msg['msg'] = '支付中';
  1111. }
  1112. } else {
  1113. $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
  1114. }
  1115. return $msg;
  1116. }
  1117. if (JdPayService::isChannel($info->channel)) {
  1118. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  1119. Log::channel('payment')->info('JD支付查询订单', $ret);
  1120. if (($ret['code'] ?? 0) == 200) {
  1121. $item = $ret['data'] ?? [];
  1122. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  1123. $info->status = self::STATUS_SUCCESS;
  1124. $info->state = $item['status'];
  1125. $info->callback_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  1126. $info->save();
  1127. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1128. $balance = $wallet->available_balance;
  1129. $available_balance = bcadd($balance, $info->amount, 10);
  1130. $wallet->available_balance = $available_balance;
  1131. $wallet->save();
  1132. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  1133. self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
  1134. $msg['code'] = self::YES;
  1135. $msg['msg'] = '支付成功';
  1136. } else {
  1137. $msg['msg'] = '支付中';
  1138. }
  1139. } else {
  1140. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  1141. }
  1142. return $msg;
  1143. }
  1144. $ret = SanJinService::queryOrder($info->order_no);
  1145. Log::error('三斤支付查询订单:', $ret);
  1146. if ($ret['code'] == 0) {
  1147. $item = [];
  1148. $item['state'] = $ret['data']['state'];
  1149. if ($ret['data']['state'] == 1) {
  1150. $item['status'] = self::STATUS_SUCCESS;
  1151. $info->update($item);
  1152. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  1153. $balance = $wallet->available_balance;
  1154. $available_balance = bcadd($balance, $info->amount, 10);
  1155. $wallet->available_balance = $available_balance;
  1156. $wallet->save();
  1157. // 记录余额变动日志
  1158. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  1159. $msg['code'] = self::YES;
  1160. $msg['msg'] = '支付成功';
  1161. } else {
  1162. $msg['msg'] = '支付中';
  1163. }
  1164. } else {
  1165. $msg['msg'] = '查询失败:' . $ret['message'];
  1166. }
  1167. } else {
  1168. $msg['msg'] = '该状态无法查询';
  1169. }
  1170. return $msg;
  1171. }
  1172. private static function assertJdBalanceEnough($amount, array $context = []): void
  1173. {
  1174. $ret = JdPayService::balance();
  1175. Log::channel('payment')->info('JD余额查询', $context + [
  1176. 'amount' => $amount,
  1177. 'response' => $ret,
  1178. ]);
  1179. if (($ret['code'] ?? 0) != 200) {
  1180. $logContext = $context + [
  1181. 'amount' => $amount,
  1182. 'response' => $ret,
  1183. ];
  1184. Log::channel('payment_error')->error('JD余额查询失败', $logContext);
  1185. Log::error('JD余额查询失败', $logContext);
  1186. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  1187. }
  1188. $balance = $ret['data']['balance'] ?? null;
  1189. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  1190. $logContext = $context + [
  1191. 'amount' => $amount,
  1192. 'balance' => $balance,
  1193. 'response' => $ret,
  1194. ];
  1195. Log::channel('payment_error')->error('JD商户余额不足', $logContext);
  1196. Log::error('JD商户余额不足', $logContext);
  1197. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  1198. }
  1199. }
  1200. private static function notifyUser($chatId, string $text): void
  1201. {
  1202. if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
  1203. return;
  1204. }
  1205. try {
  1206. self::sendMessage($chatId, $text);
  1207. } catch (\Throwable $e) {
  1208. Log::channel('payment_error')->error('支付订单用户通知失败', [
  1209. 'chat_id' => $chatId,
  1210. 'error' => $e->getMessage(),
  1211. ]);
  1212. }
  1213. }
  1214. public static function syncPayOrder()
  1215. {
  1216. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  1217. // foreach($list->toArray() as $k => $v){
  1218. // $item= [];
  1219. // if($v['status'] == self::STATUS_SUCCESS){
  1220. // $item['state'] = 1;
  1221. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1222. // }else{
  1223. // $ret = SanJinService::queryOrder($v['order_no']);
  1224. // var_dump($ret);
  1225. // if($ret['code'] == 0){
  1226. // $item['state'] = $ret['data']['state'];
  1227. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  1228. // }
  1229. // }
  1230. // }
  1231. }
  1232. }