php 微信网页授权获取微信access_token以及用户基础信息的方法

首先在微信公众平台配置好

php 微信网页授权获取微信access_token以及用户基础信息的方法_第1张图片

php 微信网页授权获取微信access_token以及用户基础信息的方法_第2张图片

官方文档地址

目录

1 第一步:用户同意授权,获取code

2 第二步:通过code换取网页授权access_token

3 第三步:刷新access_token(如果需要)

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

5 附:检验授权凭证(access_token)是否有效

  /**
     * 获取微信授权链接
     *"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx03c6c7bd931f4c61&secret=1c9f912191bfaac49c127b06c0b206e5&code=" . $code . "&grant_type=authorization_code"
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    private function get_authorize_url($plat)
    {
		//file_put_contents("./2",$plat);
		$info = $this->get_wchat_public_conf($plat);
		if ($info) {
			$this->app_id = $info['appid'];
		}
        $redirect_uri = urlencode(BASEURL . "/index.php/App/Wchacf/getOpenid?plat=".$plat);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state={$this->state}#wechat_redirect";
        return $url;
    }

    /**
     * 获取微信openid
     * //{requestType: wchat,requestKeywords:'getopenid',code:x}
     */
    public function getopenid()
    {
		header("Access-Control-Allow-Origin:*");
        //header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
        //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        if (!isset($_GET['code'])) {
            $plat = I("get.plat");
			//file_put_contents("./3",$plat);
            //触发微信返回code码
            $url = $this->get_authorize_url($plat);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
			$plat = I("get.plat");
			//file_put_contents("./4",$plat);
            $code = $_GET['code'];
		
            $access_info = $this->get_access_token($plat,$code);
			
			//file_put_contents("./4",$access_info['openid']);
			//echo json_encode(array("code" => $access_info['openid'],"plat" => $plat));die;
			header("Location:http://lm.wzmedia.net/web/#/login?code=".$access_info['openid']."&plat=".$plat);
			//header("Location:http://192.168.31.221:8080/#/login?code=".$access_info['openid']."&plat=".$plat);
        }
    }

    /**
     * 获取授权token网页授权
     *
     * @param string $code 通过get_authorize_url获取到的code
     */
    private function get_access_token($plat,$code = '')
    {	
	
		//file_put_contents("./5",$plat);
		$info = $this->get_wchat_public_conf($plat);
		if ($info) {
			$this->app_id = $info['appid'];
			$this->app_secret = $info['appsecret'];
			//$this->state = "platstate";
		}
        $appid = $this->app_id;
        $appsecret = $this->app_secret;
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
		//file_put_contents("./tokentest",$token_url);
        $token_data = $this->http_request($token_url);
		
        $res = json_decode($token_data, true);
		 return $res;
        //if ($token_data[0] == 200) {
           // $ar = json_decode($token_data[1], TRUE);
          //  return $ar;
        //}
        //return $token_data[1];
    }

1.获取access_token

public function getaccess_token(){
		$appid ='wx03c****4c61';//开发者id
		$appsecret = '1c9f91*********06e5';//开发者密码
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; 
		$res=$this->httpget($url);
		$data=json_decode($res, true);
	

	}

2.获取用户基本信息  access_token,openid

//获取用户基本信息
	public function gethead($access_token,$openid){
		$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
		$res=$this->httpget($url);
		$data=json_decode($res, true);
		return $data;
	}

下面是请求类:

protected function httpget($url, $params, $method = 'GET', $header = array(), $multi = false) {
	   $opts = array(CURLOPT_TIMEOUT => 30, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_HTTPHEADER => $header);

	   /* 根据请求类型设置特定参数 */
	   switch(strtoupper($method)) {
		   case 'GET' :
			   $opts[CURLOPT_URL] = $url . '&' . http_build_query($params);
			   //dump($opts[CURLOPT_URL]);
			   break;
		   case 'POST' :
			   //判断是否传输文件
			   $params = $multi ? $params : http_build_query($params);
			   $opts[CURLOPT_URL] = $url;
			   
			  // dump($opts[CURLOPT_URL]);
			   $opts[CURLOPT_POST] = 1;
			   $opts[CURLOPT_POSTFIELDS] = $params;
			   break;
		   default :
			   throw new Exception('不支持的请求方式!');
	   }

	   /* 初始化并执行curl请求 */
	   $ch = curl_init();
	   curl_setopt_array($ch, $opts);
	   $data = curl_exec($ch);
	   $error = curl_error($ch);
	   curl_close($ch);
	   if ($error)
		   throw new Exception('请求发生错误:' . $error);
	   return $data;
   }

 

你可能感兴趣的:(php)