备忘使用
首先第一步注册微信公众号,填写必要信息,如果没有可以先申请测试公众号调试使用
1.申请测试公众号地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
2.进入后扫码关注,如下图
3.扫描关注公众号
4.在后台填写回调地址,如下图:
5.接下来就是进行访问了
namespace app\index\controller;
use think\Controller;
class Test extends Controller
{
//首页
public function index()
{
$appid = "你的appid";
$redirect_uri = urlencode("回调地址");//刚才填在后台的域名
$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";//拼接访问地址
//上边的授权分两种snsapi_userinfo是显式授权 snsapi_base为静默授权
$this->redirect($url);//tp中重定向访问地址
}
//回调地址
public function huid()
{
$appid = "你的appid";
$appsecrt = "你的appsecret";
$code = $_GET['code'];//接受微信返回的code参数
//再次拼接访问地址
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecrt."&code=".$code."&grant_type=authorization_code";
$detail = file_get_contents($url);//获取上边url地址返回的内容,json格式
$temdetail = json_decode($detail);
$openid = $temdetail->openid;//用户openid
$access_token = $temdetail->access_token;//获取token
//拼接地址
$url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
//获取返回信息 openid、nikename、headpic等
$userdetail = file_get_contents($url1);
var_dump($userdetail);
}
}