| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118 |
- <?php
- namespace App\Services;
- use App\Constants\HttpStatus;
- use App\Models\PaymentOrder;
- use App\Models\User;
- use App\Models\Wallet as WalletModel;
- use Exception;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use App\Services\Payment\JdPayService;
- use App\Services\Payment\QianBaoService;
- use App\Services\Payment\SanJinService;
- use App\Services\ConfigService;
- /**
- * 投注
- */
- class PaymentOrderService extends BaseService
- {
- const TYPE_PAY = 1; // 代收
- const TYPE_PAYOUT = 2; // 代付
- const TYPE_SELF_PAY = 3; // 手动充值
- const TYPE_SELF_PAYOUT = 4; // 手动提现打款
- const STATUS_STAY = 0; // 待处理
- const STATUS_PROCESS = 1; // 处理中
- const STATUS_SUCCESS = 2; // 成功
- const STATUS_FAIL = 3; // 失败
- const STATUS_USER = 4; // 待用户提交凭证
- const STATUS_AUDIT = 5; //待人工审核
- const STATUS_CANCEL = 6; //已撤回
- public static string $MODEL = PaymentOrder::class;
- /**
- * @description: 模型
- * @return {string}
- */
- public static function model(): string
- {
- return PaymentOrder::class;
- }
- /**
- * @description: 枚举
- * @return {*}
- */
- public static function enum(): string
- {
- return '';
- }
- /**
- * @description: 获取查询条件
- * @param {array} $search 查询内容
- * @return {array}
- */
- public static function getWhere(array $search = []): array
- {
- $where = [];
- if (isset($search['member_id']) && !empty($search['member_id'])) {
- $where[] = ['payment_orders.member_id', '=', $search['member_id']];
- }
- if (isset($search['channel']) && !empty($search['channel'])) {
- if ($search['channel'] == 'rgcz') {
- $search['type'] = 3;
- }
- $where[] = ['payment_orders.channel', '=', $search['channel']];
-
- }
- if (isset($search['type']) && !empty($search['type'])) {
- $where[] = ['payment_orders.type', '=', $search['type']];
- }
- if (isset($search['order_no']) && !empty($search['order_no'])) {
- $where[] = ['payment_orders.order_no', '=', $search['order_no']];
- }
- if (isset($search['id']) && !empty($search['id'])) {
- $where[] = ['payment_orders.id', '=', $search['id']];
- }
- if (isset($search['status']) && $search['status'] != '') {
- $where[] = ['payment_orders.status', '=', $search['status']];
- }
- if (isset($search['first_name']) && !empty($search['first_name'])) {
- $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
- }
- if (isset($search['payment_type']) && $search['payment_type'] != '') {
- $where[] = ['payment_orders.payment_type', '=', $search['payment_type']];
- }
- return $where;
- }
- /**
- * @description: 查询单条数据
- * @param array $search
- * @return \App\Models\Coin|null
- */
- public static function findOne(array $search): ?PaymentOrder
- {
- return static::$MODEL::where(self::getWhere($search))->first();
- }
- /**
- * @description: 查询所有数据
- * @param array $search
- * @return \Illuminate\Database\Eloquent\Collection
- */
- public static function findAll(array $search = [])
- {
- return static::$MODEL::where(self::getWhere($search))->get();
- }
- /**
- * @description: 分页查询
- * @param array $search
- * @return array
- */
- public static function paginate(array $search = [])
- {
- $limit = isset($search['limit']) ? $search['limit'] : 15;
- $paginator = static::$MODEL::where(self::getWhere($search))
- ->join('users', 'users.member_id', '=', 'payment_orders.member_id')
- ->select("payment_orders.*", "users.first_name","users.admin_note as user_admin_note") // 提前查好需要的字段
- ->orderByDesc('payment_orders.created_at')
- ->paginate($limit);
- $totalAmount = 0;
- $totalSuccess = 0;
- $totalFail = 0;
- $list = $paginator->items();
- foreach ($list as $item) {
- $item['amount'] = floatval($item['amount']);
- $totalAmount += $item['amount'];
- if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
- if ($item['status'] == 3) $totalFail += $item['amount'];
- }
- return [
- 'total' => $paginator->total(),
- 'total_amount' => $totalAmount,
- 'total_success' => $totalSuccess,
- 'total_fail' => $totalFail,
- 'data' => $list
- ];
- }
- /**
- * @description:
- * @param {*} $params
- * @return {*}
- */
- public static function submit($params = [])
- {
- $result = false;
- $msg['code'] = self::NOT;
- $msg['msg'] = '';
- // 2. 判断是否是更新
- if (!empty($params['id'])) {
- // 更新
- $info = self::findOne(['id' => $params['id']]);
- if (!$info) {
- $msg['msg'] = '数据不存在!';
- } else {
- $result = $info->update($params);
- $id = $params['id'];
- }
- } else {
- // 创建
- $result = $info = static::$MODEL::create($params);
- $id = $result->id;
- }
- if ($result) {
- $msg['code'] = self::YES;
- $msg['msg'] = '设置成功';
- $msg['key'] = $id;
- } else {
- $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
- }
- return $msg;
- }
- /**
- * @description: 创建代收订单
- * @param {*} $memberId
- * @param {*} $amount
- * @param {*} $paymentType 支付类型:支付宝、数字人民币
- * @return {*}
- */
- public static function createPay($memberId, $amount, $paymentType)
- {
- $result = [];
- $result['chat_id'] = $memberId;
- $result['code'] = 0;
- $result['url'] = '';
- $channel = ''; // 支付的通道
- $product = SanJinService::product();
- $max = 0;
- $min = 0;
- $rate = 0;
- $selectedProduct = null;
- $geText = '';
- foreach ($product as $k => $v) {
- if ($v['type'] == $paymentType) {
- $selectedProduct = $v;
- if ($v['type'] == 'zfbge') {
- if (in_array($amount, $v['fixed'])) {
- $channel = $k;
- } else {
- $geText .= "❌ 此充值通道固定充值金额为" . implode(',', $v['fixed']) . "请务必输入区间金额!";
- }
- } else {
- if ($amount >= $v['min'] && $amount <= $v['max']) {
- $channel = $k;
- $rate = $v['rate'];
- }
- if ($min == 0) {
- $min = $v['min'];
- }
- if ($max == 0) {
- $max = $v['max'];
- }
- if ($min > $v['min']) {
- $min = $v['min'];
- }
- if ($max < $v['max']) {
- $max = $v['max'];
- }
- }
- }
- }
- // 没有找到支付通道
- if (empty($channel) && !JdPayService::isChannel($paymentType)) {
- // $text = "发起充值失败 \n";
- // $text .= "最低充值:" . $min . " \n";
- // $text .= "最高充值:" . $max . " \n";
- // $text .= "请重新填写充值的金额!";
- $text = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
- $result['text'] = $text;
- if ($geText) {
- $result['text'] = $geText;
- }
- $result['code'] = 20001;
- return $result;
- }
- if (JdPayService::isChannel($paymentType) || JdPayService::isChannel($channel)) {
- $channel = JdPayService::CHANNEL;
- $bankName = $selectedProduct['name'] ?? 'JD钱包';
- $data = [];
- $data['type'] = self::TYPE_PAY;
- $data['member_id'] = $memberId;
- $data['amount'] = JdPayService::amount($amount);
- $data['channel'] = $channel;
- $data['fee'] = $amount * $rate;
- $data['bank_name'] = $bankName;
- $order_no = self::createOrderNo('jd' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['callback_url'] = JdPayService::getNotifyUrl();
- $data['remark'] = '充值费率:' . $rate;
- $data['status'] = self::STATUS_STAY;
- $ret = JdPayService::pay($amount, $order_no);
- Log::channel('payment')->info('JD支付发起', $ret);
- if (($ret['code'] ?? 0) == 200) {
- $item = $ret['data'] ?? [];
- $payUrl = $item['url'] ?? '';
- $data['status'] = self::STATUS_PROCESS;
- $data['pay_no'] = $item['orderNo'] ?? '';
- $data['pay_url'] = $payUrl;
- $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
- static::$MODEL::create($data);
- if ($payUrl) {
- $result['image'] = asset(self::createPaymentQrCode($payUrl));
- }
- $text = "{$bankName}充值确认 \n";
- $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
- $text .= "支付地址:{$payUrl}\n";
- $text .= "支付金额:" . $amount . " RMB \n";
- $text .= "请按实际支付金额进行付款,否则影响到账 \n";
- $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
- $result['text'] = $text;
- $result['url'] = $payUrl;
- } else {
- $result['text'] = $ret['message'] ?? 'JD支付发起失败';
- $result['code'] = 20002;
- }
- return $result;
- }
- $data = [];
- $data['type'] = self::TYPE_PAY;
- $data['member_id'] = $memberId;
- $data['amount'] = $amount;
- $data['channel'] = $channel;
- $data['fee'] = $amount * $rate;
- $data['bank_name'] = SanJinService::getChannel($paymentType) ?? '';
- $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['callback_url'] = SanJinService::getNotifyUrl();
- $data['remark'] = '充值费率:' . $rate;
- $data['status'] = self::STATUS_STAY;
- $ret = SanJinService::pay(($amount * 100), $order_no, $channel);
- Log::error('三斤支付发起:', $ret);
- if ($ret['code'] == 0) {
- $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
- $result['image'] = $qrCode;
- $item = $ret['data'];
- $data['status'] = self::STATUS_PROCESS;
- $data['pay_no'] = $item['tradeNo'];
- $data['pay_url'] = $item['payUrl'];
- $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
- $info = static::$MODEL::create($data);
- // $text = "✅ 支付提示 \n";
- $text = "{$data['bank_name']}充值确认 \n";
- // $text .= "支付方式:{$data['bank_name']} \n";
- $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
- $text .= "支付地址:{$ret['data']['payUrl']}\n";
- $text .= "支付金额:" . $amount . " RMB \n";
- $text .= "请按实际支付金额进行付款,否则影响到账 \n";
- $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
- $result['text'] = $text;
- $result['url'] = $ret['data']['payUrl'];
- } else {
- $result['text'] = $ret['message'];
- $result['code'] = 20002;
- }
- return $result;
- }
- /**
- * @description: 接收支付的通知
- * @param {*} $params
- * @return {*}
- */
- public static function receivePay($params)
- {
- if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
- $info = self::findOne(['order_no' => $params['orderCode'] ?? ''])
- ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
- if (!$info || $info->type != self::TYPE_PAY) {
- return false;
- }
- if (!JdPayService::verifyPayNotify($params)) {
- return false;
- }
- if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- return false;
- }
- if ($info->status != self::STATUS_PROCESS) {
- return true;
- }
- $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), (string)$params['status'], JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $params);
- if ($processed && (string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
- $text = "✅ 支付成功 \n";
- $text .= "充值金额:{$info->amount} RMB \n";
- $text .= "订单号:{$info->order_no} \n";
- $text .= "您充值的金额已到账,请注意查收!";
- self::notifyUser($info->member_id, $text);
- }
- return true;
- }
- // 判断商户号
- if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
- $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
- $info = self::findOne(['order_no' => $params['outTradeNo']]);
- if ($info) {
- // 平台以分计算转成元
- $payAmount = $params['payAmount'] / 100;
- // 判断金额是不是正确认
- if ($info->amount != $payAmount) {
- $text = '❌ 支付失败提醒 \n';
- $text .= "订单金额:{$info->amount} \n";
- $text .= "实际支付:{$payAmount} \n";
- $text .= "订单号:{$params['outTradeNo']} \n";
- $text .= "失败原因:支付金额与订单金额不一致 \n";
- $text .= "请联系客服处理!";
- self::notifyUser($info->member_id, $text);
- return false;
- }
- if ($params['sign'] != SanJinService::signature($params, $must)) {
- return false;
- }
- if ($info->status != self::STATUS_PROCESS) {
- return false;
- }
- // 付款
- if ($info->type == self::TYPE_PAY) {
- $processed = self::applyPayCallback($info, $payAmount, (string)$params['state'], '1', null, $params);
- if ($processed && $params['state'] == 1) {
- $text = "✅ 支付成功 \n";
- $text .= "充值金额:{$payAmount} RMB \n";
- $text .= "订单号:{$params['outTradeNo']} \n";
- $text .= "您充值的金额已到账,请注意查收!";
- self::notifyUser($info->member_id, $text);
- } else {
- $text = "❌ 支付失败 \n";
- $text .= "充值金额:{$payAmount} RMB \n";
- $text .= "订单号:{$params['outTradeNo']} \n";
- }
- return true;
- }
- }
- }
- }
- // 充值笔笔返
- public static function rechargesBibiReturn($memberId,$payAmount,$info_id)
- {
- $rate = ConfigService::getVal('recharges_bibi_return');
- $amount = $payAmount * $rate;
- if($rate > 0){
- $wallet = WalletService::findOne(['member_id' => $memberId]);
- $balance = $wallet->available_balance;
- $available_balance = bcadd($balance, $amount, 10);
- $wallet->available_balance = $available_balance;
- $wallet->save();
- BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '优惠活动', $info_id, '充值笔笔返');
- }
- }
- private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
- {
- return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
- $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
- if (!$order || $order->status != self::STATUS_PROCESS) {
- return false;
- }
- $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
- $order->state = $status;
- if ($status === $successStatus) {
- $order->status = self::STATUS_SUCCESS;
- $order->save();
- $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
- if (!$wallet) {
- throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
- }
- $balance = $wallet->available_balance;
- $availableBalance = bcadd($balance, $payAmount, 10);
- $wallet->available_balance = $availableBalance;
- $wallet->save();
- BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
- $rate = ConfigService::getVal('recharges_bibi_return');
- $bonusAmount = $payAmount * $rate;
- if ($rate > 0 && $bonusAmount > 0) {
- $bonusBeforeBalance = $wallet->available_balance;
- $bonusAfterBalance = bcadd($bonusBeforeBalance, $bonusAmount, 10);
- $wallet->available_balance = $bonusAfterBalance;
- $wallet->save();
- BalanceLogService::addLog($order->member_id, $bonusAmount, $bonusBeforeBalance, $bonusAfterBalance, '优惠活动', $order->id, '充值笔笔返');
- }
- return true;
- }
- if ($failStatus === null || $status === $failStatus) {
- $order->status = self::STATUS_FAIL;
- }
- $order->save();
- return true;
- }, 3);
- }
- /**
- * 拒绝提现
- * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
- * @param int $orderId 订单ID PaymentOrder 表的ID
- * @param string $remark 失败原因
- * @return array
- */
- public static function withdrawalFailed($orderId, $remark): array
- {
- try {
- $order = PaymentOrder::where('id', $orderId)
- ->where('type', 2)
- ->where('status', self::STATUS_STAY)
- ->first();
- if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
- // 更新提现记录状态为失败
- $order->status = self::STATUS_FAIL;
- $order->remark = $remark;
- if (!$order->save()) {
- throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
- }
- //钱包余额增加
- $wallet = WalletService::findOne(['member_id' => $order->member_id]);
- $beforeBalance = $wallet->available_balance;
- $availableBalance = bcadd($wallet->available_balance, $order->amount, 10);
- $wallet->available_balance = $availableBalance;
- if (!$wallet->save()) {
- throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
- }
- // 记录退款日志
- BalanceLogService::addLog($order->member_id, $order->amount, $beforeBalance, $availableBalance, '三方提现', $order->id, '提现失败退款');
- } catch (Exception $e) {
- return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
- }
- return ['code' => 0, 'msg' => 'ok'];
- }
- /**
- * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
- * @param int $orderId PaymentOrder 表的ID
- */
- public static function createPayout(int $orderId): array
- {
- try {
- $order = PaymentOrder::where('id', $orderId)
- ->where('type', 2)
- ->where('status', self::STATUS_STAY)
- ->first();
- if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
- $amount = $order->amount;
- $amount = number_format($amount, 2, '.', '');
- if (JdPayService::isChannel($order->channel)) {
- self::assertJdBalanceEnough($amount, [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'address' => $order->card_no,
- ]);
- $ret = JdPayService::remit($amount, $order->order_no, $order->card_no);
- Log::channel('payment')->info('JD下发接口调用', [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'amount' => $amount,
- 'address' => $order->card_no,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? 0) != 200) {
- $logContext = [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'amount' => $amount,
- 'address' => $order->card_no,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD下发接口失败', $logContext);
- Log::error('JD下发接口失败', $logContext);
- throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
- }
- $order->pay_no = $ret['data']['orderNo'] ?? '';
- $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- } else {
- $ret = QianBaoService::payout($amount, $order->order_no, $order->bank_name, $order->account, $order->card_no);
- Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
- if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
- }
- $order->status = self::STATUS_PROCESS;
- $order->save();
- } catch (Exception $e) {
- Log::channel('payment_error')->error('创建代付订单失败', [
- 'order_id' => $orderId,
- 'error' => $e->getMessage(),
- ]);
- Log::error('创建代付订单失败', [
- 'order_id' => $orderId,
- 'error' => $e->getMessage(),
- ]);
- return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
- }
- return ['code' => 0, 'msg' => 'ok'];
- }
- /**
- * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
- * @param {*} $memberId 会员ID
- * @param {*} $amount 代付金额
- * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
- * @param {*} $bank_name 银行名称/支付宝
- * @param {*} $account 姓名
- * @param {*} $card_no 银行卡号/支付宝账号
- * @return {*}
- */
- public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
- {
- $default_amount = $amount;
- $result = [];
- $result['chat_id'] = $memberId;
- if ($amount < 100) {
- $result['text'] = '提现金额最少100';
- return $result;
- }
- if ($amount > 49999) {
- $result['text'] = '提现金额最多49999';
- return $result;
- }
- // 在调用三方支付前开始事务
- DB::beginTransaction();
- try {
- $wallet = WalletService::findOne(['member_id' => $memberId]);
- if (!$wallet) {
- $result['text'] = '钱包不存在!';
- return $result;
- }
- $balance = $wallet->available_balance;
- if (bccomp($balance, $amount, 2) < 0) {
- $result['text'] = '您的钱包余额不足!';
- return $result;
- }
- $available_balance = bcsub($balance, $amount, 10);
- $data = [];
- $data['type'] = self::TYPE_PAYOUT;
- $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['member_id'] = $memberId;
- $data['fee'] = $amount * 0.002 + 2;
- $amount = number_format($amount, 2, '.', '');
- $data['amount'] = $amount;
- $data['channel'] = $channel;
- $data['bank_name'] = $bank_name;
- $data['account'] = $account;
- $data['card_no'] = $card_no;
- $data['callback_url'] = JdPayService::isChannel($channel) ? JdPayService::getRemitNotifyUrl() : QianBaoService::getNotifyUrl();
- $data['status'] = self::STATUS_STAY;
- $data['remark'] = '提现费率:0.2%+2';
- // 先预扣款(锁定资金)
- $wallet->available_balance = $available_balance;
- if (!$wallet->save()) {
- DB::rollBack();
- $result['text'] = '钱包更新失败!';
- return $result;
- }
- // 创建待处理状态的提现记录
- $info = static::$MODEL::create($data);
- $id = $info->id;
- // 记录余额变动日志
- BalanceLogService::addLog($memberId, $default_amount * -1, $balance, $available_balance, '三方提现', $id, '钱宝提现费率:0.2%+2');
- // 提交事务,确保预扣款成功
- DB::commit();
- } //
- catch (Exception $e) {
- // 预扣款失败,回滚事务
- DB::rollBack();
- $result['text'] = '系统繁忙,请稍后重试!';
- Log::error('提现预扣款失败: ' . $e->getMessage(), [
- 'member_id' => $memberId,
- 'amount' => $amount
- ]);
- return $result;
- }
- // 调用三方支付接口(在事务外)
- if (JdPayService::isChannel($channel)) {
- try {
- self::assertJdBalanceEnough($amount, [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'address' => $card_no,
- ]);
- $ret = JdPayService::remit($amount, $order_no, $card_no);
- Log::channel('payment')->info('JD下发接口调用', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'address' => $card_no,
- 'response' => $ret,
- ]);
- $success = (($ret['code'] ?? 0) == 200);
- $failureMessage = $ret['message'] ?? 'JD下发失败';
- if (!$success) {
- $logContext = [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'address' => $card_no,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD下发接口失败', $logContext);
- Log::error('JD下发接口失败', $logContext);
- }
- } catch (Exception $e) {
- $ret = ['message' => $e->getMessage()];
- $success = false;
- $failureMessage = $e->getMessage();
- $logContext = [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'address' => $card_no,
- 'error' => $e->getMessage(),
- ];
- Log::channel('payment_error')->error('JD下发接口异常', $logContext);
- Log::error('JD下发接口异常', $logContext);
- }
- } else {
- $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
- Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
- $success = (($ret['code'] ?? 0) == 200);
- $failureMessage = $ret['msg'] ?? '代付失败';
- }
- if ($success) {
- // 更新提现记录状态为处理中
- DB::beginTransaction();
- try {
- $info->status = self::STATUS_PROCESS;
- if (JdPayService::isChannel($channel)) {
- $info->pay_no = $ret['data']['orderNo'] ?? '';
- $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- }
- $info->save();
- DB::commit();
- $text = "✅ 提现申请已提交!\n\n";
- $text .= "钱包余额:{$available_balance} RMB\n";
- $text .= "提现金额:{$default_amount} RMB\n";
- $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
- $result['text'] = $text;
- } catch (Exception $e) {
- DB::rollBack();
- // 状态更新失败,但资金已扣款且三方支付已成功
- // 这里可以记录告警,需要人工干预
- Log::error('提现状态更新失败: ' . $e->getMessage(), [
- 'member_id' => $memberId,
- 'order_no' => $order_no
- ]);
- $result['text'] = '提现申请已提交,系统处理中...';
- }
- } //
- else {
- // 三方支付失败,需要回滚之前的预扣款
- DB::beginTransaction();
- try {
- // 恢复钱包余额
- $wallet->available_balance = $balance;
- $wallet->save();
- // 更新提现记录状态为失败
- $info->status = self::STATUS_FAIL;
- $info->remark = $failureMessage;
- $info->save();
- // 记录退款日志
- BalanceLogService::addLog($memberId, $default_amount, $available_balance, $balance, '三方提现', $id, '提现失败退款');
- DB::commit();
- $result['text'] = $failureMessage;
- } catch (Exception $e) {
- DB::rollBack();
- // 回滚失败,需要记录告警,人工干预
- Log::error('提现失败回滚异常: ' . $e->getMessage(), [
- 'member_id' => $memberId,
- 'order_no' => $order_no,
- 'amount' => $amount
- ]);
- $result['text'] = '提现失败,请联系客服处理退款!';
- }
- }
- return $result;
- }
- /**
- * @description: 接收三方订单
- * @param {*} $params
- * @return {*}
- */
- public static function receiveOrder($params)
- {
- if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
- $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
- ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
- if (!$info || $info->type != self::TYPE_PAYOUT) {
- return false;
- }
- if (!JdPayService::verifyRemitNotify($params)) {
- return false;
- }
- if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- return false;
- }
- self::onSubmitJdPayout($params, $info);
- return true;
- }
- // 判断商户号是否一致
- if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
- $info = self::findOne(['order_no' => $params['orderNo']]);
- if ($info) {
- // 判断金额是不是正确认
- if ($info->amount != $params['amount']) {
- return false;
- }
- // 验证签名
- $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
- if ($params['sign'] != $sign) {
- return false;
- }
- // 代付
- if ($info->type == self::TYPE_PAYOUT) {
- self::onSubmitPayout($params, $info);
- }
- // 代收
- if ($info->type == self::TYPE_PAY) {
- }
- }
- }
- }
- /**
- * @description: 处理代付订单
- * @param {*} $params
- * @return {*}
- */
- public static function onSubmitJdPayout($params, $info)
- {
- if ($info->status != self::STATUS_PROCESS) {
- return;
- }
- $memberId = $info->member_id;
- $amount = JdPayService::amount($params['amount'] ?? $info->amount);
- $data = [];
- $chat_id = $info->member_id;
- $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
- DB::beginTransaction();
- try {
- if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
- $data['status'] = self::STATUS_SUCCESS;
- $res = static::$MODEL::where(['id' => $info->id])->update($data);
- if ($res) {
- $text = "✅ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款地址:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现成功,金额已到账,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
- $data['status'] = self::STATUS_FAIL;
- $res = static::$MODEL::where(['id' => $info->id])->update($data);
- $wallet = WalletService::findOne(['member_id' => $info->member_id]);
- $balance = $wallet->available_balance;
- $available_balance = bcadd($balance, $amount, 10);
- $wallet->available_balance = $available_balance;
- $wallet->save();
- BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
- if ($res) {
- $text = "❌ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款地址:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现失败,金额已返回钱包,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- }
- DB::commit();
- } catch (Exception $e) {
- DB::rollBack();
- Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
- }
- }
- public static function onSubmitPayout($params, $info)
- {
- $memberId = $info->member_id;
- $amount = $params['amount'];
- $data = [];
- $result = [];
- $chat_id = $info->member_id;
- $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
- DB::beginTransaction();
- try {
- if ($params['state'] == 1) {
- $data['status'] = self::STATUS_SUCCESS;
- $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
- if ($res) {
- $text = "✅ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款卡号:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现成功,金额已到账,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- } else {
- $data['status'] = self::STATUS_FAIL;
- $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
- $wallet = WalletService::findOne(['member_id' => $info->member_id]);
- $balance = $wallet->available_balance; // 钱包当前余额
- $available_balance = bcadd($balance, $params['amount'], 10);
- $wallet->available_balance = $available_balance;
- $wallet->save();
- // 记录退款日志
- BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
- if ($res) {
- $text = "❌ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款卡号:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现失败,金额已返回钱包,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- }
- DB::commit();
- } catch (Exception $e) {
- DB::rollBack();
- // 回滚失败,需要记录告警,人工干预
- Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
- }
- }
- /**
- * @description: 查询支付订单
- * @param {*} $id
- * @return {*}
- */
- public static function singlePayOrder($id)
- {
- $msg = [];
- $msg['code'] = self::NOT;
- $info = self::findOne(['id' => $id]);
- if ($info && $info->status == self::STATUS_PROCESS) {
- if (JdPayService::isChannel($info->channel)) {
- $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
- Log::channel('payment')->info('JD支付查询订单', $ret);
- if (($ret['code'] ?? 0) == 200) {
- $item = $ret['data'] ?? [];
- if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
- $info->status = self::STATUS_SUCCESS;
- $info->state = $item['status'];
- $info->callback_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- $info->save();
- $wallet = WalletService::findOne(['member_id' => $info->member_id]);
- $balance = $wallet->available_balance;
- $available_balance = bcadd($balance, $info->amount, 10);
- $wallet->available_balance = $available_balance;
- $wallet->save();
- BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
- self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
- $msg['code'] = self::YES;
- $msg['msg'] = '支付成功';
- } else {
- $msg['msg'] = '支付中';
- }
- } else {
- $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
- }
- return $msg;
- }
- $ret = SanJinService::queryOrder($info->order_no);
- Log::error('三斤支付查询订单:', $ret);
- if ($ret['code'] == 0) {
- $item = [];
- $item['state'] = $ret['data']['state'];
- if ($ret['data']['state'] == 1) {
- $item['status'] = self::STATUS_SUCCESS;
- $info->update($item);
- $wallet = WalletService::findOne(['member_id' => $info->member_id]);
- $balance = $wallet->available_balance;
- $available_balance = bcadd($balance, $info->amount, 10);
- $wallet->available_balance = $available_balance;
- $wallet->save();
- // 记录余额变动日志
- BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
- $msg['code'] = self::YES;
- $msg['msg'] = '支付成功';
- } else {
- $msg['msg'] = '支付中';
- }
- } else {
- $msg['msg'] = '查询失败:' . $ret['message'];
- }
- } else {
- $msg['msg'] = '该状态无法查询';
- }
- return $msg;
- }
- private static function assertJdBalanceEnough($amount, array $context = []): void
- {
- $ret = JdPayService::balance();
- Log::channel('payment')->info('JD余额查询', $context + [
- 'amount' => $amount,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? 0) != 200) {
- $logContext = $context + [
- 'amount' => $amount,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD余额查询失败', $logContext);
- Log::error('JD余额查询失败', $logContext);
- throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
- }
- $balance = $ret['data']['balance'] ?? null;
- if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
- $logContext = $context + [
- 'amount' => $amount,
- 'balance' => $balance,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD商户余额不足', $logContext);
- Log::error('JD商户余额不足', $logContext);
- throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
- }
- }
- private static function notifyUser($chatId, string $text): void
- {
- if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
- return;
- }
- try {
- self::sendMessage($chatId, $text);
- } catch (\Throwable $e) {
- Log::channel('payment_error')->error('支付订单用户通知失败', [
- 'chat_id' => $chatId,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- public static function syncPayOrder()
- {
- $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
- // foreach($list->toArray() as $k => $v){
- // $item= [];
- // if($v['status'] == self::STATUS_SUCCESS){
- // $item['state'] = 1;
- // static::$MODEL::where(['id'=>$v['id']])->update($item);
- // }else{
- // $ret = SanJinService::queryOrder($v['order_no']);
- // var_dump($ret);
- // if($ret['code'] == 0){
- // $item['state'] = $ret['data']['state'];
- // static::$MODEL::where(['id'=>$v['id']])->update($item);
- // }
- // }
- // }
- }
- }
|