PaymentService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services;
  12. use App\Models\AccountLogModel;
  13. use App\Models\BalanceLogModel;
  14. use App\Models\DepositModel;
  15. use App\Models\MemberModel;
  16. use App\Models\MessageModel;
  17. use App\Models\OrderModel;
  18. use App\Models\PaymentModel;
  19. use App\Models\VipModel;
  20. use App\Services\Api\MessageService;
  21. use Illuminate\Support\Facades\DB;
  22. use Yansongda\Pay\Pay;
  23. use Yansongda\Pay\Provider\Wechat;
  24. /**
  25. * 支付-服务类
  26. * @author laravel开发员
  27. * @since 2020/11/11
  28. * Class PaymentService
  29. * @package App\Services\Api
  30. */
  31. class PaymentService extends BaseService
  32. {
  33. protected static $instance = null;
  34. private $config = [];
  35. /**
  36. * 构造函数
  37. * @author laravel开发员
  38. * @since 2020/11/11
  39. * PaymentService constructor.
  40. */
  41. public function __construct()
  42. {
  43. $this->model = new PaymentModel();
  44. }
  45. /**
  46. * 静态入口
  47. * @return static|null
  48. */
  49. public static function make()
  50. {
  51. if (!self::$instance) {
  52. self::$instance = (new static());
  53. }
  54. return self::$instance;
  55. }
  56. /**
  57. * 创建支付
  58. * @param string $scene 场景,deposit-保证金,depositRefund-保证金退款,withdraw-提现
  59. * @param int $payType
  60. * @return false|\Yansongda\Pay\Provider\Alipay|Wechat
  61. */
  62. public function createPay($scene, $payType = 10)
  63. {
  64. $config = ConfigService::make()->getConfigOptionByGroup(6);
  65. if ($payType == 10) {
  66. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  67. $mchid = isset($config['wxpay_mchd']) ? $config['wxpay_mchd'] : '';
  68. $secretV3Key = isset($config['wxpay_key_v3']) ? $config['wxpay_key_v3'] : '';
  69. $wxpaySecretCert = isset($config['wxpay_secret_cert']) ? $config['wxpay_secret_cert'] : '';
  70. $wxpayPublicCert = isset($config['wxpay_public_cert']) ? $config['wxpay_public_cert'] : '';
  71. if (empty($appid) || empty($mchid) || empty($secretV3Key)) {
  72. $this->error = 2616;
  73. return false;
  74. }
  75. // 支付参数
  76. $payConfig = config('payment.wechat');
  77. $payConfig['wechat']['default']['mch_id'] = $mchid;
  78. $payConfig['wechat']['default']['app_id'] = $appid;
  79. $payConfig['wechat']['default']['mch_secret_key'] = $secretV3Key;
  80. if ($wxpaySecretCert) {
  81. $payConfig['wechat']['default']['mch_secret_cert'] = $wxpaySecretCert;
  82. }
  83. if ($wxpayPublicCert) {
  84. $payConfig['wechat']['default']['mch_public_cert_path'] = $wxpayPublicCert;
  85. }
  86. $payConfig['wechat']['default']['notify_url'] = url('/api/notify/' . $scene . '/10');
  87. $this->config = $payConfig;
  88. return Pay::wechat($payConfig);
  89. } else if ($payType == 20) {
  90. $appid = isset($config['alipay_appid']) ? $config['alipay_appid'] : '';
  91. $appSecretCert = isset($config['alipay_secret_cert']) ? $config['alipay_secret_cert'] : '';
  92. $appPublicCert = isset($config['alipay_app_public_cert_path']) ? $config['alipay_app_public_cert_path'] : '';
  93. $alipayPublicCert = isset($config['alipay_public_cert_path']) ? $config['alipay_public_cert_path'] : '';
  94. $alipayRootCert = isset($config['alipay_root_cert_path']) ? $config['alipay_root_cert_path'] : '';
  95. if (empty($appid) || empty($appSecretCert)) {
  96. $this->error = 2619;
  97. return false;
  98. }
  99. // 支付参数
  100. $payConfig = config('payment.alipay');
  101. $payConfig['alipay']['default']['app_id'] = $appid;
  102. $payConfig['alipay']['default']['app_secret_cert'] = $appSecretCert;
  103. if ($appPublicCert) {
  104. $payConfig['alipay']['default']['app_public_cert_path'] = $appPublicCert;
  105. }
  106. if ($alipayPublicCert) {
  107. $payConfig['alipay']['default']['alipay_public_cert_path'] = $alipayPublicCert;
  108. }
  109. if ($alipayRootCert) {
  110. $payConfig['alipay']['default']['alipay_root_cert_path'] = $alipayRootCert;
  111. }
  112. $payConfig['alipay']['default']['notify_url'] = url('/api/notify/' . $scene . '/20');
  113. $this->config = $payConfig;
  114. return Pay::alipay($payConfig);
  115. } else if ($payType == 30) {
  116. return true;
  117. }
  118. return false;
  119. }
  120. /**
  121. * 微信支付
  122. * @param $userInfo
  123. * @param $order
  124. * @param string $scene
  125. * @return false|\Yansongda\Supports\Collection
  126. */
  127. public function wechatPay($userInfo, $order, $scene = 'pay')
  128. {
  129. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  130. if ($amount < 0) {
  131. $this->error = 2615;
  132. return false;
  133. }
  134. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  135. // 是否调用过支付,是则用新的支付单号
  136. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  137. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  138. }
  139. $body = isset($order['body']) ? $order['body'] : '';
  140. $type = isset($order['type']) ? $order['type'] : 0;
  141. $payData = [
  142. 'out_trade_no' => $outTradeNo,
  143. 'attach' => "order-{$type}",
  144. 'description' => $body ? $body : '订单支付',
  145. 'amount' => [
  146. 'total' => intval($amount * 100),
  147. 'currency' => 'CNY'
  148. ],
  149. ];
  150. // 创建支付
  151. try {
  152. $pay = $this->createPay($scene, 10);
  153. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  154. if (empty($pay)) {
  155. $this->error = 2616;
  156. return false;
  157. }
  158. $pay = $pay->app($payData);
  159. } catch (\Exception $exception) {
  160. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order,'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
  161. $this->error = $exception->getMessage();
  162. return false;
  163. }
  164. if ($pay->prepayid) {
  165. $data = [
  166. 'user_id' => $userInfo['id'],
  167. 'out_trade_no' => $outTradeNo,
  168. 'order_no' => $order['order_no'],
  169. 'params' => json_encode($pay, 256),
  170. 'total_fee' => $amount,
  171. 'pay_type' => 10,
  172. 'create_time' => time(),
  173. 'status' => 2,
  174. 'mark' => 1,
  175. ];
  176. if ($this->model->insertGetId($data)) {
  177. $this->error = 2617;
  178. return $pay;
  179. }
  180. }
  181. $this->error = 2618;
  182. return false;
  183. }
  184. /**
  185. * 支付宝支付
  186. * @param $userInfo
  187. * @param $order
  188. * @return bool
  189. */
  190. public function aliPay($userInfo, $order, $scene = 'deposit')
  191. {
  192. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  193. if ($amount < 0) {
  194. $this->error = 2615;
  195. return false;
  196. }
  197. // 是否调用过支付,是则用新的支付单号
  198. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  199. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  200. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  201. }
  202. $body = isset($order['body']) ? $order['body'] : '';
  203. $payData = [
  204. 'out_trade_no' => $outTradeNo,
  205. 'subject' => $body ? $body : '订单支付',
  206. 'total_amount' => $amount,
  207. ];
  208. // 创建支付
  209. $pay = $this->createPay($scene, 20);
  210. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  211. if (empty($pay)) {
  212. $this->error = 2619;
  213. return false;
  214. }
  215. $pay = $pay->app($payData);
  216. if ($pay->getStatusCode() == 200) {
  217. $data = [
  218. 'user_id' => $userInfo['id'],
  219. 'out_trade_no' => $outTradeNo,
  220. 'order_no' => $order['order_no'],
  221. 'params' => json_encode($pay, 256),
  222. 'total_fee' => $amount,
  223. 'pay_type' => 20,
  224. 'create_time' => time(),
  225. 'status' => 2,
  226. 'mark' => 1,
  227. ];
  228. if ($this->model->insertGetId($data)) {
  229. $this->error = 2620;
  230. return $pay->getBody()->getContents();
  231. }
  232. }
  233. $this->error = 2621;
  234. return false;
  235. }
  236. /**
  237. * 订单支付回调处理
  238. * @param string $scene 场景 deposit-保证金,depositRefund-保证金退款,withdraw-收入提现
  239. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  240. * @param array $data 回调数据
  241. * @return bool
  242. */
  243. public function catchNotify($scene, $payType, $data)
  244. {
  245. $outTradeNo = '';
  246. $payTotal = 0;
  247. $transactionId = '';
  248. $payAt = '';
  249. $notifyData = [];
  250. // 微信支付
  251. if ($payType == 10) {
  252. $resource = isset($data['resource']) ? $data['resource'] : [];
  253. $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
  254. $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
  255. if ($tradeStatus != 'SUCCESS') {
  256. $this->error = 2622;
  257. return false;
  258. }
  259. $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
  260. $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
  261. if (empty($outTradeNo)) {
  262. $this->error = 2623;
  263. return false;
  264. }
  265. $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
  266. $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
  267. $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
  268. $notifyData = $ciphertext;
  269. if ($payTotal <= 0) {
  270. $this->error = 2624;
  271. return false;
  272. }
  273. } // 支付宝支付
  274. else if ($payType == 20) {
  275. // TRADE_SUCCESS
  276. $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
  277. if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
  278. $this->error = 2622;
  279. return false;
  280. }
  281. $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
  282. if (empty($outTradeNo)) {
  283. $this->error = 2623;
  284. return false;
  285. }
  286. $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
  287. $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
  288. $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
  289. $notifyData = $data;
  290. if ($payTotal <= 0) {
  291. $this->error = 2624;
  292. return false;
  293. }
  294. }
  295. // 支付信息
  296. $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
  297. ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
  298. ->first();
  299. $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
  300. $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
  301. $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
  302. $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
  303. $payUserId = isset($paymentInfo['user_id'])? $paymentInfo['user_id'] : 0;
  304. $payUser = isset($paymentInfo['user'])? $paymentInfo['user'] : [];
  305. $username = isset($payUser['mobile'])? $payUser['mobile'] : $payUserId;
  306. if (empty($paymentInfo) || empty($orderNo) || $payUserId<=0) {
  307. $this->error = 2625;
  308. return false;
  309. }
  310. // 验证支付状态
  311. if ($status == 1) {
  312. $this->error = 2626;
  313. return false;
  314. }
  315. // 验证支付方式
  316. if ($paymentPayType != $payType) {
  317. $this->error = 2627;
  318. return false;
  319. }
  320. if ($payTotal != $totalFee || $payTotal <= 0) {
  321. $this->error = 2628;
  322. return false;
  323. }
  324. // 删除久远旧记录
  325. $this->model->where(['mark' => 1])->where('create_time','<=', time() - 60 * 86400)->delete();
  326. // 更新订单数据
  327. DB::beginTransaction();
  328. $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
  329. if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
  330. $this->error = 2632;
  331. DB::rollBack();
  332. return false;
  333. }
  334. /* TODO 订单验证和状态处理 */
  335. // 充值订单
  336. if ($scene == 'vip') {
  337. $orderInfo = OrderModel::with(['vip'])->where(['order_no' => $orderNo, 'mark' => 1])
  338. ->select(['id as order_id', 'user_id','goods_id','expired_at', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'status'])
  339. ->first();
  340. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  341. // 验证订单
  342. if (empty($orderInfo)) {
  343. DB::rollBack();
  344. $this->error = 2629;
  345. return false;
  346. }
  347. // 订单状态
  348. if ($orderStatus != 1) {
  349. DB::rollBack();
  350. $this->error = 2630;
  351. return false;
  352. }
  353. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  354. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  355. $this->error = 2633;
  356. DB::rollBack();
  357. return false;
  358. }
  359. } // 保证金退款
  360. else if ($scene == 'refund') {
  361. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  362. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'refund_status as status'])
  363. ->first();
  364. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  365. // 验证订单
  366. if (empty($orderInfo)) {
  367. DB::rollBack();
  368. $this->error = 2629;
  369. return false;
  370. }
  371. // 订单状态
  372. if ($orderStatus != 2) {
  373. DB::rollBack();
  374. $this->error = 2639;
  375. return false;
  376. }
  377. // 订单打款状态
  378. if ($orderStatus == 4) {
  379. DB::rollBack();
  380. $this->error = 2630;
  381. return false;
  382. }
  383. $updateData = ['refund_status' => 4, 'update_time' => time()];
  384. if (!OrderModel::where(['order_no' => $orderNo,'mark' => 1])->update($updateData)) {
  385. $this->error = 2633;
  386. DB::rollBack();
  387. return false;
  388. }
  389. }
  390. // TODO 场景业务回调处理
  391. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  392. RedisService::set("caches:notify:{$orderNo}_{$scene}:data", ['order' => $orderInfo, 'notify' => $data], 7200);
  393. switch ($scene) {
  394. case 'vip': // 购买VIP
  395. $vipInfo = isset($orderInfo['vip'])? $orderInfo['vip'] : [];
  396. $vipType = isset($vipInfo['type'])? $vipInfo['type'] : 0;
  397. $expiredAt = isset($orderInfo['expired_at'])? $vipInfo['expired_at'] : '';
  398. if(empty($vipInfo) || $expiredAt <= date('Y-m-d H:i:s') || $vipType<=0){
  399. DB::rollBack();
  400. $this->error = 'VIP参数错误';
  401. }
  402. $field = "zg_vip";
  403. if($vipType == 2){
  404. $field = "zsb_vip";
  405. }else if($vipType==3){
  406. $field = "video_vip";
  407. }
  408. $updateData = ["is_{$field}"=> 1,"{$field}_expired"=> $expiredAt,'update_time'=>time()];
  409. if(!MemberModel::where(['id'=> $orderUserId,'mark'=>1])->update($updateData)){
  410. DB::rollBack();
  411. $this->error = 2639;
  412. return false;
  413. }
  414. default:
  415. DB::rollBack();
  416. $this->error = 2631;
  417. return false;
  418. }
  419. $this->error = 2638;
  420. DB::commit();
  421. return true;
  422. }
  423. /**
  424. * 退款请求
  425. * @param $order
  426. * @param string $scene
  427. * @return bool
  428. * @throws \Yansongda\Pay\Exception\ContainerException
  429. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  430. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  431. */
  432. public function refund($order, $scene='vip')
  433. {
  434. $money = isset($order['money'])? $order['money'] : 0;
  435. $payType = isset($order['pay_type'])? $order['pay_type'] : 0;
  436. $orderNo = isset($order['order_no'])? $order['order_no'] : '';
  437. $outTradeNo = isset($order['out_trade_no'])? $order['out_trade_no'] : '';
  438. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : '';
  439. $remark = isset($order['remark']) && $order['remark']? $order['remark'] : '退款';
  440. $pay = PaymentService::make()->createPay($scene, $payType);
  441. if (empty($pay)) {
  442. DB::rollBack();
  443. $this->error = 2171;
  444. return false;
  445. }
  446. // 保证金退款处理
  447. $refundStatus = false;
  448. switch ($payType) {
  449. case 10: // 微信支付
  450. $data = [
  451. 'out_trade_no' => $outTradeNo,
  452. 'out_refund_no' => get_order_num('RF'),
  453. 'transaction_id' => $transactionId,
  454. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  455. 'reason' => $remark,
  456. 'amount' => [
  457. 'refund' => intval($money * 100),
  458. 'total' => intval($money * 100),
  459. 'currency' => 'CNY',
  460. ],
  461. ];
  462. // 请求退款
  463. $pay = $pay->refund($data);
  464. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data,'pay'=>$pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  465. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  466. $refundStatus = true;
  467. } else {
  468. DB::rollBack();
  469. $this->error = 2172;
  470. return false;
  471. }
  472. break;
  473. case 20: // 支付宝
  474. $data = [
  475. 'out_request_no' => $outTradeNo,
  476. 'trade_no' => $transactionId,
  477. 'refund_amount' => $money,
  478. 'query_options' => ['deposit_back_info'],
  479. 'refund_reason' => $remark,
  480. ];
  481. $payResult = $pay->refund($data);
  482. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data,'pay'=>$payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  483. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  484. $refundStatus = true;
  485. } else {
  486. $this->error = 2173;
  487. return false;
  488. }
  489. break;
  490. default:
  491. $this->error = 2179;
  492. return false;
  493. }
  494. $this->error = 2176;
  495. return $refundStatus;
  496. }
  497. }