Pay.php 18 KB

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