PaymentService.php 30 KB

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