首先要准备几个东西
1、appid
2、secret
3、回调域名要设置好
记住不要写协议头,就是单单的域名;
下面附个官方步骤:
目录
2 第二步:通过code换取网页授权access_token
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
现在来第一步,直接扔下代码:1 第一步:用户同意授权,获取code
授权入口:http://www.minshu.xin/My/index.php/Home/Index/shouquan
function shouquan(){
//声明一下lz用的是tp3.2
$appid="wxd61ce8a6baca54b3"; //公众号appid
$secret="97079d860477014476f8078c764ce393"; //开发者密码
$reredirect_uri="https://www.minshu.xin/My/index.php/Home/Index/info";
//回调链接,当请求完接口,会以get的方式传code参数给这个url
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$reredirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//普通授权,需要用户自己手动授权
//$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$reredirect_uri&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//静默授权不需要用户手动授权,就是没有授权页面
header("Location:$url");
/*跳转到url,不能去异步请求,因为微信官方要做第二次跳转到你的回调页面 $reredirect_uri,当全部配置正确的微信官方会帮你带code参数的https://www.minshu.xin/My/index.php/Home/Index/info? code=081WVekf06xczB1MjDif02H5kf0WVekQ&state=STATE回调地址;*/
2 第二步:通过code换取网页授权access_token
在上一步中微信官方已经给你传了code参数过去了,现在就是直接接受就是了
来到回调页面
public function info(){
$appid="wxd61ce8a6baca54b3";
$secret="97079d860477014476f8078c764ce393";
$code=$_GET["code"]; //接受code
//这里就是换取access_token接口,我这里用curl去请求
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$output=$this->http_request($url); //自定义的curl()方法
//var_dump(json_decode($output,true)); //因为返回的json格式现在返回为数组格式
$info= json_decode($output,true); 这是获取到 access_token等信息
$access_token=$info["access_token"];
$openid=$info["openid"];
示例:
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
//需要第二步获取的openID ,还有access_token
$url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$output=$this->http_request($url);
$info=json_decode($output,true);
var_dump($info);//打印信息
//到这步已经完成啦
}
}