PaymentService.php 37 KB

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