首先第一步是要配置好APPID和Secret
在config.php里面进行配置,然后在控制器里面通过
$this->wx_config = Config::get('weChat');
$this->appid = $this->wx_config['AppId'];
$this->secret = $this->wx_config['AppSecret'];
来获取,记得use \think\Config;
第二步通过code获取到openID
//获取code
public function index()
{
//1.获取到code=================================
$redirect_uri = urlencode("http://" . $_SERVER['HTTP_HOST'] . "/index/Api/saveOpenid");//这里的地址需要http://
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
$this->redirect($url);
exit();
}
//存储
public function saveOpenid()
{
$data = request()->get();
$code = $data['code'];
$token = getAccess_token($this->appid,$this->secret);//这里是获取access_oken
//第二步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->secret&code=$code&grant_type=authorization_code";
$oauth2 = getJson($oauth2Url);
//第三步:根据全局ac