微信网页授权,获取用户信息代码实例
发布日期:2019年01月04日,网站分类:网站新闻
使用微信公众号网页授权,获取用户头像,昵称等基本信息代码实例,高手可直接跳过。
html文件调用js:
var appID = "{:sysconf('app_id')}"; // 公众号AppID var redirectUri = "{:sysconf('redirectUri')}/wechatuser"; // 授权接口地址 var now_url = "当前界面地址"; // 将要跳转回来的路径地址 存到session 或者cookies var openid = "{$_GET['openid']}";//获取openid var name = "{$_GET['nickname']}"; var avatar = "{$_GET['headimgurl']}"; var game_id = {$id}; var user_id = 0; if(openid == null || openid == undefined || openid == ''){ // 通过判断地址参数是否有openid来确定是否要跳转授权 var strUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appID + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect"; window.location.href = strUrl; }
php代码:
function wechatuser(){ $appId = sysconf('app_id'); $appSecret = sysconf('app_key'); $code = $_GET['code']; $now_url = $_COOKIES['now_url']; $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code={$code}&grant_type=authorization_code"; $a = file_get_contents($url); $json=(array)json_decode($a); if(!isset($json['errcode'])){ $openid = $json['openid']; $url ="https://api.weixin.qq.com/sns/userinfo?access_token=".$json['access_token']."&openid=".$json['openid']; $a = file_get_contents($url); $json = (array)json_decode($a); $nickname = $json['nickname']; $headimgurl = $json['headimgurl']; // 追加用户信息(如:openid、昵称、头像等)地址参数跳回前端页面 header("Location:'.$now_url.'?openid=$openid&nickname=$nickname&headimgurl=$headimgurl"); } }
php函数:
/** * 获取完整当前路径 * @return string */ function getDomainUrl(){ if(is_https()){ $http = 'https://'; }else{ $http = 'http://'; } $string = $http.$_SERVER['SERVER_NAME']; return $string; } /** * 判断是否是https * @return bool */ function is_https() { if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') { return true; } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) { return true; } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') { return true; } return false; }
关键词:网站优化
转载请注明来自:https://www.kufan.cn/news/240.html
上一篇:在小程序中使用字体图标