PaymentService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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. $accountId = 0;
  350. try {
  351. // 微信支付
  352. if ($payType == 10) {
  353. $resource = isset($data['resource']) ? $data['resource'] : [];
  354. $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
  355. $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
  356. if ($tradeStatus != 'SUCCESS') {
  357. $this->error = 2622;
  358. return false;
  359. }
  360. $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
  361. $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
  362. if (empty($outTradeNo)) {
  363. $this->error = 2623;
  364. return false;
  365. }
  366. $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
  367. $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
  368. $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
  369. $notifyData = $ciphertext;
  370. if ($payTotal <= 0) {
  371. $this->error = 2624;
  372. return false;
  373. }
  374. } // 支付宝支付
  375. else if ($payType == 20) {
  376. // TRADE_SUCCESS
  377. $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
  378. if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
  379. $this->error = 2622;
  380. return false;
  381. }
  382. $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
  383. if (empty($outTradeNo)) {
  384. $this->error = 2623;
  385. return false;
  386. }
  387. $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
  388. $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
  389. $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
  390. $notifyData = $data;
  391. if ($payTotal <= 0) {
  392. $this->error = 2624;
  393. return false;
  394. }
  395. }
  396. // 支付信息
  397. $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
  398. ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
  399. ->first();
  400. $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
  401. $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
  402. $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
  403. $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
  404. $payUserId = isset($paymentInfo['user_id']) ? $paymentInfo['user_id'] : 0;
  405. if (empty($paymentInfo) || empty($orderNo) || $payUserId <= 0) {
  406. $this->error = 2625;
  407. return false;
  408. }
  409. // 验证支付状态
  410. if ($status == 1) {
  411. $this->error = 2626;
  412. return false;
  413. }
  414. // 验证支付方式
  415. if ($paymentPayType != $payType) {
  416. $this->error = 2627;
  417. return false;
  418. }
  419. if ($payTotal != $totalFee || $payTotal <= 0) {
  420. $this->error = 2628;
  421. return false;
  422. }
  423. // 删除久远旧记录
  424. $this->model->where(['mark' => 1])->where('create_time', '<=', time() - 60 * 86400)->delete();
  425. // 更新订单数据
  426. DB::beginTransaction();
  427. $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
  428. if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
  429. $this->error = 2632;
  430. DB::rollBack();
  431. return false;
  432. }
  433. /* TODO 订单验证和状态处理 */
  434. $orderInfo = [];
  435. // 商城订单支付
  436. if ($scene == 'store') {
  437. $orderInfo = OrderModel::with(['user','orderGoods'])->where(['order_no' => $orderNo, 'mark' => 1])
  438. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
  439. ->first();
  440. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  441. // 验证订单
  442. if (empty($orderInfo)) {
  443. DB::rollBack();
  444. $this->error = 2629;
  445. return false;
  446. }
  447. // 订单状态
  448. if ($orderStatus != 1) {
  449. DB::rollBack();
  450. $this->error = 2630;
  451. return false;
  452. }
  453. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  454. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  455. $this->error = 2633;
  456. DB::rollBack();
  457. return false;
  458. }
  459. }
  460. // 退款
  461. else if ($scene == 'refund') {
  462. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  463. ->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'])
  464. ->first();
  465. $refundRemark = isset($orderInfo['refund_remark']) ? $orderInfo['refund_remark'] : 'refund_remark';
  466. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  467. // 验证订单
  468. if (empty($orderInfo)) {
  469. DB::rollBack();
  470. $this->error = 2629;
  471. return false;
  472. }
  473. // 订单状态
  474. if ($orderStatus != 2) {
  475. DB::rollBack();
  476. $this->error = 2639;
  477. return false;
  478. }
  479. // 订单打款状态
  480. if ($orderStatus == 1) {
  481. DB::rollBack();
  482. $this->error = 2630;
  483. return false;
  484. }
  485. $updateData = ['refund_status' => 1, 'refund_remark' => $refundRemark ? $refundRemark . ' 已退款成功' : '已退款成功', 'update_time' => time()];
  486. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  487. $this->error = 2633;
  488. DB::rollBack();
  489. return false;
  490. }
  491. }
  492. // TODO 场景业务回调处理
  493. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  494. $this->saveLog("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data]);
  495. switch ($scene) {
  496. case 'store': //
  497. $userInfo = isset($orderInfo['user'])?$orderInfo['user']:[];
  498. $orderTotal = isset($orderInfo['pay_money'])?$orderInfo['pay_money']:0;
  499. $orderGoods = isset($orderInfo['orderGoods'])?$orderInfo['orderGoods']:[];
  500. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  501. $goodsName = isset($orderGoods[0]['goods_name'])?$orderGoods[0]['goods_name']:'';
  502. $data = [
  503. 'user_id'=>$orderUserId,
  504. 'source_order_no'=>$orderNo,
  505. 'type'=> 1,
  506. 'money'=> -$payTotal,
  507. 'after_money'=>$balance,
  508. 'date'=>date('Y-m-d'),
  509. 'create_time'=>time(),
  510. 'remark'=> '商品-'.$goodsName,
  511. 'status'=>1,
  512. 'mark'=>1
  513. ];
  514. if(!AccountLogModel::insertGetId($data)){
  515. Db::rollBack();
  516. $this->error = '付款处理失败';
  517. }
  518. // 统计总消费
  519. $accountId = AccountStatisticsModel::where(['user_id'=>$orderUserId])->orderBy('id','desc')->value('id');
  520. $updateData = [
  521. 'expend'=>DB::raw("expend + {$payTotal}"),
  522. 'updated_at'=>date('Y-m-d H:i:s')
  523. ];
  524. if($accountId){
  525. if(!AccountStatisticsModel::where(['id'=>$accountId])->update($updateData)){
  526. Db::rollBack();
  527. $this->error = '统计处理失败';
  528. }
  529. }else{
  530. $updateData['expend'] = $payTotal;
  531. $updateData['user_id'] = $orderUserId;
  532. $updateData['created_at'] = date('Y-m-d H:i:s');
  533. if(!$accountId = AccountStatisticsModel::insertGetId($updateData)){
  534. Db::rollBack();
  535. $this->error = '统计处理失败';
  536. }
  537. }
  538. break;
  539. default:
  540. break;
  541. }
  542. $this->error = '回调处理成功';
  543. DB::commit();
  544. return true;
  545. } catch (\Exception $exception) {
  546. $this->error = $exception->getMessage();
  547. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['account_id'=>$accountId,'notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
  548. return false;
  549. }
  550. }
  551. /**
  552. * 日志
  553. * @param $key
  554. * @param $data
  555. */
  556. public function saveLog($key, $data)
  557. {
  558. if(env('APP_DEBUG')){
  559. RedisService::set($key,$data,7200);
  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 = 'store')
  572. {
  573. $money = isset($order['money']) ? $order['money'] : 0;
  574. $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
  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 = '创建退款支付失败';
  583. return false;
  584. }
  585. // 保证金退款处理
  586. $refundStatus = false;
  587. switch ($payType) {
  588. case 10: // 微信支付
  589. $data = [
  590. 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
  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->errorData = $data;
  609. $this->error = '微信退款处理失败:'.$pay->message;
  610. return false;
  611. }
  612. break;
  613. case 20: // 支付宝
  614. $data = [
  615. 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
  616. 'trade_no' => $transactionId,
  617. 'refund_amount' => $money,
  618. 'query_options' => ['deposit_back_info'],
  619. 'refund_reason' => $remark,
  620. ];
  621. $payResult = $pay->refund($data);
  622. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  623. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  624. $refundStatus = true;
  625. } else {
  626. $this->errorData = $data;
  627. $this->error = '支付宝退款处理失败:'.$payResult->code;
  628. return false;
  629. }
  630. break;
  631. default:
  632. $this->error = '退款支付类型错误';
  633. return false;
  634. }
  635. $this->error = '退款处理成功';
  636. return $refundStatus;
  637. }
  638. /**
  639. * 分账
  640. * @param $openid
  641. * @param $order
  642. * @param string $scene
  643. * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
  644. * @throws \Yansongda\Pay\Exception\ContainerException
  645. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  646. */
  647. public function profitsharing($openid, $order ,$scene='sharing')
  648. {
  649. $data = [
  650. 'type' => 'PERSONAL_OPENID',
  651. 'account' => $openid,
  652. 'relation_type' => 'SERVICE_PROVIDER'
  653. ];
  654. $pay = PaymentService::make()->createPay($scene, 10);
  655. $plugin = $pay->mergeCommonPlugins([
  656. AddReceiverPlugin::class
  657. ], $data);
  658. // 添加分账插件配置
  659. $pay->pay($plugin, $data);
  660. // 分账数据
  661. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : ''; // 支付交易单号
  662. $profitsharingOrderNo = isset($order['out_order_no'])? $order['out_order_no'] : ''; // 分账单号,非支付单号
  663. $body = isset($order['body'])? $order['body'] : ''; // 分账备注描述
  664. $amount = isset($order['amount'])? $order['amount'] : ''; // 分账金额
  665. $unsplit = isset($order['unsplit'])? $order['unsplit'] : true; // 是否限制只分账一次
  666. $postData = [
  667. 'transaction_id' => $transactionId,
  668. 'out_order_no' => $profitsharingOrderNo,
  669. 'receivers' => [
  670. [
  671. 'type' => 'PERSONAL_OPENID',
  672. 'account' => $openid,
  673. 'amount' => intval($amount*100), // 分账金额,单位:分
  674. 'description' => $body, //分账描述
  675. ],
  676. ],
  677. 'unfreeze_unsplit' => $unsplit,
  678. ];
  679. // 创建分账数据
  680. $createPlugin = $pay->mergeCommonPlugins([
  681. CreatePlugin::class
  682. ], $postData);
  683. // 发起分账
  684. $result = $pay->pay($createPlugin, $postData);
  685. return $result;
  686. }
  687. }