123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\common\service\OrderService;
- use app\common\service\UserService;
- use fast\Random;
- use think\Db;
- use addons\epay\library\Service;
- use think\Exception;
- /**
- * 充值配置与充值订单
- */
- class Pay extends Api
- {
- protected $noNeedLogin = ['order_notify_base'];
- protected $noNeedRight = ['*'];
- //支付订单
- //微信小程序、微信app下单使用。
- public function pay_order(){
- $pay_type = input('pay_type','wechat');
- $platform = input('platform','miniapp');
- $orderid = input('orderid','0');
- $uid = $this->auth->id;
- $orderinfo = Db::name('order')->where('id',$orderid)->where('user_id',$uid)->find();
- //创建订单
- $data['user_id'] = $uid;
- $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
- $data['order_amount'] = $orderinfo['pay_fee'];
- $data['createtime'] = time();
- $data['pay_type'] = $pay_type;
- $data['order_status'] = 0;
- $data['table_name'] = 'order';
- $data['table_id'] = $orderid;
- $orderid = Db::name('pay_order')->insertGetId($data);
- $openid = $this->auth->mini_openid;
- //下单
- $params = [
- 'type' => $pay_type,
- 'orderid' => $data['out_trade_no'],
- 'title' => '支付订单',
- 'amount' => $data['order_amount'],
- 'method' => $platform,
- 'openid' => $openid,
- 'notifyurl' => config('pay_notify_url').'/api/pay/order_notify_base/paytype/'.$pay_type,
- 'returnurl' => '',
- ];
- $res = Service::submitOrder($params);
- if($pay_type == 'wechat'){
- $this->success('success',json_decode($res,true));
- }else{
- $this->success('success',$res);
- }
- }
- //异步回调对外方法
- public function order_notify_base(){
- //验签
- $paytype = input('paytype','wechat');
- $func = input('func','order_notify_do');
- $notify_file = $this->notify_log_start($paytype);
- $pay = Service::checkNotify($paytype);
- if (!$pay) {
- echo '签名错误';
- exit;
- }
- //验证,拿订单号等信息
- $data = $pay->verify();
- $out_trade_no = $data['out_trade_no'];
- //订单查询
- $info = Db::name('pay_order')->where('out_trade_no',$out_trade_no)->find();
- if(empty($info)){
- return $pay->success()->send();
- exit;
- }
- if($info['order_status'] != 0)
- {
- return $pay->success()->send();
- exit;
- }
- //你可以在此编写订单逻辑
- $rs = $this->$func($out_trade_no);
- if($rs === false){
- //不论结果都应返回success
- return $pay->success()->send();
- exit;
- }else{
- //不论结果都应返回success
- return $pay->success()->send();
- exit;
- }
- //默认
- return $pay->success()->send();
- exit;
- }
- //异步逻辑
- private function order_notify_do($out_trade_no){
- Db::startTrans();
- $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
- if (empty($orderInfo)) {
- Db::rollback();
- return false;
- }
- if($orderInfo['order_status'] != 0){
- Db::rollback();
- return false;
- }
- //逻辑开始
- $update = [
- 'status'=>10,
- 'paytime'=>time(),
- 'pay_type'=>$orderInfo['pay_type'],
- 'pay_out_trade_no'=>$out_trade_no,
- ];
- $rs_order = Db::name('order')->where('id',$orderInfo['table_id'])->update($update);
- if($rs_order === false){
- Db::rollback();
- return false;
- }
- //逻辑结束
- //状态
- $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
- if($ros === false) {
- Db::rollback();
- return false;
- }
- //默认提交
- Db::commit();
- return true;
- }
- //异步日志
- private function notify_log_start($paytype = 'wechat'){
- //记录支付回调数据
- ignore_user_abort(); // run script in background
- set_time_limit(30);
- // 日志文件 start
- $log_base_dir = '../paylog/'.$paytype.'/';
- if (!is_dir($log_base_dir))
- {
- mkdir($log_base_dir, 0770, true);
- @chmod($log_base_dir, 0770);
- }
- $notify_file = $log_base_dir.'notify.txt';
- if(!file_exists($notify_file)) {
- @touch($notify_file);
- @chmod($notify_file, 0770);
- }
- if(filesize($notify_file)>5242880)//大于5M自动切换
- {
- rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
- }
- if(!file_exists($notify_file)) {
- @touch($notify_file);
- @chmod($notify_file, 0770);
- }
- // 日志文件 end
- //开始写入
- $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
- if($_REQUEST && $paytype == 'alipay') {
- file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
- } else {
- $xml = file_get_contents("php://input");
- file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
- $xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
- file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);
- }
- ini_set('display_errors','On');
- return $notify_file;
- }
- //////////////
- //微信小程序充值
- public function pay_recharge()
- {
- Db::startTrans();
- try {
- $pay_type = input('pay_type','wechat');
- $platform = input('platform','miniapp');
- $id = input('id','0');
- $amounts = intval(input('amounts',0));
- $uid = $this->auth->id;
- $companyId = $this->auth->company_id;
- if (empty($id) && empty($amounts)) {
- throw new Exception('参数错误');
- }
- $gift_amount = 0.00;
- if (!empty($id)) {//验证充值配置
- $where['status'] = 1;//上架
- $orderinfo = Db::name('recharge_config')->where('id',$id)->where($where)->find();
- if (empty($orderinfo)) {
- throw new Exception('未获取到充值套餐信息');
- }
- $order_amount = $orderinfo['price'];
- $gift_amount = $orderinfo['giftprice'];
- } else {
- $isInt = is_int($amounts);
- if (!$isInt) {
- throw new Exception('请输入整数');
- }
- if ($amounts < 1) {
- throw new Exception('充值金额有误');
- }
- $order_amount = $amounts;
- }
- //创建订单
- $data['company_id'] = $companyId;
- $data['user_id'] = $uid;
- $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
- $data['order_amount'] = $order_amount;
- $data['gift_amount'] = $gift_amount;
- $data['createtime'] = time();
- $data['pay_type'] = $pay_type;
- $data['order_status'] = 0;
- $data['table_name'] = 'recharge_config';
- $data['table_id'] = $id;
- $orderid = Db::name('pay_order')->insertGetId($data);
- $openid = $this->auth->mini_openid;
- $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
- $payTest = config('param.pay_test');
- $orderAmount = $payTest == 1 ? 0.01 : $data['order_amount'];
- //下单
- $params = [
- 'type' => $pay_type,
- 'orderid' => $data['out_trade_no'],
- 'title' => '余额充值',
- 'amount' => $orderAmount,
- 'method' => $platform,
- 'openid' => $openid,
- 'notifyurl' => $httpStr.'/api/pay/order_notify_base/paytype/'.$pay_type.'/func/recharge',
- 'returnurl' => '',
- ];
- $res = Service::submitOrder($params);
- Db::commit();
- if($pay_type == 'wechat'){
- $this->success('充值成功',json_decode($res,true));
- }else{
- $this->success('充值成功',$res);
- }
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- }
- /**
- * 充值到账
- * @param $out_trade_no
- * @return bool
- */
- private function recharge($out_trade_no)
- {
- Db::startTrans();
- $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
- if (empty($orderInfo)) {
- Db::rollback();
- return false;
- }
- if($orderInfo['order_status'] != 0){
- Db::rollback();
- return false;
- }
- //赠送优惠券
- $rg = 'recharge_gift';
- $c = 'coupons';
- $field = $rg.'.*,'.$c.'.name,'.$c.'.info,'.$c.'.days';
- $rechargeGiftWhere['config_id'] = $orderInfo['table_id'];
- $rechargeGiftWhere[$c.'.status'] = 1;
- $rechargeGift = Db::name($rg)->alias($rg)->field($field)
- ->join($c,$c.'.id = '.$rg.'.coupon_id','LEFT')->where($rechargeGiftWhere)->select();
- if (!empty($rechargeGift)) {
- $time = time();
- foreach ($rechargeGift as $k => $v) {
- $checkCode[] = Random::alnum(8);
- }
- $orderService = new OrderService();//防重复
- $checkCodeRes = $orderService->getCheckCoupons($checkCode);
- foreach ($rechargeGift as $key => $value) {
- $endtime = $time + 86400 * $value['days'];
- if ($checkCodeRes['status']) {
- $checkCodeStr = isset($checkCodeRes['data'][$key]) ? $checkCodeRes['data'][$key] : '';
- } else {
- $checkCodeStr = Random::alnum(8);
- }
- $userCouponsData[] = [
- 'check_code' => $checkCodeStr,
- 'user_id' => $orderInfo['user_id'],
- 'company_id' => $orderInfo['company_id'],
- 'coupons_id' => $value['coupon_id'],
- 'coupon_name' => $value['name'],
- 'coupon_info' => $value['info'],
- 'createtime' => $time,
- 'endtime' => $endtime,
- 'number' => $value['number'],
- 'remain' => $value['number'],
- 'payorder_id' => $orderInfo['id'],
- 'getfrom' => '充值赠送',
- ];
- }
- $userCouponsRes = Db::name('user_coupons')->insertAll($userCouponsData);
- if (!$userCouponsRes) {
- Db::rollback();
- return false;
- }
- }
- //绑定门店
- $userService = new UserService();
- $userParams = [
- 'user_id' => $orderInfo['user_id'],
- 'company_id' => $orderInfo['company_id'],
- 'comefrom' => '平台引流',//来源
- ];
- $userBindRes = $userService->userWallet($userParams);
- if (!$userBindRes['status']) {
- Db::rollback();
- return false;
- }
- $userWalletWhere['user_id'] = $orderInfo['user_id'];
- $userWalletWhere['company_id'] = $orderInfo['company_id'];
- $userWalletData = Db::name('user_wallet')->where($userWalletWhere)->find();
- $before = isset($userWalletData['money']) ? $userWalletData['money'] : 0.00;
- $changeValue = bcadd($orderInfo['order_amount'],$orderInfo['gift_amount'],2);
- $remain = bcadd($before,$changeValue,2);
- $time = time();
- //逻辑开始 记录充值明细
- $userMoneyLogData = [
- 'user_id' => $orderInfo['user_id'],
- 'company_id' => $orderInfo['company_id'],
- 'log_type' => 104, //日志类型 104
- 'before' => $before, //之前余额
- 'change_value' => $changeValue, //变动金额
- 'remain' => $remain, //剩余金额
- 'table' => 'pay_order', //数据来源
- 'table_id' => $orderInfo['id'], //数据来源ID
- 'remark' => '余额充值', //remark
- 'createtime' => $time,
- 'updatetime' => $time,
- ];
- $userMoneyLogRes = Db::name('user_money_log')->insertGetId($userMoneyLogData);
- if (!$userMoneyLogRes) {
- Db::rollback();
- return false;
- }
- //更新钱包余额
- $update = [
- 'money' => $remain,
- 'updatetime' => $time,
- ];
- $rs_order = Db::name('user_wallet')->where($userWalletWhere)->update($update);
- if(!$rs_order){
- Db::rollback();
- return false;
- }
- //商家端金额更新
- $companyWalletWhere['user_id'] = $orderInfo['company_id'];
- $companyWalletRes = Db::name('company_wallet')->where($companyWalletWhere)->find();
- $companyMoneyBefore = isset($companyWalletRes['money']) ? $companyWalletRes['money'] : 0.00;
- $companyMoneyNew = bcadd($companyMoneyBefore,$orderInfo['order_amount'],2);
- $companyMoneyData = [
- 'money' => $companyMoneyNew,
- ];
- $companyWalletRes = Db::name('company_wallet')->where($companyWalletWhere)->update($companyMoneyData);
- if (!$companyWalletRes) {
- Db::rollback();
- return false;
- }
- //商家端记录日志
- $companyMoneyLogData = [
- 'user_id' => $orderInfo['user_id'],//用户ID
- 'log_type' => 204,//日志类型
- 'before' => $companyMoneyBefore,//之前余额
- 'change_value' => $orderInfo['order_amount'],//变动金额
- 'remain' => $companyMoneyNew,//剩余金额
- 'table' => 'pay_order',//数据来源
- 'table_id' => $orderInfo['id'],//数据来源ID
- 'remark' => '充值',//备注
- 'createtime' => $time, //创建时间
- 'updatetime' => $time, //更新时间
- ];
- $companyMoneyLogRes = Db::name('company_money_log')->insertGetId($companyMoneyLogData);
- if (!$companyMoneyLogRes) {
- Db::rollback();
- return false;
- }
- //逻辑结束
- //状态
- $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
- if($ros === false) {
- Db::rollback();
- return false;
- }
- //默认提交
- Db::commit();
- return true;
- }
- /**
- * 购买套餐
- * @return void
- * @throws \Exception
- */
- public function package()
- {
- Db::startTrans();
- try {
- $pay_type = input('pay_type','wechat');//支付类型:wallet=余额,wechat=微信
- $platform = input('platform','miniapp');
- $id = input('package_id','0');
- $carId = input('car_id','0');
- $uid = $this->auth->id;
- $companyId = $this->auth->company_id;
- $miniOpenId = $this->auth->mini_openid;
- if (empty($id)) {
- throw new Exception('请选择套餐');
- }
- if (empty($carId)) {
- throw new Exception('请选择车辆');
- }
- $orderService = new OrderService();
- $params = [
- 'pay_type' => $pay_type,
- 'platform' => $platform,
- 'package_id' => $id,
- 'car_id' => $carId,
- 'user_id' => $uid,
- 'company_id' => $companyId,
- 'mini_openid' => $miniOpenId,
- ];
- $orderRes = $orderService->orderPay($params);
- if (!$orderRes['status']) {
- throw new Exception($orderRes['msg']);
- }
- $res = $orderRes['data'];
- Db::commit();
- $this->success('操作成功',$res);
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- }
- /**
- * 购买套餐回调
- * @param $out_trade_no
- * @return bool
- */
- private function package_do($out_trade_no)
- {
- Db::startTrans();
- $orderInfo = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();
- if (empty($orderInfo)) {
- Db::rollback();
- return false;
- }
- if($orderInfo['order_status'] != 0){
- Db::rollback();
- return false;
- }
- //绑定门店
- $userService = new UserService();
- $userParams = [
- 'user_id' => $orderInfo['user_id'],
- 'company_id' => $orderInfo['company_id'],
- 'comefrom' => '平台引流',//来源
- ];
- $userBindRes = $userService->userWallet($userParams);
- if (!$userBindRes['status']) {
- Db::rollback();
- return false;
- }
- $orderService = new OrderService();
- $extData = json_decode($orderInfo['ext_data'], true);
- $carId = isset($extData['car_id']) ? $extData['car_id'] : 0;
- $params = [
- 'package_id' => $orderInfo['table_id'],
- 'company_id' => $orderInfo['company_id'],
- 'user_id' => $orderInfo['user_id'],
- 'car_id' => $carId,
- 'pay_order_id' => $orderInfo['id'],
- 'order_paytype' => 3,//支付方式:1=线下,2=余额,3=微信
- ];
- $orderRes = $orderService->addOrder($params);
- if (!$orderRes['status']) {
- Db::rollback();
- return false;
- }
- //状态
- $ros = Db::name('pay_order')->where(['out_trade_no' => $out_trade_no])->update(['order_status'=>1,'notifytime'=>time()]);
- if($ros === false) {
- Db::rollback();
- return false;
- }
- //默认提交
- Db::commit();
- return true;
- }
- }
|