PaymentService.php 34 KB

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