微信通过网页获取用户openid

首先确定有权限并且填写授权域名:

关于特殊场景下的静默授权

1、对于以snsapi_base为scope的网页授权,就静默授权的,用户无感知;该方式需关注微信号
2、对于已关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权,用户无感知。

具体而言,网页授权流程分为四步:

1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

注意:snsapi_base需要用户关注该账号才可

构造的URL:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx29c330ac4e522f06&redirect_uri=http%3a%2f%2fsdk.zy62.com%2fwx.php&response_type=code&scope=snsapi_base&state=wx&connect_redirect=1#wechat_redirect

appid 公众号的唯一标识,redirect_uri 授权后重定向的回调链接地址,请使用urlencode对链接进行处理,response_type 返回类型,请填写code,scopensapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)

state :重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节,#wechat_redirect 必须参数

redirect_uri需要进行urlencode编码

echo $_GET['code'];  //获取code

如图所示:

微信通过网页获取用户openid

通过code换取网页授权access_token,这里的access_token和之前获取的是不一样的,

获取code后,请求以下链接获取access_token: 

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code


这样openid很轻松的就获取来了,如图所示:

微信通过网页获取用户openid


我的代码:

<?php

$code=$_GET['code'];
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx29c330ac4e522f06&redirect_uri=http%3a%2f%2fsdk.zy62.com%2fwx.php&response_type=code&scope=snsapi_base&state=wx&connect_redirect=1#wechat_redirect

$json=file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx29c330ac4e522f06&secret=换成你自己的&code='.$code.'&grant_type=authorization_code');
//echo $str;
$arr=json_decode($json,true);
print_r($arr);



<?php
//print_r($_GET);exit();
$code=$_GET['code'];//获取code
//exit($code);
$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1ce02f66d2c97b40&secret=你自己的&code='.$code.'&grant_type=authorization_code';//通过code换取网页授权access_token
$str=file_get_contents($url);
$arr=json_decode($str,true);
//print_r($arr);
$openid=$arr['openid'];
$str=file_get_contents('https://api.weixin.qq.com/cgi-bin/user/info?access_token=uHYAY1cNmaoA0iG--5Y428RTtwlu6nLOA91-xwT1CIy17keSv3jdT1gTJyNXzvtoGCT7GRqDKzRWMqzrPtqGNHDBpe16gguYZGOhCFsoyNI&openid='.$openid.'&lang=zh_CN');//获取用户信息
$arr=json_decode($str,true);
//print_r($arr);
$img=$arr['headimgurl'];//用户头像
echo '<img src="'.$img.'"/>';


接下来就可以通过openid获取用户信息了,还是不会的留言联系我

你可能感兴趣的:(微信通过网页获取用户openid)