PaymentService.php 34 KB

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