PaymentService.php 30 KB

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