首页 微信开发 正文
250

微信授权获取openid

  • yiqingpeng
  • 2015-04-24
  • 0
  •  
function getAuthUrl($redirectUrl='',$uinfo=false) {
    global $_C;
    $baseUrl = rtrim($_C['actUrl'],'/');//actUrl是基地址
    $redirectUrl = ltrim($redirectUrl,'/');
    $redirectUrl = urlencode($baseUrl.'/'.$redirectUrl);//构造跳转地址
    $scope = $uinfo?'snsapi_userinfo':'snsapi_base';
    return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$_C['appId'].'&redirect_uri='.$redirectUrl.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect';
}


function getWXAuthInfo($code){
    try{
        global $_C;
        $appId = $_C['appId'];
        $secret = $_C['appSecret'];
        if(empty($appId) || empty($secret)) throw new Exception('请在配置文件中设置微信AppId和Secret!'); 

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $out = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($out,true);
        $openId = $arr['openid'];
        $accessToken = $arr['access_token'];
        if(empty($openId)) return array('code'=>-2,'message'=>'授权失效!','data'=>'');
        return array('code'=>1, 'message'=>'授权验证通过!', 'data'=>array('openId'=>$openId, 'accessToken'=>$accessToken));
    }catch(Exception $ae){
        return array('code'=>0,'message'=>'网络繁忙,请稍后再试!','data'=>$ae->getMessage ());
    }
}


正在加载评论...