PaymentOrderService.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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. Log::channel('payment_error')->warning('JD下发接口失败', [
  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. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  515. }
  516. $order->pay_no = $ret['data']['orderNo'] ?? '';
  517. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  518. } else {
  519. $ret = QianBaoService::payout($amount, $order->order_no, $order->bank_name, $order->account, $order->card_no);
  520. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  521. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  522. }
  523. $order->status = self::STATUS_PROCESS;
  524. $order->save();
  525. } catch (Exception $e) {
  526. Log::channel('payment_error')->warning('创建代付订单失败', [
  527. 'order_id' => $orderId,
  528. 'error' => $e->getMessage(),
  529. ]);
  530. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  531. }
  532. return ['code' => 0, 'msg' => 'ok'];
  533. }
  534. /**
  535. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  536. * @param {*} $memberId 会员ID
  537. * @param {*} $amount 代付金额
  538. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  539. * @param {*} $bank_name 银行名称/支付宝
  540. * @param {*} $account 姓名
  541. * @param {*} $card_no 银行卡号/支付宝账号
  542. * @return {*}
  543. */
  544. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  545. {
  546. $default_amount = $amount;
  547. $result = [];
  548. $result['chat_id'] = $memberId;
  549. if ($amount < 100) {
  550. $result['text'] = '提现金额最少100';
  551. return $result;
  552. }
  553. if ($amount > 49999) {
  554. $result['text'] = '提现金额最多49999';
  555. return $result;
  556. }
  557. // 在调用三方支付前开始事务
  558. DB::beginTransaction();
  559. try {
  560. $wallet = WalletService::findOne(['member_id' => $memberId]);
  561. if (!$wallet) {
  562. $result['text'] = '钱包不存在!';
  563. return $result;
  564. }
  565. $balance = $wallet->available_balance;
  566. if (bccomp($balance, $amount, 2) < 0) {
  567. $result['text'] = '您的钱包余额不足!';
  568. return $result;
  569. }
  570. $available_balance = bcsub($balance, $amount, 10);
  571. $data = [];
  572. $data['type'] = self::TYPE_PAYOUT;
  573. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  574. $data['order_no'] = $order_no;
  575. $data['member_id'] = $memberId;
  576. $data['fee'] = $amount * 0.002 + 2;
  577. $amount = number_format($amount, 2, '.', '');
  578. $data['amount'] = $amount;
  579. $data['channel'] = $channel;
  580. $data['bank_name'] = $bank_name;
  581. $data['account'] = $account;
  582. $data['card_no'] = $card_no;
  583. $data['callback_url'] = JdPayService::isChannel($channel) ? JdPayService::getRemitNotifyUrl() : QianBaoService::getNotifyUrl();
  584. $data['status'] = self::STATUS_STAY;
  585. $data['remark'] = '提现费率:0.2%+2';
  586. // 先预扣款(锁定资金)
  587. $wallet->available_balance = $available_balance;
  588. if (!$wallet->save()) {
  589. DB::rollBack();
  590. $result['text'] = '钱包更新失败!';
  591. return $result;
  592. }
  593. // 创建待处理状态的提现记录
  594. $info = static::$MODEL::create($data);
  595. $id = $info->id;
  596. // 记录余额变动日志
  597. BalanceLogService::addLog($memberId, $default_amount * -1, $balance, $available_balance, '三方提现', $id, '钱宝提现费率:0.2%+2');
  598. // 提交事务,确保预扣款成功
  599. DB::commit();
  600. } //
  601. catch (Exception $e) {
  602. // 预扣款失败,回滚事务
  603. DB::rollBack();
  604. $result['text'] = '系统繁忙,请稍后重试!';
  605. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  606. 'member_id' => $memberId,
  607. 'amount' => $amount
  608. ]);
  609. return $result;
  610. }
  611. // 调用三方支付接口(在事务外)
  612. if (JdPayService::isChannel($channel)) {
  613. try {
  614. self::assertJdBalanceEnough($amount, [
  615. 'order_no' => $order_no,
  616. 'member_id' => $memberId,
  617. 'address' => $card_no,
  618. ]);
  619. $ret = JdPayService::remit($amount, $order_no, $card_no);
  620. Log::channel('payment')->info('JD下发接口调用', [
  621. 'order_no' => $order_no,
  622. 'member_id' => $memberId,
  623. 'amount' => $amount,
  624. 'address' => $card_no,
  625. 'response' => $ret,
  626. ]);
  627. $success = (($ret['code'] ?? 0) == 200);
  628. $failureMessage = $ret['message'] ?? 'JD下发失败';
  629. if (!$success) {
  630. Log::channel('payment_error')->warning('JD下发接口失败', [
  631. 'order_no' => $order_no,
  632. 'member_id' => $memberId,
  633. 'amount' => $amount,
  634. 'address' => $card_no,
  635. 'response' => $ret,
  636. ]);
  637. }
  638. } catch (Exception $e) {
  639. $ret = ['message' => $e->getMessage()];
  640. $success = false;
  641. $failureMessage = $e->getMessage();
  642. Log::channel('payment_error')->warning('JD下发接口异常', [
  643. 'order_no' => $order_no,
  644. 'member_id' => $memberId,
  645. 'amount' => $amount,
  646. 'address' => $card_no,
  647. 'error' => $e->getMessage(),
  648. ]);
  649. }
  650. } else {
  651. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  652. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  653. $success = (($ret['code'] ?? 0) == 200);
  654. $failureMessage = $ret['msg'] ?? '代付失败';
  655. }
  656. if ($success) {
  657. // 更新提现记录状态为处理中
  658. DB::beginTransaction();
  659. try {
  660. $info->status = self::STATUS_PROCESS;
  661. if (JdPayService::isChannel($channel)) {
  662. $info->pay_no = $ret['data']['orderNo'] ?? '';
  663. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  664. }
  665. $info->save();
  666. DB::commit();
  667. $text = "✅ 提现申请已提交!\n\n";
  668. $text .= "钱包余额:{$available_balance} RMB\n";
  669. $text .= "提现金额:{$default_amount} RMB\n";
  670. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  671. $result['text'] = $text;
  672. } catch (Exception $e) {
  673. DB::rollBack();
  674. // 状态更新失败,但资金已扣款且三方支付已成功
  675. // 这里可以记录告警,需要人工干预
  676. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  677. 'member_id' => $memberId,
  678. 'order_no' => $order_no
  679. ]);
  680. $result['text'] = '提现申请已提交,系统处理中...';
  681. }
  682. } //
  683. else {
  684. // 三方支付失败,需要回滚之前的预扣款
  685. DB::beginTransaction();
  686. try {
  687. // 恢复钱包余额
  688. $wallet->available_balance = $balance;
  689. $wallet->save();
  690. // 更新提现记录状态为失败
  691. $info->status = self::STATUS_FAIL;
  692. $info->remark = $failureMessage;
  693. $info->save();
  694. // 记录退款日志
  695. BalanceLogService::addLog($memberId, $default_amount, $available_balance, $balance, '三方提现', $id, '提现失败退款');
  696. DB::commit();
  697. $result['text'] = $failureMessage;
  698. } catch (Exception $e) {
  699. DB::rollBack();
  700. // 回滚失败,需要记录告警,人工干预
  701. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  702. 'member_id' => $memberId,
  703. 'order_no' => $order_no,
  704. 'amount' => $amount
  705. ]);
  706. $result['text'] = '提现失败,请联系客服处理退款!';
  707. }
  708. }
  709. return $result;
  710. }
  711. /**
  712. * @description: 接收三方订单
  713. * @param {*} $params
  714. * @return {*}
  715. */
  716. public static function receiveOrder($params)
  717. {
  718. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  719. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  720. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  721. if (!$info || $info->type != self::TYPE_PAYOUT) {
  722. return false;
  723. }
  724. if (!JdPayService::verifyRemitNotify($params)) {
  725. return false;
  726. }
  727. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  728. return false;
  729. }
  730. self::onSubmitJdPayout($params, $info);
  731. return true;
  732. }
  733. // 判断商户号是否一致
  734. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  735. $info = self::findOne(['order_no' => $params['orderNo']]);
  736. if ($info) {
  737. // 判断金额是不是正确认
  738. if ($info->amount != $params['amount']) {
  739. return false;
  740. }
  741. // 验证签名
  742. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  743. if ($params['sign'] != $sign) {
  744. return false;
  745. }
  746. // 代付
  747. if ($info->type == self::TYPE_PAYOUT) {
  748. self::onSubmitPayout($params, $info);
  749. }
  750. // 代收
  751. if ($info->type == self::TYPE_PAY) {
  752. }
  753. }
  754. }
  755. }
  756. /**
  757. * @description: 处理代付订单
  758. * @param {*} $params
  759. * @return {*}
  760. */
  761. public static function onSubmitJdPayout($params, $info)
  762. {
  763. if ($info->status != self::STATUS_PROCESS) {
  764. return;
  765. }
  766. $memberId = $info->member_id;
  767. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  768. $data = [];
  769. $chat_id = $info->member_id;
  770. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  771. DB::beginTransaction();
  772. try {
  773. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  774. $data['status'] = self::STATUS_SUCCESS;
  775. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  776. if ($res) {
  777. $text = "✅ 提现通知 \n";
  778. $text .= "提现平台:{$info->bank_name} \n";
  779. $text .= "收款人:{$info->account} \n";
  780. $text .= "收款地址:{$info->card_no} \n";
  781. $text .= "提现金额:{$info->amount} \n";
  782. $text .= "提现成功,金额已到账,请注意查收!";
  783. self::notifyUser($chat_id, $text);
  784. }
  785. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  786. $data['status'] = self::STATUS_FAIL;
  787. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  788. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  789. $balance = $wallet->available_balance;
  790. $available_balance = bcadd($balance, $amount, 10);
  791. $wallet->available_balance = $available_balance;
  792. $wallet->save();
  793. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  794. if ($res) {
  795. $text = "❌ 提现通知 \n";
  796. $text .= "提现平台:{$info->bank_name} \n";
  797. $text .= "收款人:{$info->account} \n";
  798. $text .= "收款地址:{$info->card_no} \n";
  799. $text .= "提现金额:{$info->amount} \n";
  800. $text .= "提现失败,金额已返回钱包,请注意查收!";
  801. self::notifyUser($chat_id, $text);
  802. }
  803. }
  804. DB::commit();
  805. } catch (Exception $e) {
  806. DB::rollBack();
  807. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  808. }
  809. }
  810. public static function onSubmitPayout($params, $info)
  811. {
  812. $memberId = $info->member_id;
  813. $amount = $params['amount'];
  814. $data = [];
  815. $result = [];
  816. $chat_id = $info->member_id;
  817. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  818. DB::beginTransaction();
  819. try {
  820. if ($params['state'] == 1) {
  821. $data['status'] = self::STATUS_SUCCESS;
  822. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  823. if ($res) {
  824. $text = "✅ 提现通知 \n";
  825. $text .= "提现平台:{$info->bank_name} \n";
  826. $text .= "收款人:{$info->account} \n";
  827. $text .= "收款卡号:{$info->card_no} \n";
  828. $text .= "提现金额:{$info->amount} \n";
  829. $text .= "提现成功,金额已到账,请注意查收!";
  830. self::notifyUser($chat_id, $text);
  831. }
  832. } else {
  833. $data['status'] = self::STATUS_FAIL;
  834. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  835. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  836. $balance = $wallet->available_balance; // 钱包当前余额
  837. $available_balance = bcadd($balance, $params['amount'], 10);
  838. $wallet->available_balance = $available_balance;
  839. $wallet->save();
  840. // 记录退款日志
  841. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  842. if ($res) {
  843. $text = "❌ 提现通知 \n";
  844. $text .= "提现平台:{$info->bank_name} \n";
  845. $text .= "收款人:{$info->account} \n";
  846. $text .= "收款卡号:{$info->card_no} \n";
  847. $text .= "提现金额:{$info->amount} \n";
  848. $text .= "提现失败,金额已返回钱包,请注意查收!";
  849. self::notifyUser($chat_id, $text);
  850. }
  851. }
  852. DB::commit();
  853. } catch (Exception $e) {
  854. DB::rollBack();
  855. // 回滚失败,需要记录告警,人工干预
  856. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  857. }
  858. }
  859. /**
  860. * @description: 查询支付订单
  861. * @param {*} $id
  862. * @return {*}
  863. */
  864. public static function singlePayOrder($id)
  865. {
  866. $msg = [];
  867. $msg['code'] = self::NOT;
  868. $info = self::findOne(['id' => $id]);
  869. if ($info && $info->status == self::STATUS_PROCESS) {
  870. if (JdPayService::isChannel($info->channel)) {
  871. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  872. Log::channel('payment')->info('JD支付查询订单', $ret);
  873. if (($ret['code'] ?? 0) == 200) {
  874. $item = $ret['data'] ?? [];
  875. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  876. $info->status = self::STATUS_SUCCESS;
  877. $info->state = $item['status'];
  878. $info->callback_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  879. $info->save();
  880. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  881. $balance = $wallet->available_balance;
  882. $available_balance = bcadd($balance, $info->amount, 10);
  883. $wallet->available_balance = $available_balance;
  884. $wallet->save();
  885. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  886. self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
  887. $msg['code'] = self::YES;
  888. $msg['msg'] = '支付成功';
  889. } else {
  890. $msg['msg'] = '支付中';
  891. }
  892. } else {
  893. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  894. }
  895. return $msg;
  896. }
  897. $ret = SanJinService::queryOrder($info->order_no);
  898. Log::error('三斤支付查询订单:', $ret);
  899. if ($ret['code'] == 0) {
  900. $item = [];
  901. $item['state'] = $ret['data']['state'];
  902. if ($ret['data']['state'] == 1) {
  903. $item['status'] = self::STATUS_SUCCESS;
  904. $info->update($item);
  905. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  906. $balance = $wallet->available_balance;
  907. $available_balance = bcadd($balance, $info->amount, 10);
  908. $wallet->available_balance = $available_balance;
  909. $wallet->save();
  910. // 记录余额变动日志
  911. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  912. $msg['code'] = self::YES;
  913. $msg['msg'] = '支付成功';
  914. } else {
  915. $msg['msg'] = '支付中';
  916. }
  917. } else {
  918. $msg['msg'] = '查询失败:' . $ret['message'];
  919. }
  920. } else {
  921. $msg['msg'] = '该状态无法查询';
  922. }
  923. return $msg;
  924. }
  925. private static function assertJdBalanceEnough($amount, array $context = []): void
  926. {
  927. $ret = JdPayService::balance();
  928. Log::channel('payment')->info('JD余额查询', $context + [
  929. 'amount' => $amount,
  930. 'response' => $ret,
  931. ]);
  932. if (($ret['code'] ?? 0) != 200) {
  933. Log::channel('payment_error')->warning('JD余额查询失败', $context + [
  934. 'amount' => $amount,
  935. 'response' => $ret,
  936. ]);
  937. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  938. }
  939. $balance = $ret['data']['balance'] ?? null;
  940. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  941. Log::channel('payment_error')->warning('JD商户余额不足', $context + [
  942. 'amount' => $amount,
  943. 'balance' => $balance,
  944. 'response' => $ret,
  945. ]);
  946. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  947. }
  948. }
  949. private static function notifyUser($chatId, string $text): void
  950. {
  951. if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
  952. return;
  953. }
  954. try {
  955. self::sendMessage($chatId, $text);
  956. } catch (\Throwable $e) {
  957. Log::channel('payment_error')->warning('支付订单用户通知失败', [
  958. 'chat_id' => $chatId,
  959. 'error' => $e->getMessage(),
  960. ]);
  961. }
  962. }
  963. public static function syncPayOrder()
  964. {
  965. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  966. // foreach($list->toArray() as $k => $v){
  967. // $item= [];
  968. // if($v['status'] == self::STATUS_SUCCESS){
  969. // $item['state'] = 1;
  970. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  971. // }else{
  972. // $ret = SanJinService::queryOrder($v['order_no']);
  973. // var_dump($ret);
  974. // if($ret['code'] == 0){
  975. // $item['state'] = $ret['data']['state'];
  976. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  977. // }
  978. // }
  979. // }
  980. }
  981. }