PaymentService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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\VideoOrderModel;
  20. use App\Models\VipModel;
  21. use App\Services\Api\MessageService;
  22. use Illuminate\Support\Facades\DB;
  23. use Yansongda\Pay\Pay;
  24. use Yansongda\Pay\Provider\Wechat;
  25. /**
  26. * 支付-服务类
  27. * @author laravel开发员
  28. * @since 2020/11/11
  29. * Class PaymentService
  30. * @package App\Services\Api
  31. */
  32. class PaymentService extends BaseService
  33. {
  34. protected static $instance = null;
  35. private $config = [];
  36. /**
  37. * 构造函数
  38. * @author laravel开发员
  39. * @since 2020/11/11
  40. * PaymentService constructor.
  41. */
  42. public function __construct()
  43. {
  44. $this->model = new PaymentModel();
  45. }
  46. /**
  47. * 静态入口
  48. * @return static|null
  49. */
  50. public static function make()
  51. {
  52. if (!self::$instance) {
  53. self::$instance = (new static());
  54. }
  55. return self::$instance;
  56. }
  57. /**
  58. * 创建支付
  59. * @param string $scene 场景,vip-VIP会员
  60. * @param int $payType
  61. * @param int $isMin 是否是小程序
  62. * @return false|\Yansongda\Pay\Provider\Alipay|Wechat
  63. */
  64. public function createPay($scene, $payType = 10, $payPt= '')
  65. {
  66. $config = ConfigService::make()->getConfigOptionByGroup(6);
  67. if ($payType == 10) {
  68. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  69. $mpAppid = isset($config['wxpay_mp_appid']) ? $config['wxpay_mp_appid'] : '';
  70. $minAppid = isset($config['wxpay_min_appid']) ? $config['wxpay_min_appid'] : '';
  71. $mchid = isset($config['wxpay_mchd']) ? $config['wxpay_mchd'] : '';
  72. $secretV3Key = isset($config['wxpay_key_v3']) ? $config['wxpay_key_v3'] : '';
  73. $secretV2Key = isset($config['wxpay_key_v2']) ? $config['wxpay_key_v2'] : '';
  74. $wxpaySecretCert = isset($config['wxpay_secret_cert']) ? $config['wxpay_secret_cert'] : '';
  75. $wxpayPublicCert = isset($config['wxpay_public_cert']) ? $config['wxpay_public_cert'] : '';
  76. if (empty($appid) || empty($mchid) || empty($secretV3Key)) {
  77. $this->error = 2616;
  78. return false;
  79. }
  80. // 支付参数
  81. $payConfig = config('payment.wechat');
  82. $payConfig['wechat']['default']['mch_id'] = $mchid;
  83. if($payPt == 'min'){
  84. // 小程序支付
  85. $payConfig['wechat']['default']['mini_app_id'] = $minAppid? $minAppid : $appid;
  86. }else if($payPt == 'mp'){
  87. // 公众号
  88. $payConfig['wechat']['default']['mp_app_id'] = $mpAppid? $mpAppid : $appid;
  89. }else{
  90. // APP支付
  91. $payConfig['wechat']['default']['app_id'] = $appid;
  92. }
  93. if($secretV3Key){
  94. $payConfig['wechat']['default']['mch_secret_key'] = $secretV3Key;
  95. }else if($secretV2Key){
  96. $payConfig['wechat']['default']['mch_secret_key_v2'] = $secretV2Key;
  97. }
  98. if ($wxpaySecretCert) {
  99. $payConfig['wechat']['default']['mch_secret_cert'] = $wxpaySecretCert;
  100. }
  101. if ($wxpayPublicCert) {
  102. $payConfig['wechat']['default']['mch_public_cert_path'] = $wxpayPublicCert;
  103. }
  104. $payConfig['wechat']['default']['notify_url'] = url('/api/notify/' . $scene . '/10');
  105. $this->config = $payConfig;
  106. return Pay::wechat($payConfig);
  107. } else if ($payType == 20) {
  108. $appid = isset($config['alipay_appid']) ? $config['alipay_appid'] : '';
  109. $appSecretCert = isset($config['alipay_secret_cert']) ? $config['alipay_secret_cert'] : '';
  110. $appPublicCert = isset($config['alipay_app_public_cert_path']) ? $config['alipay_app_public_cert_path'] : '';
  111. $alipayPublicCert = isset($config['alipay_public_cert_path']) ? $config['alipay_public_cert_path'] : '';
  112. $alipayRootCert = isset($config['alipay_root_cert_path']) ? $config['alipay_root_cert_path'] : '';
  113. if (empty($appid) || empty($appSecretCert)) {
  114. $this->error = 2619;
  115. return false;
  116. }
  117. // 支付参数
  118. $payConfig = config('payment.alipay');
  119. $payConfig['alipay']['default']['app_id'] = $appid;
  120. $payConfig['alipay']['default']['app_secret_cert'] = $appSecretCert;
  121. if ($appPublicCert) {
  122. $payConfig['alipay']['default']['app_public_cert_path'] = $appPublicCert;
  123. }
  124. if ($alipayPublicCert) {
  125. $payConfig['alipay']['default']['alipay_public_cert_path'] = $alipayPublicCert;
  126. }
  127. if ($alipayRootCert) {
  128. $payConfig['alipay']['default']['alipay_root_cert_path'] = $alipayRootCert;
  129. }
  130. $payConfig['alipay']['default']['notify_url'] = url('/api/notify/' . $scene . '/20');
  131. $this->config = $payConfig;
  132. return Pay::alipay($payConfig);
  133. } else if ($payType == 30) {
  134. return true;
  135. }
  136. return false;
  137. }
  138. /**
  139. * 微信小程序支付
  140. * @param $userInfo
  141. * @param $order
  142. * @param string $scene
  143. * @return false|\Yansongda\Supports\Collection
  144. */
  145. public function minPay($userInfo, $order, $scene = 'pay')
  146. {
  147. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  148. $openid = isset($order['openid']) ? $order['openid'] : '';
  149. if ($amount < 0) {
  150. $this->error = 2615;
  151. return false;
  152. }
  153. if(empty($openid)){
  154. $this->error = 2614;
  155. return false;
  156. }
  157. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  158. // 是否调用过支付,是则用新的支付单号
  159. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  160. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  161. }
  162. $body = isset($order['body']) ? $order['body'] : '';
  163. $payData = [
  164. 'out_trade_no' => $outTradeNo,
  165. 'description' => $body ? $body : '订单支付',
  166. 'amount' => [
  167. 'total' => intval($amount * 100),
  168. 'currency' => 'CNY'
  169. ],
  170. 'payer' => [
  171. 'openid' => $openid,
  172. ],
  173. ];
  174. // 创建支付
  175. try {
  176. $pay = $this->createPay($scene, 10, 'min');
  177. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  178. if (empty($pay)) {
  179. $this->error = 2616;
  180. return false;
  181. }
  182. $pay = $pay->mini($payData);
  183. } catch (\Exception $exception) {
  184. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order,'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
  185. $this->error = $exception->getMessage();
  186. return false;
  187. }
  188. if ($pay->package) {
  189. $data = [
  190. 'user_id' => $userInfo['id'],
  191. 'out_trade_no' => $outTradeNo,
  192. 'order_no' => $order['order_no'],
  193. 'params' => json_encode($pay, 256),
  194. 'total_fee' => $amount,
  195. 'pay_type' => 10,
  196. 'create_time' => time(),
  197. 'status' => 2,
  198. 'mark' => 1,
  199. ];
  200. if ($this->model->insertGetId($data)) {
  201. $this->error = 2617;
  202. return $pay;
  203. }
  204. }
  205. $this->error = 2618;
  206. return false;
  207. }
  208. /**
  209. * 微信支付
  210. * @param $userInfo
  211. * @param $order
  212. * @param string $scene
  213. * @return false|\Yansongda\Supports\Collection
  214. */
  215. public function wechatPay($userInfo, $order, $scene = 'pay')
  216. {
  217. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  218. if ($amount < 0) {
  219. $this->error = 2615;
  220. return false;
  221. }
  222. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  223. // 是否调用过支付,是则用新的支付单号
  224. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  225. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  226. }
  227. $body = isset($order['body']) ? $order['body'] : '';
  228. $type = isset($order['type']) ? $order['type'] : 0;
  229. $payData = [
  230. 'out_trade_no' => $outTradeNo,
  231. 'attach' => "order-{$type}",
  232. 'description' => $body ? $body : '订单支付',
  233. 'amount' => [
  234. 'total' => intval($amount * 100),
  235. 'currency' => 'CNY'
  236. ],
  237. ];
  238. // 创建支付
  239. try {
  240. $pay = $this->createPay($scene, 10);
  241. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  242. if (empty($pay)) {
  243. $this->error = 2616;
  244. return false;
  245. }
  246. $pay = $pay->app($payData);
  247. } catch (\Exception $exception) {
  248. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order,'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
  249. $this->error = $exception->getMessage();
  250. return false;
  251. }
  252. if ($pay->prepayid) {
  253. $data = [
  254. 'user_id' => $userInfo['id'],
  255. 'out_trade_no' => $outTradeNo,
  256. 'order_no' => $order['order_no'],
  257. 'params' => json_encode($pay, 256),
  258. 'total_fee' => $amount,
  259. 'pay_type' => 10,
  260. 'create_time' => time(),
  261. 'status' => 2,
  262. 'mark' => 1,
  263. ];
  264. if ($this->model->insertGetId($data)) {
  265. $this->error = 2617;
  266. return $pay;
  267. }
  268. }
  269. $this->error = 2618;
  270. return false;
  271. }
  272. /**
  273. * 支付宝支付
  274. * @param $userInfo
  275. * @param $order
  276. * @return bool
  277. */
  278. public function aliPay($userInfo, $order, $scene = 'deposit')
  279. {
  280. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  281. if ($amount < 0) {
  282. $this->error = 2615;
  283. return false;
  284. }
  285. // 是否调用过支付,是则用新的支付单号
  286. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  287. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  288. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  289. }
  290. $body = isset($order['body']) ? $order['body'] : '';
  291. $payData = [
  292. 'out_trade_no' => $outTradeNo,
  293. 'subject' => $body ? $body : '订单支付',
  294. 'total_amount' => $amount,
  295. ];
  296. // 创建支付
  297. $pay = $this->createPay($scene, 20);
  298. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  299. if (empty($pay)) {
  300. $this->error = 2619;
  301. return false;
  302. }
  303. $pay = $pay->app($payData);
  304. if ($pay->getStatusCode() == 200) {
  305. $data = [
  306. 'user_id' => $userInfo['id'],
  307. 'out_trade_no' => $outTradeNo,
  308. 'order_no' => $order['order_no'],
  309. 'params' => json_encode($pay, 256),
  310. 'total_fee' => $amount,
  311. 'pay_type' => 20,
  312. 'create_time' => time(),
  313. 'status' => 2,
  314. 'mark' => 1,
  315. ];
  316. if ($this->model->insertGetId($data)) {
  317. $this->error = 2620;
  318. return $pay->getBody()->getContents();
  319. }
  320. }
  321. $this->error = 2621;
  322. return false;
  323. }
  324. /**
  325. * 订单支付回调处理
  326. * @param string $scene 场景 deposit-保证金,depositRefund-保证金退款,withdraw-收入提现
  327. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  328. * @param array $data 回调数据
  329. * @return bool
  330. */
  331. public function catchNotify($scene, $payType, $data)
  332. {
  333. $outTradeNo = '';
  334. $payTotal = 0;
  335. $transactionId = '';
  336. $payAt = '';
  337. $notifyData = [];
  338. try {
  339. // 微信支付
  340. if ($payType == 10) {
  341. $resource = isset($data['resource']) ? $data['resource'] : [];
  342. $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
  343. $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
  344. if ($tradeStatus != 'SUCCESS') {
  345. $this->error = 2622;
  346. return false;
  347. }
  348. $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
  349. $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
  350. if (empty($outTradeNo)) {
  351. $this->error = 2623;
  352. return false;
  353. }
  354. $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
  355. $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
  356. $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
  357. $notifyData = $ciphertext;
  358. if ($payTotal <= 0) {
  359. $this->error = 2624;
  360. return false;
  361. }
  362. } // 支付宝支付
  363. else if ($payType == 20) {
  364. // TRADE_SUCCESS
  365. $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
  366. if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
  367. $this->error = 2622;
  368. return false;
  369. }
  370. $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
  371. if (empty($outTradeNo)) {
  372. $this->error = 2623;
  373. return false;
  374. }
  375. $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
  376. $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
  377. $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
  378. $notifyData = $data;
  379. if ($payTotal <= 0) {
  380. $this->error = 2624;
  381. return false;
  382. }
  383. }
  384. // 支付信息
  385. $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
  386. ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
  387. ->first();
  388. $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
  389. $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
  390. $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
  391. $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
  392. $payUserId = isset($paymentInfo['user_id']) ? $paymentInfo['user_id'] : 0;
  393. $payUser = isset($paymentInfo['user']) ? $paymentInfo['user'] : [];
  394. if (empty($paymentInfo) || empty($orderNo) || $payUserId <= 0) {
  395. $this->error = 2625;
  396. return false;
  397. }
  398. // 验证支付状态
  399. if ($status == 1) {
  400. $this->error = 2626;
  401. return false;
  402. }
  403. // 验证支付方式
  404. if ($paymentPayType != $payType) {
  405. $this->error = 2627;
  406. return false;
  407. }
  408. if ($payTotal != $totalFee || $payTotal <= 0) {
  409. $this->error = 2628;
  410. return false;
  411. }
  412. // 删除久远旧记录
  413. $this->model->where(['mark' => 1])->where('create_time', '<=', time() - 60 * 86400)->delete();
  414. // 更新订单数据
  415. DB::beginTransaction();
  416. $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
  417. if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
  418. $this->error = 2632;
  419. DB::rollBack();
  420. return false;
  421. }
  422. /* TODO 订单验证和状态处理 */
  423. // VIP购买
  424. if ($scene == 'vip') {
  425. $orderInfo = OrderModel::with(['vip'])->where(['order_no' => $orderNo, 'mark' => 1])
  426. ->select(['id as order_id', 'user_id', 'goods_id', 'expired_at', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
  427. ->first();
  428. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  429. // 验证订单
  430. if (empty($orderInfo)) {
  431. DB::rollBack();
  432. $this->error = 2629;
  433. return false;
  434. }
  435. // 订单状态
  436. if ($orderStatus != 1) {
  437. DB::rollBack();
  438. $this->error = 2630;
  439. return false;
  440. }
  441. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  442. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  443. $this->error = 2633;
  444. DB::rollBack();
  445. return false;
  446. }
  447. } // 视频单集购买
  448. if ($scene == 'video') {
  449. $orderInfo = VideoOrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  450. ->select(['id as order_id', 'user_id', 'goods_id', 'expired_at', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
  451. ->first();
  452. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  453. // 验证订单
  454. if (empty($orderInfo)) {
  455. DB::rollBack();
  456. $this->error = 2629;
  457. return false;
  458. }
  459. // 订单状态
  460. if ($orderStatus != 1) {
  461. DB::rollBack();
  462. $this->error = 2630;
  463. return false;
  464. }
  465. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  466. if (!VideoOrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  467. $this->error = 2633;
  468. DB::rollBack();
  469. return false;
  470. }
  471. } // VIP退款
  472. else if ($scene == 'refund') {
  473. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  474. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'remark', 'pay_at as pay_time', 'refund_status as status'])
  475. ->first();
  476. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  477. // 验证订单
  478. if (empty($orderInfo)) {
  479. DB::rollBack();
  480. $this->error = 2629;
  481. return false;
  482. }
  483. // 订单状态
  484. if ($orderStatus != 2) {
  485. DB::rollBack();
  486. $this->error = 2639;
  487. return false;
  488. }
  489. // 订单打款状态
  490. if ($orderStatus == 4) {
  491. DB::rollBack();
  492. $this->error = 2630;
  493. return false;
  494. }
  495. $updateData = ['refund_status' => 4, 'update_time' => time()];
  496. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  497. $this->error = 2633;
  498. DB::rollBack();
  499. return false;
  500. }
  501. }
  502. // TODO 场景业务回调处理
  503. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  504. RedisService::set("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data], 7200);
  505. switch ($scene) {
  506. case 'vip': // 购买VIP
  507. $vipInfo = isset($orderInfo['vip']) ? $orderInfo['vip'] : [];
  508. $vipType = isset($vipInfo['type']) ? $vipInfo['type'] : 0;
  509. $expiredAt = isset($orderInfo['expired_at']) ? $orderInfo['expired_at'] : '';
  510. $price = isset($orderInfo['price']) ? $orderInfo['price'] : 0;
  511. $remark = isset($orderInfo['remark']) && $orderInfo['remark'] ? $orderInfo['remark'] : '购买VIP会员';
  512. if (empty($vipInfo) || $expiredAt <= date('Y-m-d H:i:s') || $vipType <= 0) {
  513. DB::rollBack();
  514. $this->error = 'VIP参数错误';
  515. return false;
  516. }
  517. $field = "zg_vip";
  518. if ($vipType == 2) {
  519. $field = "zsb_vip";
  520. } else if ($vipType == 3) {
  521. $field = "video_vip";
  522. }
  523. $updateData = ["is_{$field}" => 1, "{$field}_expired" => $expiredAt, 'update_time' => time()];
  524. RedisService::set("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}_update", ['order' => $orderInfo, 'update' => $updateData, 'notify' => $data], 600);
  525. if (!MemberModel::where(['id' => $orderUserId, 'mark' => 1])->update($updateData)) {
  526. DB::rollBack();
  527. $this->error = 2639;
  528. return false;
  529. }
  530. // 账单记录
  531. $log = [
  532. 'user_id' => $orderUserId,
  533. 'source_order_no' => $orderNo,
  534. 'type' => 1,
  535. 'money' => $price,
  536. 'date' => date('Y-m-d'),
  537. 'create_time' => time(),
  538. 'remark' => $remark,
  539. 'status' => 1,
  540. 'mark' => 1
  541. ];
  542. RedisService::set("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}_log", ['order' => $orderInfo, 'log' => $log, 'notify' => $data], 600);
  543. if (!AccountLogModel::insertGetId($log)) {
  544. $this->error = 2635;
  545. return false;
  546. }
  547. break;
  548. default:
  549. DB::rollBack();
  550. $this->error = 2631;
  551. return false;
  552. }
  553. $this->error = 2638;
  554. DB::commit();
  555. return true;
  556. } catch (\Exception $exception){
  557. $this->error = $exception->getMessage();
  558. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo.'_error', ['notify' => $data,'error' => $exception->getMessage(),'trace'=>$exception->getTrace()], 7200);
  559. return false;
  560. }
  561. }
  562. /**
  563. * 退款请求
  564. * @param $order
  565. * @param string $scene
  566. * @return bool
  567. * @throws \Yansongda\Pay\Exception\ContainerException
  568. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  569. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  570. */
  571. public function refund($order, $scene='vip')
  572. {
  573. $money = isset($order['money'])? $order['money'] : 0;
  574. $payType = isset($order['pay_type'])? $order['pay_type'] : 0;
  575. $orderNo = isset($order['order_no'])? $order['order_no'] : '';
  576. $outTradeNo = isset($order['out_trade_no'])? $order['out_trade_no'] : '';
  577. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : '';
  578. $remark = isset($order['remark']) && $order['remark']? $order['remark'] : '退款';
  579. $pay = PaymentService::make()->createPay($scene, $payType);
  580. if (empty($pay)) {
  581. DB::rollBack();
  582. $this->error = 2171;
  583. return false;
  584. }
  585. // 保证金退款处理
  586. $refundStatus = false;
  587. switch ($payType) {
  588. case 10: // 微信支付
  589. $data = [
  590. 'out_trade_no' => $outTradeNo,
  591. 'out_refund_no' => get_order_num('RF'),
  592. 'transaction_id' => $transactionId,
  593. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  594. 'reason' => $remark,
  595. 'amount' => [
  596. 'refund' => intval($money * 100),
  597. 'total' => intval($money * 100),
  598. 'currency' => 'CNY',
  599. ],
  600. ];
  601. // 请求退款
  602. $pay = $pay->refund($data);
  603. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data,'pay'=>$pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  604. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  605. $refundStatus = true;
  606. } else {
  607. DB::rollBack();
  608. $this->error = 2172;
  609. return false;
  610. }
  611. break;
  612. case 20: // 支付宝
  613. $data = [
  614. 'out_request_no' => $outTradeNo,
  615. 'trade_no' => $transactionId,
  616. 'refund_amount' => $money,
  617. 'query_options' => ['deposit_back_info'],
  618. 'refund_reason' => $remark,
  619. ];
  620. $payResult = $pay->refund($data);
  621. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data,'pay'=>$payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  622. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  623. $refundStatus = true;
  624. } else {
  625. $this->error = 2173;
  626. return false;
  627. }
  628. break;
  629. default:
  630. $this->error = 2179;
  631. return false;
  632. }
  633. $this->error = 2176;
  634. return $refundStatus;
  635. }
  636. }