获取openid
$code = input('code'); $appid = ''; //公众号的唯一标识 $appsecret = ''; //秘钥 $grant_type = 'authorization_code'; $scope = 'snsapi_base'; //应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) $state = 'STATE'; //重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 $response_type = 'code'; //返回类型,请填写code if(empty($code)){ // 获取当前域名协议 $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; //授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理 $redirect_uri = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // 跳转到当前地址授权 header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$siteInfo['appid'].'&redirect_uri='.$redirect_uri.'&response_type='.$response_type.'&scope='.$scope.'&state='.$state.'#wechat_redirect'); exit; }else{ $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type='.$grant_type; $content = file_get_contents($get_token_url); $arr = json_decode($content,TRUE); //返回openid,expires_in,access_token,refresh_token,scope print_r($arr); }
输出:
Array ( [access_token] => 30_w3WgQXSMRsM04J24mFwx6PEUIyPzF42qHwD_C8jOk6EkMWwb63aYStIdvNxtXsUftLRJ7n4Hc6oTVitRFNReuQ [expires_in] => 7200 [refresh_token] => 30_ACxVB3JGH33ZEc8OAl-m7Jv1HMsljDnBOHn5sdwj8NTXZt6vQI6JAaRsNT9TWAyb543adbnDs5KC0cQ6zCkmew [openid] => oYNSNwZvgpk597M3ladk4XqxRouw [scope] => snsapi_base )
根据上面获取到的参数获取微信用户详细信息
注:用户先关注公众号才能获取
//获取微信信息 $infoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN'; $infoObj = file_get_contents($infoUrl); $wechatRes = json_decode($infoObj,TRUE); //返回openid,expires_in,session_key print_r($$wechatRes);
输出:
Array ( [openid] => oYNSNwZvgpk597M3ladk4XqxRouw [nickname] => 立行搏 [sex] => 1 [language] => zh_CN [city] => 海口 [province] => 海南 [country] => 中国 [headimgurl] => http://thirdwx.qlogo.cn/mmopen/vi_32/oibXNNKmCZ0ODibPvELnt9kqTSI5NDDvf8nZ0k0TeT3qXBYCLFHmaKtXXTJ1fuxGlA6TcoCmdgoz597L3ZgS9Ngw/132 [privilege] => Array ( ) )
未关注公众后返回错误:
Array ( [errcode] => 48001 [errmsg] => api unauthorized, hints: [ req_id: kgFAHA0gE- ] )
48001:api 功能未授权,请确认公众号已获得该接口,可以在公众平台官网 - 开发者中心页中查看接口权限