PaymentService.php 35 KB

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