PaymentService.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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. $orderGoods = isset($orderInfo['orderGoods'])?$orderInfo['orderGoods']:[];
  512. // 订单支付成功结算
  513. if($orderType == 2){
  514. SettleService::make()->commissionSettle($orderId);
  515. }
  516. break;
  517. default:
  518. break;
  519. }
  520. $this->error = '回调处理成功';
  521. DB::commit();
  522. return true;
  523. } catch (\Exception $exception) {
  524. $this->error = $exception->getMessage();
  525. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
  526. return false;
  527. }
  528. }
  529. /**
  530. * 日志
  531. * @param $key
  532. * @param $data
  533. */
  534. public function saveLog($key, $data)
  535. {
  536. if(env('APP_DEBUG')){
  537. RedisService::set($key,$data,7200);
  538. }
  539. }
  540. /**
  541. * 退款请求
  542. * @param $order
  543. * @param string $scene
  544. * @return bool
  545. * @throws \Yansongda\Pay\Exception\ContainerException
  546. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  547. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  548. */
  549. public function refund($order, $scene = 'store')
  550. {
  551. $money = isset($order['money']) ? $order['money'] : 0;
  552. $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
  553. $orderNo = isset($order['order_no']) ? $order['order_no'] : '';
  554. $outTradeNo = isset($order['out_trade_no']) ? $order['out_trade_no'] : '';
  555. $transactionId = isset($order['transaction_id']) ? $order['transaction_id'] : '';
  556. $remark = isset($order['remark']) && $order['remark'] ? $order['remark'] : '退款';
  557. $pay = PaymentService::make()->createPay($scene, $payType);
  558. if (empty($pay)) {
  559. DB::rollBack();
  560. $this->error = '创建退款支付失败';
  561. return false;
  562. }
  563. // 保证金退款处理
  564. $refundStatus = false;
  565. switch ($payType) {
  566. case 10: // 微信支付
  567. $data = [
  568. 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
  569. 'out_refund_no' => get_order_num('RF'),
  570. 'transaction_id' => $transactionId,
  571. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  572. 'reason' => $remark,
  573. 'amount' => [
  574. 'refund' => intval($money * 100),
  575. 'total' => intval($money * 100),
  576. 'currency' => 'CNY',
  577. ],
  578. ];
  579. // 请求退款
  580. $pay = $pay->refund($data);
  581. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data, 'pay' => $pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  582. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  583. $refundStatus = true;
  584. } else {
  585. DB::rollBack();
  586. $this->errorData = $data;
  587. $this->error = '微信退款处理失败:'.$pay->message;
  588. return false;
  589. }
  590. break;
  591. case 20: // 支付宝
  592. $data = [
  593. 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
  594. 'trade_no' => $transactionId,
  595. 'refund_amount' => $money,
  596. 'query_options' => ['deposit_back_info'],
  597. 'refund_reason' => $remark,
  598. ];
  599. $payResult = $pay->refund($data);
  600. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  601. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  602. $refundStatus = true;
  603. } else {
  604. $this->errorData = $data;
  605. $this->error = '支付宝退款处理失败:'.$payResult->code;
  606. return false;
  607. }
  608. break;
  609. default:
  610. $this->error = '退款支付类型错误';
  611. return false;
  612. }
  613. $this->error = '退款处理成功';
  614. return $refundStatus;
  615. }
  616. /**
  617. * 企业打款到零钱(商家转账)
  618. * @param $order 订单参数:order_no-单号,pay_money-打款金额,account-打款账号(微信openid或支付宝账号),body-打款备注
  619. * @param string $scene
  620. * @param int $payType
  621. * @return bool
  622. */
  623. public function transfer($order, $scene='withdraw', $payType=10)
  624. {
  625. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('WD');
  626. $body = isset($order['body']) ? $order['body'] : '';
  627. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  628. $account = isset($order['account']) ? $order['account'] : ''; // 微信openid或支付宝账号
  629. $realName = isset($order['real_name']) ? $order['real_name'] : ''; // 实名
  630. if ($amount < 0) {
  631. $this->error = '打款金额错误';
  632. return false;
  633. }
  634. if(empty($account)){
  635. $this->error = $payType == 10? '缺少微信OPENID' : '支付宝账户不为空';
  636. return false;
  637. }
  638. // 创建支付
  639. $result = [];
  640. try {
  641. $config = ConfigService::make()->getConfigOptionByGroup(6);
  642. if ($payType == 10) {
  643. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  644. $payData = [
  645. '_action' => 'mch_transfer', // 微信官方老版本下线后,此部分可省略
  646. 'appid' => $appid,
  647. 'out_bill_no' => $outTradeNo,
  648. 'transfer_scene_id' => '1000',
  649. 'openid' => $account,
  650. 'transfer_amount' => intval($amount * 100),
  651. 'transfer_remark' => $body?$body:'收益结算',
  652. 'user_recv_perception' => '现金奖励',
  653. "transfer_scene_report_infos"=> [
  654. [
  655. "info_type" => "活动名称",
  656. "info_content" => "收益结算"
  657. ],
  658. [
  659. "info_type" => "奖励说明",
  660. "info_content" => "数字资产提现"
  661. ]
  662. ],
  663. ];
  664. $pay = $this->createPay($scene, $payType);
  665. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_pay", ['order' => $order,'params'=>$payData,'pay'=>$pay, 'config' => $this->config], 7200);
  666. if (empty($pay)) {
  667. $this->error = '微信打款失败';
  668. return false;
  669. }
  670. $result = $pay->transfer($payData);
  671. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_result", ['order' => $order,'params'=>$payData,'result'=> $result, 'config' => $this->config], 7200);
  672. $msg = isset($result['message'])? trim($result['message']) : '';
  673. $batchId = isset($result['transfer_bill_no'])? trim($result['transfer_bill_no']) : '';
  674. $packageInfo = isset($result['package_info'])? trim($result['package_info']) : '';
  675. if(empty($batchId) || empty($packageInfo)){
  676. $this->error = $msg? $msg : '微信打款失败';
  677. return false;
  678. }
  679. $this->error = '微信打款成功';
  680. return ['order_no'=> $outTradeNo,'mch_id'=>$config['wxpay_mchd'],'batch_id'=> $batchId,'package_info'=>$packageInfo,'result'=>$result];
  681. }else if ($payType == 20){
  682. $payData = [
  683. 'out_biz_no' => $outTradeNo,//商户订单号,内部订单号
  684. 'trans_amount' => $amount, //订单总金额,单位为元,精确到小数点后两位,
  685. 'biz_scene' => 'DIRECT_TRANSFER', //描述特定的业务场景,可传的参数如下:DIRECT_TRANSFER:单笔无密转账到支付宝,B2C现金红包PERSONAL_COLLECTION:C2C现金红包-领红包
  686. 'product_code' => 'TRANS_ACCOUNT_NO_PWD', //业务产品码,单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD;收发现金红包固定为:STD_RED_PACKET;
  687. 'remark' => $body? $body : '提现',//业务备注
  688. 'order_title' => $body? $body : '提现',//转账业务的标题,用于在支付宝用户的账单里显示
  689. 'payee_info' => [
  690. 'identity' => $account,//参与方的唯一标识'208823395231'
  691. 'name' => $realName,//参与方的唯一标识'208823395231'
  692. 'identity_type' => 'ALIPAY_LOGON_ID',//参与方的标识类型,目前支持如下类型:1、ALIPAY_USER_ID 支付宝的会员ID2、ALIPAY_LOGON_ID:支付宝登录号,支持邮箱和手机号格式3、ALIPAY_OPEN_ID:支付宝openid
  693. ],//收款方信息
  694. ];
  695. $pay = $this->createPay($scene, $payType);
  696. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_pay", ['order' => $order,'params'=>$payData, 'config' => $this->config], 7200);
  697. if (empty($pay)) {
  698. $this->error = '支付宝打款失败';
  699. return false;
  700. }
  701. $result = $pay->transfer($payData);
  702. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_result", ['order' => $order,'params'=>$payData,'result'=> $result, 'config' => $this->config], 7200);
  703. $code = isset($result['code'])? intval($result['code']) : '';
  704. $msg = isset($result['sub_msg'])? trim($result['sub_msg']) : '';
  705. if($code != 10000){
  706. $this->error = $msg? $msg : '支付宝打款失败';
  707. return false;
  708. }
  709. $this->error = '支付宝打款成功';
  710. return $result;
  711. }else if($payType == 50){
  712. $this->error = '银行卡打款未开通';
  713. return false;
  714. }
  715. $this->error = '打款失败';
  716. return false;
  717. } catch (\Exception $exception) {
  718. RedisService::set("caches:payments:trabsfer:{$scene}_{$outTradeNo}_error", ['order' => $order,'msg'=>$exception->getMessage(),'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
  719. $this->error = '打款失败:'.$exception->getMessage().'或运营账户资金是否充足';
  720. return false;
  721. }
  722. }
  723. /**
  724. * 分账
  725. * @param $openid
  726. * @param $order
  727. * @param string $scene
  728. * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
  729. * @throws \Yansongda\Pay\Exception\ContainerException
  730. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  731. */
  732. public function profitsharing($openid, $order ,$scene='sharing')
  733. {
  734. $data = [
  735. 'type' => 'PERSONAL_OPENID',
  736. 'account' => $openid,
  737. 'relation_type' => 'SERVICE_PROVIDER'
  738. ];
  739. $pay = PaymentService::make()->createPay($scene, 10);
  740. $plugin = $pay->mergeCommonPlugins([
  741. AddReceiverPlugin::class
  742. ], $data);
  743. // 添加分账插件配置
  744. $pay->pay($plugin, $data);
  745. // 分账数据
  746. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : ''; // 支付交易单号
  747. $profitsharingOrderNo = isset($order['out_order_no'])? $order['out_order_no'] : ''; // 分账单号,非支付单号
  748. $body = isset($order['body'])? $order['body'] : ''; // 分账备注描述
  749. $amount = isset($order['amount'])? $order['amount'] : ''; // 分账金额
  750. $unsplit = isset($order['unsplit'])? $order['unsplit'] : true; // 是否限制只分账一次
  751. $postData = [
  752. 'transaction_id' => $transactionId,
  753. 'out_order_no' => $profitsharingOrderNo,
  754. 'receivers' => [
  755. [
  756. 'type' => 'PERSONAL_OPENID',
  757. 'account' => $openid,
  758. 'amount' => intval($amount*100), // 分账金额,单位:分
  759. 'description' => $body, //分账描述
  760. ],
  761. ],
  762. 'unfreeze_unsplit' => $unsplit,
  763. ];
  764. // 创建分账数据
  765. $createPlugin = $pay->mergeCommonPlugins([
  766. CreatePlugin::class
  767. ], $postData);
  768. // 发起分账
  769. $result = $pay->pay($createPlugin, $postData);
  770. return $result;
  771. }
  772. }