PaymentService.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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 App\Services\Api\SettleService;
  17. use Illuminate\Support\Facades\DB;
  18. use Yansongda\Pay\Pay;
  19. use Yansongda\Pay\Plugin\Wechat\Fund\Profitsharing\AddReceiverPlugin;
  20. use Yansongda\Pay\Plugin\Wechat\Fund\Profitsharing\CreatePlugin;
  21. use Yansongda\Pay\Provider\Wechat;
  22. /**
  23. * 支付-服务类
  24. * @author laravel开发员
  25. * @since 2020/11/11
  26. * Class PaymentService
  27. * @package App\Services\Api
  28. */
  29. class PaymentService extends BaseService
  30. {
  31. protected static $instance = null;
  32. private $config = [];
  33. /**
  34. * 构造函数
  35. * @author laravel开发员
  36. * @since 2020/11/11
  37. * PaymentService constructor.
  38. */
  39. public function __construct()
  40. {
  41. $this->model = new PaymentModel();
  42. }
  43. /**
  44. * 静态入口
  45. * @return static|null
  46. */
  47. public static function make()
  48. {
  49. if (!self::$instance) {
  50. self::$instance = (new static());
  51. }
  52. return self::$instance;
  53. }
  54. /**
  55. * 创建支付
  56. * @param string $scene 场景,store-购物消费,pay-生活充值,refund-退款
  57. * @param int $payType
  58. * @param int $isMin 是否是小程序
  59. * @return false|\Yansongda\Pay\Provider\Alipay|Wechat
  60. */
  61. public function createPay($scene, $payType = 10, $payPt = '')
  62. {
  63. $config = ConfigService::make()->getConfigOptionByGroup(6);
  64. try {
  65. if ($payType == 10) {
  66. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  67. $mpAppid = isset($config['wxpay_mp_appid']) ? $config['wxpay_mp_appid'] : '';
  68. $minAppid = isset($config['wxpay_min_appid']) ? $config['wxpay_min_appid'] : '';
  69. $mchid = isset($config['wxpay_mchd']) ? $config['wxpay_mchd'] : '';
  70. $secretV3Key = isset($config['wxpay_key_v3']) ? $config['wxpay_key_v3'] : '';
  71. $secretV2Key = isset($config['wxpay_key_v2']) ? $config['wxpay_key_v2'] : '';
  72. $publicKeyId = isset($config['public_key_id']) ? $config['public_key_id'] : '';
  73. $wxpaySecretCert = isset($config['wxpay_secret_cert']) ? $config['wxpay_secret_cert'] : '';
  74. $wxpayPublicCert = isset($config['wxpay_public_cert']) ? $config['wxpay_public_cert'] : '';
  75. if (empty($appid) || empty($mchid) || empty($secretV3Key)) {
  76. $this->error = 2616;
  77. return false;
  78. }
  79. // 支付参数
  80. $payConfig = config('payment.wechat');
  81. $payConfig['wechat']['default']['mch_id'] = $mchid;
  82. $payConfig['wechat']['default']['wechat_public_cert_path']["PUB_KEY_ID_{$publicKeyId}"] = base_path().'/resources/certs/wechat/pub_key.pem';
  83. if ($payPt == 'min') {
  84. // 小程序支付
  85. $payConfig['wechat']['default']['mini_app_id'] = $minAppid ? $minAppid : $appid;
  86. } else if ($payPt == 'mp' || $scene == 'sharing') {
  87. // 公众号
  88. $payConfig['wechat']['default']['mp_app_id'] = $mpAppid ? $mpAppid : $appid;
  89. } else {
  90. // APP支付
  91. $payConfig['wechat']['default']['app_id'] = $appid;
  92. }
  93. if ($secretV3Key) {
  94. $payConfig['wechat']['default']['mch_secret_key'] = $secretV3Key;
  95. } else if ($secretV2Key) {
  96. $payConfig['wechat']['default']['mch_secret_key_v2'] = $secretV2Key;
  97. }
  98. if ($wxpaySecretCert) {
  99. $payConfig['wechat']['default']['mch_secret_cert'] = $wxpaySecretCert;
  100. }
  101. if ($wxpayPublicCert) {
  102. $payConfig['wechat']['default']['mch_public_cert_path'] = $wxpayPublicCert;
  103. }
  104. //$payConfig['wechat']['default']['notify_url'] = url('/api/notify/' . $scene . '/10');
  105. $payConfig['wechat']['default']['notify_url'] = url(env('APP_URL') . 'api/notify/' . $scene . '/10');
  106. $this->config = $payConfig;
  107. //var_dump($payConfig);
  108. return Pay::wechat($payConfig);
  109. } else if ($payType == 20) {
  110. $appid = isset($config['alipay_appid']) ? $config['alipay_appid'] : '';
  111. $appSecretCert = isset($config['alipay_secret_cert']) ? $config['alipay_secret_cert'] : '';
  112. $appPublicCert = isset($config['alipay_app_public_cert_path']) ? $config['alipay_app_public_cert_path'] : '';
  113. $alipayPublicCert = isset($config['alipay_public_cert_path']) ? $config['alipay_public_cert_path'] : '';
  114. $alipayRootCert = isset($config['alipay_root_cert_path']) ? $config['alipay_root_cert_path'] : '';
  115. if (empty($appid) || empty($appSecretCert)) {
  116. $this->error = 2619;
  117. return false;
  118. }
  119. // 支付参数
  120. $payConfig = config('payment.alipay');
  121. $payConfig['alipay']['default']['app_id'] = $appid;
  122. $payConfig['alipay']['default']['app_secret_cert'] = $appSecretCert;
  123. if ($appPublicCert) {
  124. $payConfig['alipay']['default']['app_public_cert_path'] = $appPublicCert;
  125. }
  126. if ($alipayPublicCert) {
  127. $payConfig['alipay']['default']['alipay_public_cert_path'] = $alipayPublicCert;
  128. }
  129. if ($alipayRootCert) {
  130. $payConfig['alipay']['default']['alipay_root_cert_path'] = $alipayRootCert;
  131. }
  132. $payConfig['alipay']['default']['notify_url'] = url('/api/notify/' . $scene . '/20');
  133. $this->config = $payConfig;
  134. return Pay::alipay($payConfig);
  135. } else if ($payType == 30) {
  136. return true;
  137. }
  138. return false;
  139. } catch (\Exception $exception){
  140. $this->errorData = $this->config;
  141. $this->error = '请检查支付配置是否正常:'.$exception->getMessage();
  142. return false;
  143. }
  144. }
  145. /**
  146. * 微信小程序支付
  147. * @param $userInfo
  148. * @param $order
  149. * @param string $scene
  150. * @return false|\Yansongda\Supports\Collection
  151. */
  152. public function minPay($userInfo, $order, $scene = 'store')
  153. {
  154. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  155. $openid = isset($order['openid']) ? $order['openid'] : '';
  156. $isRevenue = isset($order['is_revenue']) ? $order['is_revenue'] : 0;
  157. if ($amount < 0) {
  158. $this->error = 2615;
  159. return false;
  160. }
  161. if (empty($openid)) {
  162. $this->error = 2614;
  163. return false;
  164. }
  165. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  166. // 是否调用过支付,是则用新的支付单号
  167. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  168. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  169. }
  170. $body = isset($order['body']) ? $order['body'] : '';
  171. $payData = [
  172. 'out_trade_no' => $outTradeNo,
  173. 'description' => $body ? $body : '订单支付',
  174. 'amount' => [
  175. 'total' => intval($amount * 1000/10),
  176. 'currency' => 'CNY'
  177. ],
  178. 'payer' => [
  179. 'openid' => $openid,
  180. ],
  181. ];
  182. // 订单分账
  183. if($isRevenue==1){
  184. $payData['settle_info'] = [
  185. 'profit_sharing'=> true,
  186. ];
  187. }
  188. // 创建支付
  189. try {
  190. $pay = $this->createPay($scene, 10, 'min');
  191. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  192. if (empty($pay)) {
  193. $this->error = 2616;
  194. return false;
  195. }
  196. $pay = $pay->mini($payData);
  197. } catch (\Exception $exception) {
  198. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  199. $this->error = $exception->getMessage();
  200. return false;
  201. }
  202. if ($pay->package) {
  203. $data = [
  204. 'user_id' => $userInfo['id'],
  205. 'out_trade_no' => $outTradeNo,
  206. 'order_no' => $order['order_no'],
  207. 'params' => json_encode($pay, 256),
  208. 'total_fee' => $amount,
  209. 'pay_type' => 10,
  210. 'create_time' => time(),
  211. 'status' => 2,
  212. 'mark' => 1,
  213. ];
  214. if ($this->model->insertGetId($data)) {
  215. $this->error = 2617;
  216. return $pay;
  217. }
  218. }
  219. $this->error = 2618;
  220. return false;
  221. }
  222. /**
  223. * 微信支付
  224. * @param $userInfo
  225. * @param $order
  226. * @param string $scene
  227. * @return false|\Yansongda\Supports\Collection
  228. */
  229. public function wechatPay($userInfo, $order, $scene = 'store')
  230. {
  231. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  232. if ($amount < 0) {
  233. $this->error = 2615;
  234. return false;
  235. }
  236. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  237. // 是否调用过支付,是则用新的支付单号
  238. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  239. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  240. }
  241. $body = isset($order['body']) ? $order['body'] : '';
  242. $type = isset($order['type']) ? $order['type'] : 0;
  243. $payData = [
  244. 'out_trade_no' => $outTradeNo,
  245. 'attach' => "order-{$type}",
  246. 'description' => $body ? $body : '订单支付',
  247. 'amount' => [
  248. 'total' => intval($amount * 1000/10),
  249. 'currency' => 'CNY'
  250. ],
  251. ];
  252. // 创建支付
  253. try {
  254. $pay = $this->createPay($scene, 10);
  255. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  256. if (empty($pay)) {
  257. $this->error = 2616;
  258. return false;
  259. }
  260. $pay = $pay->app($payData);
  261. } catch (\Exception $exception) {
  262. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  263. $this->error = $exception->getMessage();
  264. return false;
  265. }
  266. if ($pay->prepayid) {
  267. $data = [
  268. 'user_id' => $userInfo['id'],
  269. 'out_trade_no' => $outTradeNo,
  270. 'order_no' => $order['order_no'],
  271. 'params' => json_encode($pay, 256),
  272. 'total_fee' => $amount,
  273. 'pay_type' => 10,
  274. 'create_time' => time(),
  275. 'status' => 2,
  276. 'mark' => 1,
  277. ];
  278. if ($this->model->insertGetId($data)) {
  279. $this->error = 2617;
  280. return $pay;
  281. }
  282. }
  283. $this->error = 2618;
  284. return false;
  285. }
  286. /**
  287. * 支付宝支付
  288. * @param $userInfo
  289. * @param $order
  290. * @return bool
  291. */
  292. public function aliPay($userInfo, $order, $scene = 'shop')
  293. {
  294. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  295. if ($amount < 0) {
  296. $this->error = 2615;
  297. return false;
  298. }
  299. // 是否调用过支付,是则用新的支付单号
  300. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  301. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  302. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  303. }
  304. $body = isset($order['body']) ? $order['body'] : '';
  305. $payData = [
  306. 'out_trade_no' => $outTradeNo,
  307. 'subject' => $body ? $body : '订单支付',
  308. 'total_amount' => $amount,
  309. ];
  310. // 创建支付
  311. $pay = $this->createPay($scene, 20);
  312. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  313. if (empty($pay)) {
  314. $this->error = 2619;
  315. return false;
  316. }
  317. $pay = $pay->app($payData);
  318. if ($pay->getStatusCode() == 200) {
  319. $data = [
  320. 'user_id' => $userInfo['id'],
  321. 'out_trade_no' => $outTradeNo,
  322. 'order_no' => $order['order_no'],
  323. 'params' => json_encode($pay, 256),
  324. 'total_fee' => $amount,
  325. 'pay_type' => 20,
  326. 'create_time' => time(),
  327. 'status' => 2,
  328. 'mark' => 1,
  329. ];
  330. if ($this->model->insertGetId($data)) {
  331. $this->error = 2620;
  332. return $pay->getBody()->getContents();
  333. }
  334. }
  335. $this->error = 2621;
  336. return false;
  337. }
  338. /**
  339. * 订单支付回调处理
  340. * @param string $scene 场景 store-购物消费,pay-充值,refund-退款
  341. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  342. * @param array $data 回调数据
  343. * @return bool
  344. */
  345. public function catchNotify($scene, $payType, $data)
  346. {
  347. $outTradeNo = '';
  348. $payTotal = 0;
  349. $transactionId = '';
  350. $payAt = '';
  351. $notifyData = [];
  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','type', 'user_id', 'order_no', 'total as pay_money','bd_score','profit_total', 'pay_at as pay_time', 'remark', 'status'])
  441. ->first();
  442. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  443. $orderType = isset($orderInfo['type']) ? $orderInfo['type'] : 0;
  444. // 验证订单
  445. if (empty($orderInfo)) {
  446. DB::rollBack();
  447. $this->error = 2629;
  448. return false;
  449. }
  450. // 订单状态
  451. if ($orderStatus != 1) {
  452. DB::rollBack();
  453. $this->error = 2630;
  454. return false;
  455. }
  456. $updateData = ['pay_at' => $payAt,'pay_status'=>20, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  457. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  458. $this->error = 2633;
  459. DB::rollBack();
  460. return false;
  461. }
  462. // 创业订单
  463. if($orderType==2){
  464. $updateData = ['pay_at' => $payAt,'pay_status'=>20, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  465. if (!OrderModel::where(['main_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  466. $this->error = 2633;
  467. DB::rollBack();
  468. return false;
  469. }
  470. }
  471. }
  472. // 退款
  473. else if ($scene == 'refund') {
  474. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  475. ->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'])
  476. ->first();
  477. $refundRemark = isset($orderInfo['refund_remark']) ? $orderInfo['refund_remark'] : 'refund_remark';
  478. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  479. // 验证订单
  480. if (empty($orderInfo)) {
  481. DB::rollBack();
  482. $this->error = 2629;
  483. return false;
  484. }
  485. // 订单状态
  486. if ($orderStatus != 2) {
  487. DB::rollBack();
  488. $this->error = 2639;
  489. return false;
  490. }
  491. // 订单打款状态
  492. if ($orderStatus == 1) {
  493. DB::rollBack();
  494. $this->error = 2630;
  495. return false;
  496. }
  497. $updateData = ['refund_status' => 1, 'refund_remark' => $refundRemark ? $refundRemark . ' 已退款成功' : '已退款成功', 'update_time' => time()];
  498. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  499. $this->error = 2633;
  500. DB::rollBack();
  501. return false;
  502. }
  503. }
  504. // TODO 场景业务回调处理
  505. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  506. $this->saveLog("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data]);
  507. switch ($scene) {
  508. case 'store': //
  509. $orderId = isset($orderInfo['id'])?$orderInfo['id']:0;
  510. $orderType = isset($orderInfo['type'])?$orderInfo['type']:0;
  511. $userInfo = isset($orderInfo['user'])?$orderInfo['user']:[];
  512. $points = isset($userInfo['points'])?$userInfo['points']:'';
  513. // 礼包订单
  514. if($orderType == 2){
  515. // 订单支付成功结算
  516. SettleService::make()->commissionSettle($orderId);
  517. // 用户升级处理
  518. SettleService::make()->updateUserData($orderUserId, $points);
  519. }
  520. RedisService::clear("caches:orders:settleList");
  521. break;
  522. default:
  523. break;
  524. }
  525. $this->error = '回调处理成功';
  526. DB::commit();
  527. return true;
  528. } catch (\Exception $exception) {
  529. $this->error = $exception->getMessage();
  530. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
  531. return false;
  532. }
  533. }
  534. /**
  535. * 日志
  536. * @param $key
  537. * @param $data
  538. */
  539. public function saveLog($key, $data)
  540. {
  541. if(env('APP_DEBUG')){
  542. RedisService::set($key,$data,7200);
  543. }
  544. }
  545. /**
  546. * 退款请求
  547. * @param $order
  548. * @param string $scene
  549. * @return bool
  550. * @throws \Yansongda\Pay\Exception\ContainerException
  551. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  552. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  553. */
  554. public function refund($order, $scene = 'store')
  555. {
  556. $money = isset($order['money']) ? $order['money'] : 0;
  557. $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
  558. $orderNo = isset($order['order_no']) ? $order['order_no'] : '';
  559. $outTradeNo = isset($order['out_trade_no']) ? $order['out_trade_no'] : '';
  560. $transactionId = isset($order['transaction_id']) ? $order['transaction_id'] : '';
  561. $remark = isset($order['remark']) && $order['remark'] ? $order['remark'] : '退款';
  562. $pay = PaymentService::make()->createPay($scene, $payType);
  563. if (empty($pay)) {
  564. DB::rollBack();
  565. $this->error = '创建退款支付失败';
  566. return false;
  567. }
  568. // 保证金退款处理
  569. $refundStatus = false;
  570. switch ($payType) {
  571. case 10: // 微信支付
  572. $data = [
  573. 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
  574. 'out_refund_no' => get_order_num('RF'),
  575. 'transaction_id' => $transactionId,
  576. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  577. 'reason' => $remark,
  578. 'amount' => [
  579. 'refund' => intval($money * 100),
  580. 'total' => intval($money * 100),
  581. 'currency' => 'CNY',
  582. ],
  583. ];
  584. // 请求退款
  585. $pay = $pay->refund($data);
  586. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data, 'pay' => $pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  587. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  588. $refundStatus = true;
  589. } else {
  590. DB::rollBack();
  591. $this->errorData = $data;
  592. $this->error = '微信退款处理失败:'.$pay->message;
  593. return false;
  594. }
  595. break;
  596. case 20: // 支付宝
  597. $data = [
  598. 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
  599. 'trade_no' => $transactionId,
  600. 'refund_amount' => $money,
  601. 'query_options' => ['deposit_back_info'],
  602. 'refund_reason' => $remark,
  603. ];
  604. $payResult = $pay->refund($data);
  605. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  606. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  607. $refundStatus = true;
  608. } else {
  609. $this->errorData = $data;
  610. $this->error = '支付宝退款处理失败:'.$payResult->code;
  611. return false;
  612. }
  613. break;
  614. default:
  615. $this->error = '退款支付类型错误';
  616. return false;
  617. }
  618. $this->error = '退款处理成功';
  619. return $refundStatus;
  620. }
  621. /**
  622. * 企业打款到零钱(商家转账)
  623. * @param $order 订单参数:order_no-单号,pay_money-打款金额,account-打款账号(微信openid或支付宝账号),body-打款备注
  624. * @param string $scene
  625. * @param int $payType
  626. * @return bool
  627. */
  628. public function transfer($order, $scene='withdraw', $payType=10)
  629. {
  630. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('WD');
  631. $body = isset($order['body']) ? $order['body'] : '';
  632. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  633. $account = isset($order['account']) ? $order['account'] : ''; // 微信openid或支付宝账号
  634. $realName = isset($order['real_name']) ? $order['real_name'] : ''; // 实名
  635. if ($amount < 0) {
  636. $this->error = '打款金额错误';
  637. return false;
  638. }
  639. if(empty($account)){
  640. $this->error = $payType == 10? '缺少微信OPENID' : '支付宝账户不为空';
  641. return false;
  642. }
  643. // 创建支付
  644. $result = [];
  645. try {
  646. $config = ConfigService::make()->getConfigOptionByGroup(6);
  647. if ($payType == 10) {
  648. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  649. $payData = [
  650. '_action' => 'mch_transfer', // 微信官方老版本下线后,此部分可省略
  651. 'appid' => $appid,
  652. 'out_bill_no' => $outTradeNo,
  653. 'transfer_scene_id' => '1000',
  654. 'openid' => $account,
  655. 'transfer_amount' => intval($amount * 100),
  656. 'transfer_remark' => $body?$body:'收益结算',
  657. 'user_recv_perception' => '现金奖励',
  658. "transfer_scene_report_infos"=> [
  659. [
  660. "info_type" => "活动名称",
  661. "info_content" => "收益结算"
  662. ],
  663. [
  664. "info_type" => "奖励说明",
  665. "info_content" => "数字资产提现"
  666. ]
  667. ],
  668. ];
  669. $pay = $this->createPay($scene, $payType);
  670. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_pay", ['order' => $order,'params'=>$payData,'pay'=>$pay, 'config' => $this->config], 7200);
  671. if (empty($pay)) {
  672. $this->error = '微信打款失败';
  673. return false;
  674. }
  675. $result = $pay->transfer($payData);
  676. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_result", ['order' => $order,'params'=>$payData,'result'=> $result, 'config' => $this->config], 7200);
  677. $msg = isset($result['message'])? trim($result['message']) : '';
  678. $batchId = isset($result['transfer_bill_no'])? trim($result['transfer_bill_no']) : '';
  679. $packageInfo = isset($result['package_info'])? trim($result['package_info']) : '';
  680. if(empty($batchId) || empty($packageInfo)){
  681. $this->error = $msg? $msg : '微信打款失败';
  682. return false;
  683. }
  684. $this->error = '微信打款成功';
  685. return ['order_no'=> $outTradeNo,'mch_id'=>$config['wxpay_mchd'],'batch_id'=> $batchId,'package_info'=>$packageInfo,'result'=>$result];
  686. }else if ($payType == 20){
  687. $payData = [
  688. 'out_biz_no' => $outTradeNo,//商户订单号,内部订单号
  689. 'trans_amount' => $amount, //订单总金额,单位为元,精确到小数点后两位,
  690. 'biz_scene' => 'DIRECT_TRANSFER', //描述特定的业务场景,可传的参数如下:DIRECT_TRANSFER:单笔无密转账到支付宝,B2C现金红包PERSONAL_COLLECTION:C2C现金红包-领红包
  691. 'product_code' => 'TRANS_ACCOUNT_NO_PWD', //业务产品码,单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD;收发现金红包固定为:STD_RED_PACKET;
  692. 'remark' => $body? $body : '提现',//业务备注
  693. 'order_title' => $body? $body : '提现',//转账业务的标题,用于在支付宝用户的账单里显示
  694. 'payee_info' => [
  695. 'identity' => $account,//参与方的唯一标识'208823395231'
  696. 'name' => $realName,//参与方的唯一标识'208823395231'
  697. 'identity_type' => 'ALIPAY_LOGON_ID',//参与方的标识类型,目前支持如下类型:1、ALIPAY_USER_ID 支付宝的会员ID2、ALIPAY_LOGON_ID:支付宝登录号,支持邮箱和手机号格式3、ALIPAY_OPEN_ID:支付宝openid
  698. ],//收款方信息
  699. ];
  700. $pay = $this->createPay($scene, $payType);
  701. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_pay", ['order' => $order,'params'=>$payData, 'config' => $this->config], 7200);
  702. if (empty($pay)) {
  703. $this->error = '支付宝打款失败';
  704. return false;
  705. }
  706. $result = $pay->transfer($payData);
  707. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_result", ['order' => $order,'params'=>$payData,'result'=> $result, 'config' => $this->config], 7200);
  708. $code = isset($result['code'])? intval($result['code']) : '';
  709. $msg = isset($result['sub_msg'])? trim($result['sub_msg']) : '';
  710. if($code != 10000){
  711. $this->error = $msg? $msg : '支付宝打款失败';
  712. return false;
  713. }
  714. $this->error = '支付宝打款成功';
  715. return $result;
  716. }else if($payType == 50){
  717. $this->error = '银行卡打款未开通';
  718. return false;
  719. }
  720. $this->error = '打款失败';
  721. return false;
  722. } catch (\Exception $exception) {
  723. RedisService::set("caches:payments:trabsfer:{$scene}_{$outTradeNo}_error", ['order' => $order,'msg'=>$exception->getMessage(),'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
  724. $this->error = '打款失败:'.$exception->getMessage().'或运营账户资金是否充足';
  725. return false;
  726. }
  727. }
  728. /**
  729. * 分账
  730. * @param $openid
  731. * @param $order
  732. * @param string $scene
  733. * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
  734. * @throws \Yansongda\Pay\Exception\ContainerException
  735. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  736. */
  737. public function profitsharing($openid, $order ,$scene='sharing')
  738. {
  739. $data = [
  740. 'type' => 'PERSONAL_OPENID',
  741. 'account' => $openid,
  742. 'relation_type' => 'SERVICE_PROVIDER'
  743. ];
  744. $pay = PaymentService::make()->createPay($scene, 10);
  745. $plugin = $pay->mergeCommonPlugins([
  746. AddReceiverPlugin::class
  747. ], $data);
  748. // 添加分账插件配置
  749. $pay->pay($plugin, $data);
  750. // 分账数据
  751. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : ''; // 支付交易单号
  752. $profitsharingOrderNo = isset($order['out_order_no'])? $order['out_order_no'] : ''; // 分账单号,非支付单号
  753. $body = isset($order['body'])? $order['body'] : ''; // 分账备注描述
  754. $amount = isset($order['amount'])? $order['amount'] : ''; // 分账金额
  755. $unsplit = isset($order['unsplit'])? $order['unsplit'] : true; // 是否限制只分账一次
  756. $postData = [
  757. 'transaction_id' => $transactionId,
  758. 'out_order_no' => $profitsharingOrderNo,
  759. 'receivers' => [
  760. [
  761. 'type' => 'PERSONAL_OPENID',
  762. 'account' => $openid,
  763. 'amount' => intval($amount*100), // 分账金额,单位:分
  764. 'description' => $body, //分账描述
  765. ],
  766. ],
  767. 'unfreeze_unsplit' => $unsplit,
  768. ];
  769. // 创建分账数据
  770. $createPlugin = $pay->mergeCommonPlugins([
  771. CreatePlugin::class
  772. ], $postData);
  773. // 发起分账
  774. $result = $pay->pay($createPlugin, $postData);
  775. return $result;
  776. }
  777. }