微信开发2之php网页授权登录

在开发之前,我们要确保我们的服务号,在接口权限处,已经获得了网页授权权限

此外,我们还需要有个备案通过的域名,比如"www.myname.com",并确保你的域名可以访问到你的服务器,于是在公众号设置那里把域名配置好,把校验文件"MP_verify_lS1VtPAOta6l5jrQ.txt"放置到你的网站的根目录,于是提交成功,变成如下设置

接下来,我们要去建立一个php文件"getinfo.php",内容如下:

<?php
$appid = 'wxxxxa95xxx0xxxxx';

#你的公众号appid

$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=http%3A%2F%2Fwww.xingchuangpinzhi.com%2FgetinfoDetail.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

#redirect_uri改为你的网页授权域名和刚刚跳转到的显示页面,比如我的是getinfoDetail.php

header('location:'.$url);
?>

建立一个php文件"getinfoDetail.php",内容如下:

<?php
header("Access-Control-Allow-Origin:*"); #设置跨域
header("Content-Type: application/json; charset=UTF-8"); 
//获取存放在cookies里面的token
$code = $_GET['code'];
$state = $_GET['state'];
//换成自己的接口信息
$appid = 'wxxxxxxxxxxxxxx';#你的公众号appid
$appsecret = '7xxfxxxxxxxxxxxxxxxxx';#你的公众号appsecret
if (empty($code)) $this->error('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
    echo '<h1>错误:</h1>'.$token->errcode;
    echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
    exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
    echo '<h1>错误:</h1>'.$access_token->errcode;
    echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
    exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
    echo '<h1>错误:</h1>'.$user_info->errcode;
    echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
    exit;
}

$rs =  json_decode(json_encode($user_info),true);//返回的json数组转换成array数组
$openid= $rs["openid"];
$nickname=$rs["nickname"];
$sex=$rs["sex"];
$language=$rs["language"];
$city=$rs["city"];
$province=$rs["province"];
$country=$rs["country"];
$headuri=$rs["headimgurl"];
//打印用户信息
echo $openid;
echo $nickname;
echo $sex;
echo $language;
echo $city;
echo $province;
echo $nickname;
echo $headuri;
echo $country;
?>

完成后访问url:"http://www.我的域名.com/getinfo.php",显示

点击获取,打印出授权用户信息:

任何程序错误,以及技术疑问或需要解答的,请扫码添加作者VX

640?wx_fmt=jpeg

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青年夏日科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值