PHP获取微信openid 简单教程

//***方法一

获取code

https://open.weixin.qq.com/connect/oauth2/authorize?appid=这里是你的公众号的APPID&redirect_uri=http://www.xx.com/getcode&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect

用户点击确认登录,自动跳转下面地址得到code

http://www.xx.com/getcode 这个是你自己的跳转地址

http://www.xx.com/getcode?code=0064f7afef7af7b395147bfe8b51f7bf&state=123

 

后面的这个 ?code=……123   是微信自动跳转添加的,不是你自己加的

 

下面是PHP语言,写在getcode这个页面里

1

2

3

4

5

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

$weixin =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=这里是你的APPID&secret=这里是你的SECRET&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token

$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码

$array = get_object_vars($jsondecode);//转换成数组

$openid $array['openid'];//输出openid

 

 

//***方法二

$appid "公众号在微信的appid";

$secret "公众号在微信的app secret";

$code $_GET["code"];

$get_token_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,$get_token_url);

curl_setopt($ch,CURLOPT_HEADER,0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

$res = curl_exec($ch);

curl_close($ch);

$json_obj = json_decode($res,true);

//根据openid和access_token查询用户信息

$access_token $json_obj['access_token'];

$openid $json_obj['openid'];

$get_user_info_url 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

 

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$get_user_info_url);

curl_setopt($ch,CURLOPT_HEADER,0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

$res = curl_exec($ch);

curl_close($ch);

 

//解析json

$user_obj = json_decode($res,true);

$_SESSION['user'] = $user_obj;

print_r($user_obj); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值