PaymentService.php 30 KB

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