开发文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
有两种授权方式:基本授权和详细授权
appid和appsecret可以用公众平台测试帐号的,网页授权回调域名等等自己都要配置好。
网站后台我用的Thinkphp3.2,话不多说
//获取用户的openid (基本授权)
function getBaseInfo(){
//1.获取到code
$appid="开发者ID";
$redirect_uri=urlencode("https://cs.xxxxxx.com/shop/index.php/User/getUserOpenId");
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
header('location:'.$url);//引导关注者打开页面
}
function getUserOpenId(){
$appid="开发者ID";
$appsecret="开发者密码";
$code=$_GET['code'];
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
//3.拉取用的openid
$res = $this->http_curl($url,'get');
var_dump($res);
$openid = $res['openid'];
//time(); 1,2,3
//用户访问次数统计和限制
}
public function http_curl($url,$type='get',$res='json',$arr=''){
/*
$url 请求的url
$type 请求类型
$res 返回数据类型
$arr post请求参数
ctrl+f键查找 extension=php_curl.dll 将前面的分号;去掉,
*/
// 1. 初始化
$ch=curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);//CURLOPT_URL 指定请求的URL
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//CURLOPT_RETURNTRANSFER 设置为1表示稍后执行的curl_exec函数的返回是URL的返回字符串,而不是把返回字符串定向到标准输出并返回TRUE
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//FALSE 禁止 cURL 验证对等证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
if($type=='post'){
curl_setopt($ch,CURLOPT_POST,1);//TRUE 时会发送 POST 请求
curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);//全部数据使用HTTP协议中的 "POST" 操作来发送
}
// 3. 执行并获取HTML文档内容
$output = curl_exec($ch);
// 4. 释放curl句柄
curl_close($ch);
if($res=='json'){
return json_decode($output,true);//对 JSON 格式的字符串进行解码(数组)
}
}
//(详细授权)
function getUserDetail(){
//1.获取到code
$appid="开发者ID";
$redirect_uri=urlencode("https://cs.xxxxxx.com/shop/index.php/User/getUserInfo");
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
header('location:'.$url);
}
function getUserInfo(){
//2.获取到网页授权的access_token
$appid="开发者ID";
$appsecret="开发者密码";
$code=$_GET['code'];
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
$res = $this->http_curl($url,'get');
$access_token = $res['access_token'];
$openid = $res['openid'];
//3.拉取用户的详细信息
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
$res= $this->http_curl($url);
var_dump($res);
}
微信测试地址(一定要在微信上测试):
基本授权: https://cs.xxxxxx.com/shop/index.php/User/getBaseInfo
详细授权: https://cs.xxxxxx.com/shop/index.php/User/getUserDetail