PaymentOrderService.php 44 KB

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