php 微信服务号登录授权

  <?php
    'weixin_api' => [        
    'url' => 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code',    
    'get_access_url' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET',      
    'get_jsticket_access_url' => 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi',     
    'get_userinfo' => 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID',       
    'get_userinfo_userinfo' => 'https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN',     
    'get_down_weixinuploadimg_url' => 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID',    
    'appid' => 'wx34ac8393c93bc0d7',    # 公众号appid       
    'secret' => 'd3b37cbdd759ad3ebc544ddfd539bee2',  # 公众号秘钥      
    'mchid' => '1557758981',   # 商户号      
    'apikey' => 'fglhltankroruroHufei73vkgrirvklr',     # 商户ID
    'notify' => 'http://zyapi.xiaoluge.top/paymenting/notify',        
    'finalorder' => 'http://zyapi.xiaoluge.top/paymenting/isfinalorderpayment',       
    'qrcodeurl' => 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN',        //买卖成功通知模板id       
    'wx_auction_id' => '2xKCNx58_UvwfN4LtPl_yPkl9ETmgLyF_R46VgOdDCY',        //商品详情url      
    'goods_detal_url' => 'http://zywap.xiaoluge.top/#/index/',        //实名认证url     
    'realname_url' => 'http://zywap.xiaoluge.top/#/user/authentication/authentication_index',   
   ],
 public function getToken(Request $request)
    {
        $code = $request->param('code');
        $state = $request->param('state');
        $config = Config::get('weixin_api');
        $url = str_replace('APPID', $config['appid'], $config['url']);
        $url = str_replace('SECRET', $config['secret'], $url);
        $url = str_replace('CODE', $code, $url);
        $client = new Client([
            'timeout' => 2.0,
        ]);
        $header = ['Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Credentials' => true, 'Access-Control-Allow-Methods' => 'GET, PUT, POST, DELETE'];
        try {
            // 获取open_id
            $requestobj = new GuRequest('get', $url);
            $response = $client->send($requestobj, ['timeout' => 2, 'verify' => false]);
            $body = $response->getBody();
            $remainingBytes = $body->getContents();
            $access_toke_data = json_decode($remainingBytes, true);
        } catch (\Exception $e) {
            $this->loginError(['nickname'=>'XX','headimgurl'=>'未获取信息'],json_encode(['errormsg' => '未获取信息'.$e->getMessage(), 'statue_code' => '4003']));
            Response::create(['errormsg' => $e->getMessage(), 'statue_code' => '4003'], 'json')->header($header)->send();
        }
        /**
            正确返回
        { 
                    "access_token":"ACCESS_TOKEN", 
                    "expires_in":7200, 
                    "refresh_token":"REFRESH_TOKEN",
                    "openid":"OPENID", 
                    "scope":"SCOPE",
                    "unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL"
                } /*
        if (isset($access_toke_data['openid'])) {
            $uu = new UserServer();
            // 从数据库中获取是否有该用户
            $userong = $uu->getThirdUserinfo($access_toke_data['openid']);
            if (empty($userong)) {
                                // 判断是否有access_token
                $grant_token = $access_toke_data['access_token']??'';
                if (!empty($grant_token)) {
                      //   $this->filecacheobj =  Cache::store('filetoken');
                      // 存到文件缓存
                   $this->filecacheobj->set('grant_access_token', $grant_token, 7000);
                }
                 
                $jsapiobj = new  Weixin();
                 // 从缓存中拿access_token
                $token = $jsapiobj->getAccessToeknCode($this->filecacheobj);
                /**
                    function getAccessToeknCode($cacheobj){ 
                                            $access_token =$cacheobj->get('access_token');
                                            if (empty($access_token) ||$access_token ==false) {
                                                return null;
                                            }
                                            $data =json_decode($access_token,true);
                                            if(!isset($data['access_token']) || $data['access_token']==''){
                                                return null;
                                            }
                                            return $data['access_token']; 
                                    }
                                */
                try {
                      // 授权级别
                   if ('snsapi_userinfo' == $state) {
                        $userinfoobj = $jsapiobj->getUserinfosnsapi_userinfo($grant_token, $access_toke_data['openid']);
                   /**
                         function getUserinfosnsapi_userinfo($ACCESS_TOKEN, $openid)
                                            {
                                         
                                                $url = Config::get('weixin_api.get_userinfo_userinfo');
                                         
                                                $url = str_replace('ACCESS_TOKEN', $ACCESS_TOKEN, $url);
                                                $url = str_replace('OPENID', $openid, $url);
                                                $client = new Client([
                                                    // Base URI is used with relative requests
                                                    // You can set any number of default request options.
                                                    'timeout' => 2.0,
                                                ]);
                                                $request = new GuRequest('get', $url);
                                                $response = $client->send($request, ['timeout' => 2, 'verify' => false]);
                                                $body = $response->getBody();
                                                $remainingBytes = $body->getContents();
                                                return $remainingBytes;
                                            }
                    
                   */
                    
                   } else {
                        $userinfoobj = $jsapiobj->getUserinfo($token, $access_toke_data['openid']);
                   /**
                         function getUserinfo($ACCESS_TOKEN, $openid)
                                            {
                                                $configdata = Config::get('weixin_api');
                                                $url= $configdata['get_userinfo'];
                                                $url = str_replace('ACCESS_TOKEN', $ACCESS_TOKEN, $url);
                                                $url = str_replace('OPENID', $openid, $url);
                                                $client = new Client();
                                                $request = new GuRequest('GET', $url);
                                                $response = $client->send($request, ['timeout' => 2, 'verify' => false]);
                                                $body = $response->getBody();
                                                $remainingBytes = $body->getContents();
                                                return $remainingBytes;
                                            }
                   */
                    
                   }
                   // 删除反斜杠
                   $userinfoobj = stripslashes($userinfoobj);
                   // 数组输出格式
                   $userinfoobj = json_decode($userinfoobj, true);
                    //没有关注
                   if (isset($userinfoobj['subscribe']) && 0 == $userinfoobj['subscribe']) {  
                       $this->loginError($userinfoobj,json_encode(['errormsg' => $userinfoobj, 'statue_code' => '4006']));
                       Response::create(['errormsg' => $userinfoobj, 'statue_code' => '4006'], 'json')->header($header)->send();
                   }
                   // 授权成功,存数据库
                   if (is_array($userinfoobj) && !isset($userinfoobj['errmsg']) ) {
                       $userong = $uu->addThirdUserinfo($access_toke_data['openid'], $request, $userinfoobj, 1);
                       if(empty($userong)){
                           $this->loginError($userinfoobj,json_encode(['errormsg' => $userinfoobj, 'statue_code' => '4007']));
                           Response::create(['errormsg' => '', 'statue_code' => '4007'], 'json')->header($header)->send();
                       }
                   } else {
                       $this->loginError($userinfoobj,json_encode(['errormsg' => $userinfoobj['errmsg'], 'statue_code' => '4008']));
                       Response::create(['errormsg' => $userinfoobj['errmsg'], 'statue_code' => '4008'], 'json')->header($header)->send();
                   }
                } catch (\Exception $e) {
                    $this->loginError($userinfoobj,json_encode(['errormsg' =>$e->getMessage(), 'statue_code' => '4004']));
                    Response::create(['errormsg' => $e->getMessage(), 'statue_code' => '4004'], 'json')->header($header)->send();
                }
            }
            $this->loginError(['nickname'=>$userong['nickname'],'headimgurl'=>$userong['head_pic']],json_encode(['errormsg' =>$userong, 'statue_code' => '2000']),1);
            $access_toke_data['userong'] = $userong;
            $access_toke_data['user'] = $uu->getUserinfo($userong->user_id);
            $access_toke_data['statue_code'] = '2000';
            Hook::add('appInit', 'app\\dataapi\\behavior\\Jwt');
            Hook::listen('appInit', $access_toke_data);
            //{"subscribe":1,"openid":"oASY5wXqQnE1Q8AWXAQPsc0VYA9Q","nickname":"牧童","sex":1,"language":"zh_CN","city":"普陀","province":"上海","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/uI5pczeERTYiaOhicicADBR2MdoPQy7Nk2ofoxRhcRmHBCrs3RdlLobszakIVJUnSOXb5L949bNGCxMRc4rJOlibcjrgrUc0sugB\/0","subscribe_time":1484811704,"remark":"","groupid":0,"tagid_list":[]}
            Response::create($access_toke_data, 'json')->header($header)->send();
        } else {
            $this->loginError(['nickname'=>'XX','headimgurl'=>'未获取信息2'],json_encode(['errormsg' =>$access_toke_data,'code'=>$code,'url'=>$url,'statue_code' => '4005']));
            Response::create(['errormsg' => '', 'statue_code' => '4005'], 'json')->header($header)->send();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信OAuth2.0网页授权接口PHP版用法示例,测试前请先申请一个公众供测试,微信提供测试用的公众账,此帐只能添加100个关注者且只有__已关注__的用户才可以进行OAuth2.0受权。   1.开通后将```appID```、```appsecret```、```Token```填入```index/Conf/config.php```中。然后将接口配置信息中的URL改至php服务器,将地址定位到```index.php/Index/wechatInitAuth```进行微信API认证,直到提示"配置成功"。   2.点击‘体验接口权限表--OAuth2.0网页授权(仅关注者才能授权)’中的修改,将授权回调页面域名改为php服务器地址。直到出现‘通过安全监测’。   配置完微信测试后,在微信中打开```http://项目目录/index.php```(例:```http://121.40.135.90/weixin_auth/index.php```)将会在页面中打印出session中的受权数据,表示测试受权成功。   在AuthAction中的初始化函数```_initialize```中进行了OAuth2.0受权,所有基于AuthAction的控制器都将进行受权过程(除了微信API认证过程wechatInitAuth)。   对于同一用户在受权过期时间内多次打开此控制器的页面,将不会进行多次受权,因为其受权信息记录在session中,以免重复受权,减慢访问速度。受权过期时间在```index/Conf/config.php```中```wx_webauth_expire```设置,建议不要大于微信的过期时间7200秒。注意:   * 微信OAuth2.0受权分为snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息),AuthAction.class.php默认为snsapi_base,而且session中只记录了snsapi_base中的基础数据,如需要snsapi_userinfo请自行修改。   * 具体的实现方法见代码注释。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值