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\OrderModel;
  14. use App\Models\PaymentModel;
  15. use Illuminate\Support\Facades\DB;
  16. use Yansongda\Pay\Pay;
  17. use Yansongda\Pay\Plugin\Wechat\Fund\Profitsharing\AddReceiverPlugin;
  18. use Yansongda\Pay\Plugin\Wechat\Fund\Profitsharing\CreatePlugin;
  19. use Yansongda\Pay\Provider\Wechat;
  20. /**
  21. * 支付-服务类
  22. * @author laravel开发员
  23. * @since 2020/11/11
  24. * Class PaymentService
  25. * @package App\Services\Api
  26. */
  27. class PaymentService extends BaseService
  28. {
  29. protected static $instance = null;
  30. private $config = [];
  31. /**
  32. * 构造函数
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. * PaymentService constructor.
  36. */
  37. public function __construct()
  38. {
  39. $this->model = new PaymentModel();
  40. }
  41. /**
  42. * 静态入口
  43. * @return static|null
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = (new static());
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * 创建支付
  54. * @param string $scene 场景,store-购物消费,pay-生活充值,refund-退款
  55. * @param int $payType
  56. * @param int $isMin 是否是小程序
  57. * @return false|\Yansongda\Pay\Provider\Alipay|Wechat
  58. */
  59. public function createPay($scene, $payType = 10, $payPt = '')
  60. {
  61. $config = ConfigService::make()->getConfigOptionByGroup(6);
  62. try {
  63. if ($payType == 10) {
  64. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  65. $mpAppid = isset($config['wxpay_mp_appid']) ? $config['wxpay_mp_appid'] : '';
  66. $minAppid = isset($config['wxpay_min_appid']) ? $config['wxpay_min_appid'] : '';
  67. $mchid = isset($config['wxpay_mchd']) ? $config['wxpay_mchd'] : '';
  68. $secretV3Key = isset($config['wxpay_key_v3']) ? $config['wxpay_key_v3'] : '';
  69. $secretV2Key = isset($config['wxpay_key_v2']) ? $config['wxpay_key_v2'] : '';
  70. $publicKeyId = isset($config['public_key_id']) ? $config['public_key_id'] : '';
  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. $payConfig['wechat']['default']['wechat_public_cert_path']["PUB_KEY_ID_{$publicKeyId}"] = base_path().'/resources/certs/wechat/pub_key.pem';
  81. if ($payPt == 'min') {
  82. // 小程序支付
  83. $payConfig['wechat']['default']['mini_app_id'] = $minAppid ? $minAppid : $appid;
  84. } else if ($payPt == 'mp' || $scene == 'sharing') {
  85. // 公众号
  86. $payConfig['wechat']['default']['mp_app_id'] = $mpAppid ? $mpAppid : $appid;
  87. } else {
  88. // APP支付
  89. $payConfig['wechat']['default']['app_id'] = $appid;
  90. }
  91. if ($secretV3Key) {
  92. $payConfig['wechat']['default']['mch_secret_key'] = $secretV3Key;
  93. } else if ($secretV2Key) {
  94. $payConfig['wechat']['default']['mch_secret_key_v2'] = $secretV2Key;
  95. }
  96. if ($wxpaySecretCert) {
  97. $payConfig['wechat']['default']['mch_secret_cert'] = $wxpaySecretCert;
  98. }
  99. if ($wxpayPublicCert) {
  100. $payConfig['wechat']['default']['mch_public_cert_path'] = $wxpayPublicCert;
  101. }
  102. //$payConfig['wechat']['default']['notify_url'] = url('/api/notify/' . $scene . '/10');
  103. $payConfig['wechat']['default']['notify_url'] = url(env('APP_URL') . 'api/notify/' . $scene . '/10');
  104. $this->config = $payConfig;
  105. //var_dump($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. } catch (\Exception $exception){
  138. $this->errorData = $this->config;
  139. $this->error = '请检查支付配置是否正常:'.$exception->getMessage();
  140. return false;
  141. }
  142. }
  143. /**
  144. * 微信小程序支付
  145. * @param $userInfo
  146. * @param $order
  147. * @param string $scene
  148. * @return false|\Yansongda\Supports\Collection
  149. */
  150. public function minPay($userInfo, $order, $scene = 'store')
  151. {
  152. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  153. $openid = isset($order['openid']) ? $order['openid'] : '';
  154. $isRevenue = isset($order['is_revenue']) ? $order['is_revenue'] : 0;
  155. if ($amount < 0) {
  156. $this->error = 2615;
  157. return false;
  158. }
  159. if (empty($openid)) {
  160. $this->error = 2614;
  161. return false;
  162. }
  163. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  164. // 是否调用过支付,是则用新的支付单号
  165. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  166. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  167. }
  168. $body = isset($order['body']) ? $order['body'] : '';
  169. $payData = [
  170. 'out_trade_no' => $outTradeNo,
  171. 'description' => $body ? $body : '订单支付',
  172. 'amount' => [
  173. 'total' => intval($amount * 1000/10),
  174. 'currency' => 'CNY'
  175. ],
  176. 'payer' => [
  177. 'openid' => $openid,
  178. ],
  179. ];
  180. // 订单分账
  181. if($isRevenue==1){
  182. $payData['settle_info'] = [
  183. 'profit_sharing'=> true,
  184. ];
  185. }
  186. // 创建支付
  187. try {
  188. $pay = $this->createPay($scene, 10, 'min');
  189. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  190. if (empty($pay)) {
  191. $this->error = 2616;
  192. return false;
  193. }
  194. $pay = $pay->mini($payData);
  195. } catch (\Exception $exception) {
  196. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  197. $this->error = $exception->getMessage();
  198. return false;
  199. }
  200. if ($pay->package) {
  201. $data = [
  202. 'user_id' => $userInfo['id'],
  203. 'out_trade_no' => $outTradeNo,
  204. 'order_no' => $order['order_no'],
  205. 'params' => json_encode($pay, 256),
  206. 'total_fee' => $amount,
  207. 'pay_type' => 10,
  208. 'create_time' => time(),
  209. 'status' => 2,
  210. 'mark' => 1,
  211. ];
  212. if ($this->model->insertGetId($data)) {
  213. $this->error = 2617;
  214. return $pay;
  215. }
  216. }
  217. $this->error = 2618;
  218. return false;
  219. }
  220. /**
  221. * 微信支付
  222. * @param $userInfo
  223. * @param $order
  224. * @param string $scene
  225. * @return false|\Yansongda\Supports\Collection
  226. */
  227. public function wechatPay($userInfo, $order, $scene = 'store')
  228. {
  229. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  230. if ($amount < 0) {
  231. $this->error = 2615;
  232. return false;
  233. }
  234. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  235. // 是否调用过支付,是则用新的支付单号
  236. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  237. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  238. }
  239. $body = isset($order['body']) ? $order['body'] : '';
  240. $type = isset($order['type']) ? $order['type'] : 0;
  241. $payData = [
  242. 'out_trade_no' => $outTradeNo,
  243. 'attach' => "order-{$type}",
  244. 'description' => $body ? $body : '订单支付',
  245. 'amount' => [
  246. 'total' => intval($amount * 1000/10),
  247. 'currency' => 'CNY'
  248. ],
  249. ];
  250. // 创建支付
  251. try {
  252. $pay = $this->createPay($scene, 10);
  253. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  254. if (empty($pay)) {
  255. $this->error = 2616;
  256. return false;
  257. }
  258. $pay = $pay->app($payData);
  259. } catch (\Exception $exception) {
  260. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  261. $this->error = $exception->getMessage();
  262. return false;
  263. }
  264. if ($pay->prepayid) {
  265. $data = [
  266. 'user_id' => $userInfo['id'],
  267. 'out_trade_no' => $outTradeNo,
  268. 'order_no' => $order['order_no'],
  269. 'params' => json_encode($pay, 256),
  270. 'total_fee' => $amount,
  271. 'pay_type' => 10,
  272. 'create_time' => time(),
  273. 'status' => 2,
  274. 'mark' => 1,
  275. ];
  276. if ($this->model->insertGetId($data)) {
  277. $this->error = 2617;
  278. return $pay;
  279. }
  280. }
  281. $this->error = 2618;
  282. return false;
  283. }
  284. /**
  285. * 支付宝支付
  286. * @param $userInfo
  287. * @param $order
  288. * @return bool
  289. */
  290. public function aliPay($userInfo, $order, $scene = 'shop')
  291. {
  292. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  293. if ($amount < 0) {
  294. $this->error = 2615;
  295. return false;
  296. }
  297. // 是否调用过支付,是则用新的支付单号
  298. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  299. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  300. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  301. }
  302. $body = isset($order['body']) ? $order['body'] : '';
  303. $payData = [
  304. 'out_trade_no' => $outTradeNo,
  305. 'subject' => $body ? $body : '订单支付',
  306. 'total_amount' => $amount,
  307. ];
  308. // 创建支付
  309. $pay = $this->createPay($scene, 20);
  310. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  311. if (empty($pay)) {
  312. $this->error = 2619;
  313. return false;
  314. }
  315. $pay = $pay->app($payData);
  316. if ($pay->getStatusCode() == 200) {
  317. $data = [
  318. 'user_id' => $userInfo['id'],
  319. 'out_trade_no' => $outTradeNo,
  320. 'order_no' => $order['order_no'],
  321. 'params' => json_encode($pay, 256),
  322. 'total_fee' => $amount,
  323. 'pay_type' => 20,
  324. 'create_time' => time(),
  325. 'status' => 2,
  326. 'mark' => 1,
  327. ];
  328. if ($this->model->insertGetId($data)) {
  329. $this->error = 2620;
  330. return $pay->getBody()->getContents();
  331. }
  332. }
  333. $this->error = 2621;
  334. return false;
  335. }
  336. /**
  337. * 订单支付回调处理
  338. * @param string $scene 场景 store-购物消费,pay-充值,refund-退款
  339. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  340. * @param array $data 回调数据
  341. * @return bool
  342. */
  343. public function catchNotify($scene, $payType, $data)
  344. {
  345. $outTradeNo = '';
  346. $payTotal = 0;
  347. $transactionId = '';
  348. $payAt = '';
  349. $notifyData = [];
  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. $id = 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($id){
  525. if(!AccountStatisticsModel::where(['id'=>$id])->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(!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', ['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. }