Pay.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\service\OrderService;
  5. use app\common\service\UserService;
  6. use fast\Random;
  7. use think\Db;
  8. use addons\epay\library\Service;
  9. use think\Exception;
  10. /**
  11. * 充值配置与充值订单
  12. */
  13. class Pay extends Api
  14. {
  15. protected $noNeedLogin = ['order_notify_base'];
  16. protected $noNeedRight = ['*'];
  17. //支付订单
  18. //微信小程序、微信app下单使用。
  19. public function pay_order(){
  20. $pay_type = input('pay_type','wechat');
  21. $platform = input('platform','miniapp');
  22. $orderid = input('orderid','0');
  23. $uid = $this->auth->id;
  24. $orderinfo = Db::name('order')->where('id',$orderid)->where('user_id',$uid)->find();
  25. //创建订单
  26. $data['user_id'] = $uid;
  27. $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
  28. $data['order_amount'] = $orderinfo['pay_fee'];
  29. $data['createtime'] = time();
  30. $data['pay_type'] = $pay_type;
  31. $data['order_status'] = 0;
  32. $data['table_name'] = 'order';
  33. $data['table_id'] = $orderid;
  34. $orderid = Db::name('pay_order')->insertGetId($data);
  35. $openid = $this->auth->mini_openid;
  36. //下单
  37. $params = [
  38. 'type' => $pay_type,
  39. 'orderid' => $data['out_trade_no'],
  40. 'title' => '支付订单',
  41. 'amount' => $data['order_amount'],
  42. 'method' => $platform,
  43. 'openid' => $openid,
  44. 'notifyurl' => config('pay_notify_url').'/api/pay/order_notify_base/paytype/'.$pay_type,
  45. 'returnurl' => '',
  46. ];
  47. $res = Service::submitOrder($params);
  48. if($pay_type == 'wechat'){
  49. $this->success('success',json_decode($res,true));
  50. }else{
  51. $this->success('success',$res);
  52. }
  53. }
  54. //异步回调对外方法
  55. public function order_notify_base(){
  56. //验签
  57. $paytype = input('paytype','wechat');
  58. $func = input('func','order_notify_do');
  59. $notify_file = $this->notify_log_start($paytype);
  60. $pay = Service::checkNotify($paytype);
  61. if (!$pay) {
  62. echo '签名错误';
  63. exit;
  64. }
  65. //验证,拿订单号等信息
  66. $data = $pay->verify();
  67. $out_trade_no = $data['out_trade_no'];
  68. //订单查询
  69. $info = Db::name('pay_order')->where('out_trade_no',$out_trade_no)->find();
  70. if(empty($info)){
  71. return $pay->success()->send();
  72. exit;
  73. }
  74. if($info['order_status'] != 0)
  75. {
  76. return $pay->success()->send();
  77. exit;
  78. }
  79. //你可以在此编写订单逻辑
  80. $rs = $this->$func($out_trade_no);
  81. if($rs === false){
  82. //不论结果都应返回success
  83. return $pay->success()->send();
  84. exit;
  85. }else{
  86. //不论结果都应返回success
  87. return $pay->success()->send();
  88. exit;
  89. }
  90. //默认
  91. return $pay->success()->send();
  92. exit;
  93. }
  94. //异步逻辑
  95. private function order_notify_do($out_trade_no){
  96. Db::startTrans();
  97. $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
  98. if (empty($orderInfo)) {
  99. Db::rollback();
  100. return false;
  101. }
  102. if($orderInfo['order_status'] != 0){
  103. Db::rollback();
  104. return false;
  105. }
  106. //逻辑开始
  107. $update = [
  108. 'status'=>10,
  109. 'paytime'=>time(),
  110. 'pay_type'=>$orderInfo['pay_type'],
  111. 'pay_out_trade_no'=>$out_trade_no,
  112. ];
  113. $rs_order = Db::name('order')->where('id',$orderInfo['table_id'])->update($update);
  114. if($rs_order === false){
  115. Db::rollback();
  116. return false;
  117. }
  118. //逻辑结束
  119. //状态
  120. $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
  121. if($ros === false) {
  122. Db::rollback();
  123. return false;
  124. }
  125. //默认提交
  126. Db::commit();
  127. return true;
  128. }
  129. //异步日志
  130. private function notify_log_start($paytype = 'wechat'){
  131. //记录支付回调数据
  132. ignore_user_abort(); // run script in background
  133. set_time_limit(30);
  134. // 日志文件 start
  135. $log_base_dir = '../paylog/'.$paytype.'/';
  136. if (!is_dir($log_base_dir))
  137. {
  138. mkdir($log_base_dir, 0770, true);
  139. @chmod($log_base_dir, 0770);
  140. }
  141. $notify_file = $log_base_dir.'notify.txt';
  142. if(!file_exists($notify_file)) {
  143. @touch($notify_file);
  144. @chmod($notify_file, 0770);
  145. }
  146. if(filesize($notify_file)>5242880)//大于5M自动切换
  147. {
  148. rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
  149. }
  150. if(!file_exists($notify_file)) {
  151. @touch($notify_file);
  152. @chmod($notify_file, 0770);
  153. }
  154. // 日志文件 end
  155. //开始写入
  156. $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
  157. if($_REQUEST && $paytype == 'alipay') {
  158. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
  159. } else {
  160. $xml = file_get_contents("php://input");
  161. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
  162. $xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  163. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);
  164. }
  165. ini_set('display_errors','On');
  166. return $notify_file;
  167. }
  168. //////////////
  169. //微信小程序充值
  170. public function pay_recharge()
  171. {
  172. Db::startTrans();
  173. try {
  174. $pay_type = input('pay_type','wechat');
  175. $platform = input('platform','miniapp');
  176. $id = input('id','0');
  177. $amounts = intval(input('amounts',0));
  178. $uid = $this->auth->id;
  179. $companyId = $this->auth->company_id;
  180. if (empty($id) && empty($amounts)) {
  181. throw new Exception('参数错误');
  182. }
  183. $gift_amount = 0.00;
  184. if (!empty($id)) {//验证充值配置
  185. $where['status'] = 1;//上架
  186. $orderinfo = Db::name('recharge_config')->where('id',$id)->where($where)->find();
  187. if (empty($orderinfo)) {
  188. throw new Exception('未获取到充值套餐信息');
  189. }
  190. $order_amount = $orderinfo['price'];
  191. $gift_amount = $orderinfo['giftprice'];
  192. } else {
  193. $isInt = is_int($amounts);
  194. if (!$isInt) {
  195. throw new Exception('请输入整数');
  196. }
  197. if ($amounts < 1) {
  198. throw new Exception('充值金额有误');
  199. }
  200. $order_amount = $amounts;
  201. }
  202. //创建订单
  203. $data['company_id'] = $companyId;
  204. $data['user_id'] = $uid;
  205. $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
  206. $data['order_amount'] = $order_amount;
  207. $data['gift_amount'] = $gift_amount;
  208. $data['createtime'] = time();
  209. $data['pay_type'] = $pay_type;
  210. $data['order_status'] = 0;
  211. $data['table_name'] = 'recharge_config';
  212. $data['table_id'] = $id;
  213. $orderid = Db::name('pay_order')->insertGetId($data);
  214. $openid = $this->auth->mini_openid;
  215. $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
  216. $payTest = config('param.pay_test');
  217. $orderAmount = $payTest == 1 ? 0.01 : $data['order_amount'];
  218. //下单
  219. $params = [
  220. 'type' => $pay_type,
  221. 'orderid' => $data['out_trade_no'],
  222. 'title' => '余额充值',
  223. 'amount' => $orderAmount,
  224. 'method' => $platform,
  225. 'openid' => $openid,
  226. 'notifyurl' => $httpStr.'/api/pay/order_notify_base/paytype/'.$pay_type.'/func/recharge',
  227. 'returnurl' => '',
  228. ];
  229. $res = Service::submitOrder($params);
  230. Db::commit();
  231. if($pay_type == 'wechat'){
  232. $this->success('充值成功',json_decode($res,true));
  233. }else{
  234. $this->success('充值成功',$res);
  235. }
  236. } catch (Exception $e) {
  237. Db::rollback();
  238. $this->error($e->getMessage());
  239. }
  240. }
  241. /**
  242. * 充值到账
  243. * @param $out_trade_no
  244. * @return bool
  245. */
  246. private function recharge($out_trade_no)
  247. {
  248. Db::startTrans();
  249. $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
  250. if (empty($orderInfo)) {
  251. Db::rollback();
  252. return false;
  253. }
  254. if($orderInfo['order_status'] != 0){
  255. Db::rollback();
  256. return false;
  257. }
  258. //赠送优惠券
  259. $rg = 'recharge_gift';
  260. $c = 'coupons';
  261. $field = $rg.'.*,'.$c.'.name,'.$c.'.info,'.$c.'.days';
  262. $rechargeGiftWhere['config_id'] = $orderInfo['table_id'];
  263. $rechargeGiftWhere[$c.'.status'] = 1;
  264. $rechargeGift = Db::name($rg)->alias($rg)->field($field)
  265. ->join($c,$c.'.id = '.$rg.'.coupon_id','LEFT')->where($rechargeGiftWhere)->select();
  266. if (!empty($rechargeGift)) {
  267. $time = time();
  268. foreach ($rechargeGift as $k => $v) {
  269. $checkCode[] = Random::alnum(8);
  270. }
  271. $orderService = new OrderService();//防重复
  272. $checkCodeRes = $orderService->getCheckCoupons($checkCode);
  273. foreach ($rechargeGift as $key => $value) {
  274. $endtime = $time + 86400 * $value['days'];
  275. if ($checkCodeRes['status']) {
  276. $checkCodeStr = isset($checkCodeRes['data'][$key]) ? $checkCodeRes['data'][$key] : '';
  277. } else {
  278. $checkCodeStr = Random::alnum(8);
  279. }
  280. $userCouponsData[] = [
  281. 'check_code' => $checkCodeStr,
  282. 'user_id' => $orderInfo['user_id'],
  283. 'company_id' => $orderInfo['company_id'],
  284. 'coupons_id' => $value['coupon_id'],
  285. 'coupon_name' => $value['name'],
  286. 'coupon_info' => $value['info'],
  287. 'createtime' => $time,
  288. 'endtime' => $endtime,
  289. 'number' => $value['number'],
  290. 'remain' => $value['number'],
  291. 'payorder_id' => $orderInfo['id'],
  292. 'getfrom' => '充值赠送',
  293. ];
  294. }
  295. $userCouponsRes = Db::name('user_coupons')->insertAll($userCouponsData);
  296. if (!$userCouponsRes) {
  297. Db::rollback();
  298. return false;
  299. }
  300. }
  301. //绑定门店
  302. $userService = new UserService();
  303. $userParams = [
  304. 'user_id' => $orderInfo['user_id'],
  305. 'company_id' => $orderInfo['company_id'],
  306. 'comefrom' => '平台引流',//来源
  307. ];
  308. $userBindRes = $userService->userWallet($userParams);
  309. if (!$userBindRes['status']) {
  310. Db::rollback();
  311. return false;
  312. }
  313. $userWalletWhere['user_id'] = $orderInfo['user_id'];
  314. $userWalletWhere['company_id'] = $orderInfo['company_id'];
  315. $userWalletData = Db::name('user_wallet')->where($userWalletWhere)->find();
  316. $before = isset($userWalletData['money']) ? $userWalletData['money'] : 0.00;
  317. $changeValue = bcadd($orderInfo['order_amount'],$orderInfo['gift_amount'],2);
  318. $remain = bcadd($before,$changeValue,2);
  319. $time = time();
  320. //逻辑开始 记录充值明细
  321. $userMoneyLogData = [
  322. 'user_id' => $orderInfo['user_id'],
  323. 'company_id' => $orderInfo['company_id'],
  324. 'log_type' => 104, //日志类型 104
  325. 'before' => $before, //之前余额
  326. 'change_value' => $changeValue, //变动金额
  327. 'remain' => $remain, //剩余金额
  328. 'table' => 'pay_order', //数据来源
  329. 'table_id' => $orderInfo['id'], //数据来源ID
  330. 'remark' => '余额充值', //remark
  331. 'createtime' => $time,
  332. 'updatetime' => $time,
  333. ];
  334. $userMoneyLogRes = Db::name('user_money_log')->insertGetId($userMoneyLogData);
  335. if (!$userMoneyLogRes) {
  336. Db::rollback();
  337. return false;
  338. }
  339. //更新钱包余额
  340. $update = [
  341. 'money' => $remain,
  342. 'updatetime' => $time,
  343. ];
  344. $rs_order = Db::name('user_wallet')->where($userWalletWhere)->update($update);
  345. if(!$rs_order){
  346. Db::rollback();
  347. return false;
  348. }
  349. //商家端金额更新
  350. $companyWalletWhere['user_id'] = $orderInfo['company_id'];
  351. $companyWalletRes = Db::name('company_wallet')->where($companyWalletWhere)->find();
  352. $companyMoneyBefore = isset($companyWalletRes['money']) ? $companyWalletRes['money'] : 0.00;
  353. $companyMoneyNew = bcadd($companyMoneyBefore,$orderInfo['order_amount'],2);
  354. $companyMoneyData = [
  355. 'money' => $companyMoneyNew,
  356. ];
  357. $companyWalletRes = Db::name('company_wallet')->where($companyWalletWhere)->update($companyMoneyData);
  358. if (!$companyWalletRes) {
  359. Db::rollback();
  360. return false;
  361. }
  362. //商家端记录日志
  363. $companyMoneyLogData = [
  364. 'user_id' => $orderInfo['user_id'],//用户ID
  365. 'log_type' => 204,//日志类型
  366. 'before' => $companyMoneyBefore,//之前余额
  367. 'change_value' => $orderInfo['order_amount'],//变动金额
  368. 'remain' => $companyMoneyNew,//剩余金额
  369. 'table' => 'pay_order',//数据来源
  370. 'table_id' => $orderInfo['id'],//数据来源ID
  371. 'remark' => '充值',//备注
  372. 'createtime' => $time, //创建时间
  373. 'updatetime' => $time, //更新时间
  374. ];
  375. $companyMoneyLogRes = Db::name('company_money_log')->insertGetId($companyMoneyLogData);
  376. if (!$companyMoneyLogRes) {
  377. Db::rollback();
  378. return false;
  379. }
  380. //逻辑结束
  381. //状态
  382. $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
  383. if($ros === false) {
  384. Db::rollback();
  385. return false;
  386. }
  387. //默认提交
  388. Db::commit();
  389. return true;
  390. }
  391. /**
  392. * 购买套餐
  393. * @return void
  394. * @throws \Exception
  395. */
  396. public function package()
  397. {
  398. Db::startTrans();
  399. try {
  400. $pay_type = input('pay_type','wechat');//支付类型:wallet=余额,wechat=微信
  401. $platform = input('platform','miniapp');
  402. $id = input('package_id','0');
  403. $carId = input('car_id','0');
  404. $uid = $this->auth->id;
  405. $companyId = $this->auth->company_id;
  406. $miniOpenId = $this->auth->mini_openid;
  407. if (empty($id)) {
  408. throw new Exception('请选择套餐');
  409. }
  410. if (empty($carId)) {
  411. throw new Exception('请选择车辆');
  412. }
  413. $orderService = new OrderService();
  414. $params = [
  415. 'pay_type' => $pay_type,
  416. 'platform' => $platform,
  417. 'package_id' => $id,
  418. 'car_id' => $carId,
  419. 'user_id' => $uid,
  420. 'company_id' => $companyId,
  421. 'mini_openid' => $miniOpenId,
  422. ];
  423. $orderRes = $orderService->orderPay($params);
  424. if (!$orderRes['status']) {
  425. throw new Exception($orderRes['msg']);
  426. }
  427. $res = $orderRes['data'];
  428. Db::commit();
  429. $this->success('操作成功',$res);
  430. } catch (Exception $e) {
  431. Db::rollback();
  432. $this->error($e->getMessage());
  433. }
  434. }
  435. /**
  436. * 购买套餐回调
  437. * @param $out_trade_no
  438. * @return bool
  439. */
  440. private function package_do($out_trade_no)
  441. {
  442. Db::startTrans();
  443. $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
  444. if (empty($orderInfo)) {
  445. Db::rollback();
  446. return false;
  447. }
  448. if($orderInfo['order_status'] != 0){
  449. Db::rollback();
  450. return false;
  451. }
  452. //绑定门店
  453. $userService = new UserService();
  454. $userParams = [
  455. 'user_id' => $orderInfo['user_id'],
  456. 'company_id' => $orderInfo['company_id'],
  457. 'comefrom' => '平台引流',//来源
  458. ];
  459. $userBindRes = $userService->userWallet($userParams);
  460. if (!$userBindRes['status']) {
  461. Db::rollback();
  462. return false;
  463. }
  464. $orderService = new OrderService();
  465. $extData = json_decode($orderInfo['ext_data'], true);
  466. $carId = isset($extData['car_id']) ? $extData['car_id'] : 0;
  467. $params = [
  468. 'package_id' => $orderInfo['table_id'],
  469. 'company_id' => $orderInfo['company_id'],
  470. 'user_id' => $orderInfo['user_id'],
  471. 'car_id' => $carId,
  472. 'pay_order_id' => $orderInfo['id'],
  473. 'order_paytype' => 3,//支付方式:1=线下,2=余额,3=微信
  474. ];
  475. $orderRes = $orderService->addOrder($params);
  476. if (!$orderRes['status']) {
  477. Db::rollback();
  478. return false;
  479. }
  480. //状态
  481. $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
  482. if($ros === false) {
  483. Db::rollback();
  484. return false;
  485. }
  486. //默认提交
  487. Db::commit();
  488. return true;
  489. }
  490. }