PaymentService.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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 * 1000/10),
  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:minPay_{$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:minPay_{$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 mpPay($userInfo, $order, $scene = 'store')
  213. {
  214. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  215. $openid = isset($order['openid']) ? $order['openid'] : '';
  216. if ($amount < 0) {
  217. $this->error = 2615;
  218. return false;
  219. }
  220. if (empty($openid)) {
  221. $this->error = 2614;
  222. return false;
  223. }
  224. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  225. // 是否调用过支付,是则用新的支付单号
  226. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  227. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  228. }
  229. $body = isset($order['body']) ? $order['body'] : '';
  230. $payData = [
  231. 'out_trade_no' => $outTradeNo,
  232. 'description' => $body ? $body : '订单支付',
  233. 'amount' => [
  234. 'total' => intval($amount * 1000/10),
  235. 'currency' => 'CNY'
  236. ],
  237. 'payer' => [
  238. 'openid' => $openid,
  239. ],
  240. ];
  241. // 创建支付
  242. try {
  243. $pay = $this->createPay($scene, 10, 'mp');
  244. RedisService::set("caches:payments:wechat:mp_{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  245. if (empty($pay)) {
  246. $this->error = 2616;
  247. return false;
  248. }
  249. $pay = $pay->mp($payData);
  250. } catch (\Exception $exception) {
  251. RedisService::set("caches:payments:wechat:mp_{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  252. $this->error = $exception->getMessage();
  253. return false;
  254. }
  255. if ($pay->package) {
  256. $data = [
  257. 'user_id' => $userInfo['id'],
  258. 'out_trade_no' => $outTradeNo,
  259. 'order_no' => $order['order_no'],
  260. 'params' => json_encode($pay, 256),
  261. 'total_fee' => $amount,
  262. 'pay_type' => 10,
  263. 'create_time' => time(),
  264. 'status' => 2,
  265. 'mark' => 1,
  266. ];
  267. if ($this->model->insertGetId($data)) {
  268. $this->error = 2617;
  269. return $pay;
  270. }
  271. }
  272. $this->error = 2618;
  273. return false;
  274. }
  275. /**
  276. * 微信APP支付
  277. * @param $userInfo
  278. * @param $order
  279. * @param string $scene
  280. * @return false|\Yansongda\Supports\Collection
  281. */
  282. public function wechatPay($userInfo, $order, $scene = 'store')
  283. {
  284. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  285. if ($amount < 0) {
  286. $this->error = 2615;
  287. return false;
  288. }
  289. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  290. // 是否调用过支付,是则用新的支付单号
  291. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  292. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  293. }
  294. $body = isset($order['body']) ? $order['body'] : '';
  295. $type = isset($order['type']) ? $order['type'] : 0;
  296. $payData = [
  297. 'out_trade_no' => $outTradeNo,
  298. 'attach' => "order-{$type}",
  299. 'description' => $body ? $body : '订单支付',
  300. 'amount' => [
  301. 'total' => intval($amount * 1000/10),
  302. 'currency' => 'CNY'
  303. ],
  304. ];
  305. // 创建支付
  306. try {
  307. $pay = $this->createPay($scene, 10);
  308. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  309. if (empty($pay)) {
  310. $this->error = 2616;
  311. return false;
  312. }
  313. $pay = $pay->app($payData);
  314. } catch (\Exception $exception) {
  315. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  316. $this->error = $exception->getMessage();
  317. return false;
  318. }
  319. if ($pay->prepayid) {
  320. $data = [
  321. 'user_id' => $userInfo['id'],
  322. 'out_trade_no' => $outTradeNo,
  323. 'order_no' => $order['order_no'],
  324. 'params' => json_encode($pay, 256),
  325. 'total_fee' => $amount,
  326. 'pay_type' => 10,
  327. 'create_time' => time(),
  328. 'status' => 2,
  329. 'mark' => 1,
  330. ];
  331. if ($this->model->insertGetId($data)) {
  332. $this->error = 2617;
  333. return $pay;
  334. }
  335. }
  336. $this->error = 2618;
  337. return false;
  338. }
  339. /**
  340. * 支付宝支付
  341. * @param $userInfo
  342. * @param $order
  343. * @return bool
  344. */
  345. public function aliPay($userInfo, $order, $scene = 'shop')
  346. {
  347. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  348. if ($amount < 0) {
  349. $this->error = 2615;
  350. return false;
  351. }
  352. // 是否调用过支付,是则用新的支付单号
  353. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  354. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  355. $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
  356. }
  357. $body = isset($order['body']) ? $order['body'] : '';
  358. $payData = [
  359. 'out_trade_no' => $outTradeNo,
  360. 'subject' => $body ? $body : '订单支付',
  361. 'total_amount' => $amount,
  362. ];
  363. // 创建支付
  364. $pay = $this->createPay($scene, 20);
  365. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  366. if (empty($pay)) {
  367. $this->error = 2619;
  368. return false;
  369. }
  370. $pay = $pay->app($payData);
  371. if ($pay->getStatusCode() == 200) {
  372. $data = [
  373. 'user_id' => $userInfo['id'],
  374. 'out_trade_no' => $outTradeNo,
  375. 'order_no' => $order['order_no'],
  376. 'params' => json_encode($pay, 256),
  377. 'total_fee' => $amount,
  378. 'pay_type' => 20,
  379. 'create_time' => time(),
  380. 'status' => 2,
  381. 'mark' => 1,
  382. ];
  383. if ($this->model->insertGetId($data)) {
  384. $this->error = 2620;
  385. return $pay->getBody()->getContents();
  386. }
  387. }
  388. $this->error = 2621;
  389. return false;
  390. }
  391. /**
  392. * 订单支付回调处理
  393. * @param string $scene 场景 store-购物消费,pay-充值,refund-退款
  394. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  395. * @param array $data 回调数据
  396. * @return bool
  397. */
  398. public function catchNotify($scene, $payType, $data)
  399. {
  400. $outTradeNo = '';
  401. $payTotal = 0;
  402. $transactionId = '';
  403. $payAt = '';
  404. $notifyData = [];
  405. try {
  406. // 微信支付
  407. if ($payType == 10) {
  408. $resource = isset($data['resource']) ? $data['resource'] : [];
  409. $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
  410. $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
  411. if ($tradeStatus != 'SUCCESS') {
  412. $this->error = 2622;
  413. return false;
  414. }
  415. $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
  416. $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
  417. if (empty($outTradeNo)) {
  418. $this->error = 2623;
  419. return false;
  420. }
  421. $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
  422. $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
  423. $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
  424. $notifyData = $ciphertext;
  425. if ($payTotal <= 0) {
  426. $this->error = 2624;
  427. return false;
  428. }
  429. } // 支付宝支付
  430. else if ($payType == 20) {
  431. // TRADE_SUCCESS
  432. $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
  433. if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
  434. $this->error = 2622;
  435. return false;
  436. }
  437. $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
  438. if (empty($outTradeNo)) {
  439. $this->error = 2623;
  440. return false;
  441. }
  442. $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
  443. $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
  444. $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
  445. $notifyData = $data;
  446. if ($payTotal <= 0) {
  447. $this->error = 2624;
  448. return false;
  449. }
  450. }
  451. // 支付信息
  452. $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
  453. ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
  454. ->first();
  455. $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
  456. $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
  457. $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
  458. $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
  459. $payUserId = isset($paymentInfo['user_id']) ? $paymentInfo['user_id'] : 0;
  460. if (empty($paymentInfo) || empty($orderNo) || $payUserId <= 0) {
  461. $this->error = 2625;
  462. return false;
  463. }
  464. // 验证支付状态
  465. if ($status == 1) {
  466. $this->error = 2626;
  467. return false;
  468. }
  469. // 验证支付方式
  470. if ($paymentPayType != $payType) {
  471. $this->error = 2627;
  472. return false;
  473. }
  474. if ($payTotal != $totalFee || $payTotal <= 0) {
  475. $this->error = 2628;
  476. return false;
  477. }
  478. // 删除久远旧记录
  479. $this->model->where(['mark' => 1])->where('create_time', '<=', time() - 60 * 86400)->delete();
  480. // 更新订单数据
  481. DB::beginTransaction();
  482. $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
  483. if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
  484. $this->error = 2632;
  485. DB::rollBack();
  486. return false;
  487. }
  488. /* TODO 订单验证和状态处理 */
  489. $orderInfo = [];
  490. // 商城订单支付
  491. if ($scene == 'store') {
  492. $orderInfo = OrderModel::with(['user'])->where(['order_no' => $orderNo, 'mark' => 1])
  493. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
  494. ->first();
  495. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  496. // 验证订单
  497. if (empty($orderInfo)) {
  498. DB::rollBack();
  499. $this->error = 2629;
  500. return false;
  501. }
  502. // 订单状态
  503. if ($orderStatus != 1) {
  504. DB::rollBack();
  505. $this->error = 2630;
  506. return false;
  507. }
  508. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  509. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  510. $this->error = 2633;
  511. DB::rollBack();
  512. return false;
  513. }
  514. }
  515. // 生活充值
  516. else if ($scene == 'pay') {
  517. $orderInfo = PayOrdersModel::with(['meal'])->where(['order_no' => $orderNo, 'mark' => 1])
  518. ->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'])
  519. ->first();
  520. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  521. // 验证订单
  522. if (empty($orderInfo)) {
  523. DB::rollBack();
  524. $this->error = 2629;
  525. return false;
  526. }
  527. // 订单状态
  528. if ($orderStatus != 1) {
  529. DB::rollBack();
  530. $this->error = 2630;
  531. return false;
  532. }
  533. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  534. if (!PayOrdersModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  535. $this->error = 2633;
  536. DB::rollBack();
  537. return false;
  538. }
  539. }
  540. // 退款
  541. else if ($scene == 'refund') {
  542. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  543. ->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'])
  544. ->first();
  545. $refundRemark = isset($orderInfo['refund_remark']) ? $orderInfo['refund_remark'] : 'refund_remark';
  546. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  547. // 验证订单
  548. if (empty($orderInfo)) {
  549. DB::rollBack();
  550. $this->error = 2629;
  551. return false;
  552. }
  553. // 订单状态
  554. if ($orderStatus != 2) {
  555. DB::rollBack();
  556. $this->error = 2639;
  557. return false;
  558. }
  559. // 订单打款状态
  560. if ($orderStatus == 1) {
  561. DB::rollBack();
  562. $this->error = 2630;
  563. return false;
  564. }
  565. $updateData = ['refund_status' => 1, 'refund_remark' => $refundRemark ? $refundRemark . ' 已退款成功' : '已退款成功', 'update_time' => time()];
  566. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  567. $this->error = 2633;
  568. DB::rollBack();
  569. return false;
  570. }
  571. }
  572. // TODO 场景业务回调处理
  573. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  574. $this->saveLog("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data]);
  575. switch ($scene) {
  576. case 'store': //
  577. break;
  578. case 'pay': //
  579. // 调起 接口充值
  580. $orderId = isset($orderInfo['order_id'])? $orderInfo['order_id'] : 0;
  581. $productId = isset($orderInfo['product_id'])? $orderInfo['product_id'] : '';
  582. $orderNo = isset($orderInfo['order_no'])? $orderInfo['order_no'] : '';
  583. $account = isset($orderInfo['account'])? $orderInfo['account'] : '';
  584. $total = isset($orderInfo['pay_money'])? $orderInfo['pay_money'] : 0;
  585. $payTotal = isset($orderInfo['pay_total'])? $orderInfo['pay_total'] : 0;
  586. $mealData = isset($orderInfo['meal'])? $orderInfo['meal'] : [];
  587. $orderType = isset($orderInfo['type'])?$orderInfo['type']:1;
  588. $electricType = isset($mealData['electric_type'])?$mealData['electric_type']:0;
  589. $city = isset($orderInfo['city'])?$orderInfo['city']:'';
  590. $amount = $total;
  591. $params = [
  592. 'price'=>$payTotal,
  593. 'ytype'=>isset($orderInfo['ytype'])?$orderInfo['ytype']:0,
  594. 'id_card_no'=>isset($orderInfo['id_card_no'])?$orderInfo['id_card_no']:'',
  595. 'area'=>isset($orderInfo['area'])?$orderInfo['area']:'',
  596. ];
  597. if($orderType==2 && $electricType!= 3 && $city){
  598. $params['city'] = $city;
  599. }
  600. $result = DyrPayService::make()->recharge($orderNo, $account, $productId, $amount, $params);
  601. $errno = isset($result['errno'])?$result['errno'] : -1;
  602. $errmsg = isset($result['errmsg'])?$result['errmsg'] : '';
  603. $res = isset($result['data'])?$result['data']:[];
  604. $order_number = isset($res['order_number'])?$res['order_number']:'';
  605. if(empty($result) || $errno != 0 || empty($order_number)){
  606. $this->error = '充值调用失败:'.$errmsg;
  607. // 退款
  608. $orderInfo['money'] = $payTotal;
  609. $orderInfo['transaction_id'] = $transactionId;
  610. $orderInfo['remark'] = '充值失败退款';
  611. $refundStatus = PaymentService::make()->refund($orderInfo,'pay');
  612. $updateData = ['refund_status'=> $refundStatus?1:3,'status'=>5,'transaction_id'=>$transactionId,'pay_at'=>$payAt,'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()];
  613. $this->saveLog("caches:payments:notify_{$scene}:pay_failed_{$orderNo}_{$orderUserId}", ['error'=>$this->error,'update'=>$updateData,'order' => $orderInfo,'result'=>$result, 'notify' => $data]);
  614. if(!PayOrdersModel::where(['id'=>$orderId])->update($updateData)){
  615. $this->error = '订单退款状态更新错误~';
  616. }
  617. DB::commit();
  618. return false;
  619. }
  620. $updateData = ['status'=>3,'result'=>json_encode(['amount'=>$amount,'params'=>$params,'result'=>$result],256),'out_trade_no'=>$order_number,'update_time'=>time()+1];
  621. $this->saveLog("caches:payments:notify_{$scene}:pay_success_{$orderNo}_{$orderUserId}", ['error'=> '充值调用成功','id'=>$orderId,'update'=>$updateData,'order' => $orderInfo,'result'=>$result, 'notify' => $data]);
  622. if(!PayOrdersModel::where(['id'=>$orderId])->update($updateData)){
  623. DB::commit();
  624. $this->error = '更新充值订单失败';
  625. $this->saveLog("caches:payments:notify_{$scene}:pay_failed_{$orderNo}_{$orderUserId}", ['error'=>$this->error,'update'=>$updateData,'order' => $orderInfo,'result'=>$result, 'notify' => $data]);
  626. return false;
  627. }
  628. DB::commit();
  629. return true;
  630. default:
  631. break;
  632. }
  633. $this->error = '回调处理成功';
  634. DB::commit();
  635. return true;
  636. } catch (\Exception $exception) {
  637. $this->error = $exception->getMessage();
  638. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
  639. return false;
  640. }
  641. }
  642. /**
  643. * 充值回调
  644. * @param $productId
  645. * @param $data
  646. * @return bool
  647. * @throws \Yansongda\Pay\Exception\ContainerException
  648. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  649. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  650. */
  651. public function catchPayNotify($productId, $data)
  652. {
  653. $out_trade_num = isset($data['out_trade_num'])?$data['out_trade_num']:'';
  654. $state = isset($data['state'])? $data['state'] : 0;
  655. $charge_kami = isset($data['charge_kami'])?$data['charge_kami'] : '';
  656. $remark = isset($data['remark'])?$data['remark'] : '';
  657. $amount = isset($data['charge_amount'])?floatval($data['charge_amount']) : 0;
  658. if($state==0){
  659. $this->error = '充值处理中~';
  660. return false;
  661. }
  662. $orderInfo = PayOrdersModel::with(['user'])->where(['order_no'=>$out_trade_num,'mark'=>1])->first();
  663. $orderId = isset($orderInfo['id'])? $orderInfo['id'] : 0;
  664. $orderUserId = isset($orderInfo['user_id'])? $orderInfo['user_id'] : 0;
  665. $status = isset($orderInfo['status'])? $orderInfo['status'] : 0;
  666. $total = isset($orderInfo['pay_total'])? $orderInfo['pay_total'] : 0;
  667. $recBonusId = isset($orderInfo['rec_bonus_id'])?$orderInfo['rec_bonus_id'] : 0;
  668. $recBonus = isset($orderInfo['rec_bonus'])?$orderInfo['rec_bonus'] : 0;
  669. if(empty($orderInfo) || $orderId<=0 || $total<=0){
  670. $this->error = '充值订单不存在';
  671. $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}_error", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
  672. return false;
  673. }
  674. if($status!=3){
  675. $this->error = '充值订单状态错误,状态非充值中';
  676. $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}_error", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
  677. return false;
  678. }
  679. // 成功
  680. $status = 4;
  681. $refundAmount = 0;
  682. if($state == 1){
  683. $this->error = '充值成功~';
  684. }
  685. //部分成功,退部分
  686. else if($state == 3) {
  687. $status = 6;
  688. $refundAmount = moneyFormat($total - $amount,2);
  689. $this->error = '充值成功部分退款';
  690. }
  691. //失败,退全款
  692. else if(in_array($state,[-1,2])){
  693. $status = 5;
  694. $refundAmount = $total;
  695. $this->error = '充值失败退款';
  696. }
  697. // 更新订单状态
  698. DB::beginTransaction();
  699. $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
  700. if(!PayOrdersModel::where(['id'=>$orderId])->update(['status'=>$status,'charge_kami'=>$charge_kami,'refund_status'=>$status!=4?2:0,'charge_amount'=>$amount,'update_time'=>time()])){
  701. $this->error = '更新订单状态错误~';
  702. DB::rollBack();
  703. return false;
  704. }
  705. // 是否要退款
  706. if($refundAmount>0){
  707. $orderInfo['money'] = $refundAmount;
  708. $orderInfo['remark'] = $this->error;
  709. $orderInfo['out_trade_no'] = '';
  710. $refundStatus = PaymentService::make()->refund($orderInfo,'pay');
  711. 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()])){
  712. $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}_error", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
  713. $this->error = '订单退款状态更新错误~';
  714. DB::rollBack();
  715. return false;
  716. }
  717. }
  718. // 订单完成,代理收益结算
  719. if($status == 4 && $amount>0)
  720. {
  721. // 代理佣金结算
  722. $result = SettleService::make()->agentBonus($orderUserId, $recBonus, $orderInfo, $recBonusId);
  723. if ($result<0) {
  724. DB::rollBack();
  725. $this->error = SettleService::make()->getError();
  726. $this->saveLog("caches:settle:{$out_trade_num}:agent_{$orderUserId}_error",SettleService::make()->getError());
  727. return false;
  728. }
  729. $this->saveLog("caches:settle:{$out_trade_num}:agent_{$orderUserId}",['msg'=>SettleService::make()->getError(),'result'=>$result]);
  730. // 更新订单结算状态
  731. if(!$this->model->where(['id'=>$orderId])->update(['bonus_settle'=>1,'update_time'=>time()])){
  732. DB::rollBack();
  733. $this->error = '收益结算状态更新失败';
  734. return false;
  735. }
  736. }
  737. DB::commit();
  738. $this->error = '充值订单处理成功~';
  739. return ['id'=>$orderId,'amount'=>$amount,'status'=>$status,'refund'=>$refundAmount];
  740. }
  741. /**
  742. * 日志
  743. * @param $key
  744. * @param $data
  745. */
  746. public function saveLog($key, $data)
  747. {
  748. if(env('APP_DEBUG')){
  749. RedisService::set($key,$data,env('DEBUG_EXPIRE',7200));
  750. }
  751. }
  752. /**
  753. * 退款请求
  754. * @param $order
  755. * @param string $scene
  756. * @return bool
  757. * @throws \Yansongda\Pay\Exception\ContainerException
  758. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  759. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  760. */
  761. public function refund($order, $scene = 'store')
  762. {
  763. $money = isset($order['money']) ? $order['money'] : 0;
  764. $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
  765. $orderNo = isset($order['order_no']) ? $order['order_no'] : '';
  766. $outTradeNo = isset($order['out_trade_no']) ? $order['out_trade_no'] : '';
  767. $transactionId = isset($order['transaction_id']) ? $order['transaction_id'] : '';
  768. $remark = isset($order['remark']) && $order['remark'] ? $order['remark'] : '退款';
  769. $pay = PaymentService::make()->createPay($scene, $payType);
  770. if (empty($pay)) {
  771. DB::rollBack();
  772. $this->error = '创建退款支付失败';
  773. return false;
  774. }
  775. // 保证金退款处理
  776. $refundStatus = false;
  777. switch ($payType) {
  778. case 10: // 微信支付
  779. $data = [
  780. 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
  781. 'out_refund_no' => get_order_num('RF'),
  782. 'transaction_id' => $transactionId,
  783. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  784. 'reason' => $remark,
  785. 'amount' => [
  786. 'refund' => intval($money * 100),
  787. 'total' => intval($money * 100),
  788. 'currency' => 'CNY',
  789. ],
  790. ];
  791. // 请求退款
  792. $pay = $pay->refund($data);
  793. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data, 'pay' => $pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  794. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  795. $refundStatus = true;
  796. } else {
  797. DB::rollBack();
  798. $this->errorData = $data;
  799. $this->error = '微信退款处理失败:'.$pay->message;
  800. return false;
  801. }
  802. break;
  803. case 20: // 支付宝
  804. $data = [
  805. 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
  806. 'trade_no' => $transactionId,
  807. 'refund_amount' => $money,
  808. 'query_options' => ['deposit_back_info'],
  809. 'refund_reason' => $remark,
  810. ];
  811. $payResult = $pay->refund($data);
  812. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  813. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  814. $refundStatus = true;
  815. } else {
  816. $this->errorData = $data;
  817. $this->error = '支付宝退款处理失败:'.$payResult->code;
  818. return false;
  819. }
  820. break;
  821. default:
  822. $this->error = '退款支付类型错误';
  823. return false;
  824. }
  825. $this->error = '退款处理成功';
  826. return $refundStatus;
  827. }
  828. /**
  829. * 企业打款到零钱(商家转账)
  830. * @param $order 订单参数:order_no-单号,pay_money-打款金额,account-打款账号(微信openid或支付宝账号),body-打款备注
  831. * @param string $scene
  832. * @param int $payType
  833. * @return bool
  834. */
  835. public function transfer($order, $scene='withdraw', $payType=10)
  836. {
  837. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('WD');
  838. $body = isset($order['body']) ? $order['body'] : '';
  839. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  840. $account = isset($order['account']) ? $order['account'] : ''; // 微信openid或支付宝账号
  841. $realName = isset($order['real_name']) ? $order['real_name'] : ''; // 实名
  842. if ($amount < 0) {
  843. $this->error = '打款金额错误';
  844. return false;
  845. }
  846. if(empty($account)){
  847. $this->error = $payType == 10? '缺少微信OPENID' : '支付宝账户不为空';
  848. return false;
  849. }
  850. // 创建支付
  851. $result = [];
  852. try {
  853. $config = ConfigService::make()->getConfigOptionByGroup(6);
  854. if ($payType == 10) {
  855. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  856. $payData = [
  857. '_action' => 'mch_transfer', // 微信官方老版本下线后,此部分可省略
  858. 'appid' => $appid,
  859. 'out_bill_no' => $outTradeNo,
  860. 'transfer_scene_id' => '1000',
  861. 'openid' => $account,
  862. 'transfer_amount' => intval($amount * 100),
  863. 'transfer_remark' => $body?$body:'收入提现',
  864. 'user_recv_perception' => $body? $body : '收入提现',
  865. "transfer_scene_report_infos"=> [
  866. [
  867. "info_type" => "活动名称",
  868. "info_content" => "收入提现"
  869. ],
  870. [
  871. "info_type" => "奖励说明",
  872. "info_content" => "用户收入提现"
  873. ]
  874. ],
  875. ];
  876. $pay = $this->createPay($scene, $payType);
  877. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_pay", ['order' => $order,'params'=>$payData,'pay'=>$pay, 'config' => $this->config], 7200);
  878. if (empty($pay)) {
  879. $this->error = '微信打款失败';
  880. return false;
  881. }
  882. $result = $pay->transfer($payData);
  883. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_result", ['order' => $order,'params'=>$payData,'result'=> $result, 'config' => $this->config], 7200);
  884. $msg = isset($result['message'])? trim($result['message']) : '';
  885. $batchId = isset($result['batch_id'])? trim($result['batch_id']) : '';
  886. if(empty($batchId)){
  887. $this->error = $msg? $msg : '微信打款失败';
  888. return false;
  889. }
  890. $this->error = '微信打款成功';
  891. return ['order_no'=> $outTradeNo,'batch_id'=> $batchId,'result'=>$result];
  892. }else if ($payType == 20){
  893. $payData = [
  894. 'out_biz_no' => $outTradeNo,//商户订单号,内部订单号
  895. 'trans_amount' => $amount, //订单总金额,单位为元,精确到小数点后两位,
  896. 'biz_scene' => 'DIRECT_TRANSFER', //描述特定的业务场景,可传的参数如下:DIRECT_TRANSFER:单笔无密转账到支付宝,B2C现金红包PERSONAL_COLLECTION:C2C现金红包-领红包
  897. 'product_code' => 'TRANS_ACCOUNT_NO_PWD', //业务产品码,单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD;收发现金红包固定为:STD_RED_PACKET;
  898. 'remark' => $body? $body : '提现',//业务备注
  899. 'order_title' => $body? $body : '提现',//转账业务的标题,用于在支付宝用户的账单里显示
  900. 'payee_info' => [
  901. 'identity' => $account,//参与方的唯一标识'208823395231'
  902. 'name' => $realName,//参与方的唯一标识'208823395231'
  903. 'identity_type' => 'ALIPAY_LOGON_ID',//参与方的标识类型,目前支持如下类型:1、ALIPAY_USER_ID 支付宝的会员ID2、ALIPAY_LOGON_ID:支付宝登录号,支持邮箱和手机号格式3、ALIPAY_OPEN_ID:支付宝openid
  904. ],//收款方信息
  905. ];
  906. $pay = $this->createPay($scene, $payType);
  907. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_pay", ['order' => $order,'params'=>$payData, 'config' => $this->config], 7200);
  908. if (empty($pay)) {
  909. $this->error = '支付宝打款失败';
  910. return false;
  911. }
  912. $result = $pay->transfer($payData);
  913. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_result", ['order' => $order,'params'=>$payData,'result'=> $result, 'config' => $this->config], 7200);
  914. $code = isset($result['code'])? intval($result['code']) : '';
  915. $msg = isset($result['sub_msg'])? trim($result['sub_msg']) : '';
  916. if($code != 10000){
  917. $this->error = $msg? $msg : '支付宝打款失败';
  918. return false;
  919. }
  920. $this->error = '支付宝打款成功';
  921. return $result;
  922. }else if($payType == 50){
  923. $this->error = '银行卡打款未开通';
  924. return false;
  925. }
  926. $this->error = '打款失败';
  927. return false;
  928. } catch (\Exception $exception) {
  929. RedisService::set("caches:payments:trabsfer:{$scene}_{$outTradeNo}_error", ['order' => $order,'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
  930. $this->error = $exception->getMessage();
  931. return false;
  932. }
  933. }
  934. }