search
HomeBackend DevelopmentPHP Tutorial微信oauth2的access_token问题

微信oauth2获取用户信息的整个流程都走通了。也没有问题。。

不过中间有一事不明。希望哪位知道的朋友帮解答下。。

每一次都要通过code去获取access_token吗?
不的话,那么用户的openid又只能在获取access_token时返回,不然就得不到用户的openid了。
或者是第一次获取到用户的openid以后存到cookie里去,下次读cookie吗???
否则那个刷新access_token有什么意义啊。。。

再有就是获取到的access_token是只是当前会话有效,还是对应某个用户openid有效,或者是所有用户都有效。。。

初次接触微信这个,谢谢。。。。。


回复讨论(解决方案)

这个只是针对你需要操作微信上的管理功能的时候才用到的,像一般的聊天啥的是没必要获取的,一般只有微信平台的管理后台才会用到这个,一般是在获取第一次之后记录下来防止每次操作都会去获取一次导致当天的API调用次数消耗完毕。

这个只是针对你需要操作微信上的管理功能的时候才用到的,像一般的聊天啥的是没必要获取的,一般只有微信平台的管理后台才会用到这个,一般是在获取第一次之后记录下来防止每次操作都会去获取一次导致当天的API调用次数消耗完毕。


我说的是:微信的网页授权获取用户基本信息;不是微信基础功能接口。。

大概流程是这样的:
1.构造URL地址:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

REDIRECT_URI是我自己的网页地址。用户直接访问的是上面的地址,再回调REDIRECT_URI地址,并带参数CODE;这里并没有用户的openid

2.
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code
根据CODE获取access_token,在这里会返回:
{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}
在这一步才有openid,也就是当前访问我这个页面的微信用户的openid
3.
根据openid获取微信用户资料

而问题就在第二步。
我保存access_token,那下一次我不是应该跳过第二步?跳过的话,那我又如何得到openid?没有openid我就不能进行第三步。。

如果不存储access_token,那么每一次微信用户访问网页都要获取一次access_token。太频繁了。。

没有做过这个的吗?

用户的openid保存到数据库,与用户进行绑定
access_token每获取一次,保存到数据库,在使用之前,首先查数据库的access_token有没有过期,二小时过期,过期重新获取再保存,

access_token有访问限制的,如果你不停的获取,最终没法提供服务

用户的openid保存到数据库,与用户进行绑定
access_token每获取一次,保存到数据库,在使用之前,首先查数据库的access_token有没有过期,二小时过期,过期重新获取再保存,

access_token有访问限制的,如果你不停的获取,最终没法提供服务



这个明白。。
但微信的网页授权里,要获取到用户的openid只有通过获取token那一步同时返回。。也就是获取token的时候同时返回token和当前访问网页的微信用户的openid。。这一点上和基础接口里不一样。基础接口里,用户每操作一次都可以获取到用户的openid。。
{
    "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
    "openid":"OPENID",//当前访问网页的微信用户的openid
   "scope":"SCOPE"
}
可是没有用户的openid,我即使有token也无法获取到这个用户的用户信息。。


<?phprequire_once("weixin.config.php");class Webweixin{	//APPID 默认是服务号	var $APPID = APPID1;	var $APPSECRET = APPSECRET1;		//用户方信息(存储当前交互用户的操作状态,以及状态时效)	var $_client = array('wx_id'=>'', 'user_id'=>0, 'act'=>'', 'exp'=>0, 'token'=>'','userdata'=>'');	var $wxu_mod;	var $CODE = '';	    function __construct()    {		$this->APPID = APPID1;		$this->APPSECRET = APPSECRET1;				if (isset($_GET['code']))		{			$this->CODE =  $_GET['code'];			$userinfo = $this->getUserInfo();			dump($userinfo);		}    }		public function getUserInfo()	{		$accessToken = $this->getAccessToken();				$cfg['ssl'] = true;		//https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID		$userinfo = $this->__curlOpen("https://api.weixin.qq.com/sns/userinfo?access_token=".$accessToken."&openid=".$this->_client['wx_id'].'&lang=zh_CN', $cfg);		$userinfo = json_decode($userinfo,true);		return $userinfo;	}		/**	 * 获取ACCESS TOKEN	 */	public function getAccessToken($getHTTP = false)	{		$isCurl = true;		/*		$tokenfile = ROOT_PATH . "/temp/TOKEN_WEB";		$token = file_exists($tokenfile)?file_get_contents($tokenfile):'';		if($token)		{			$token = json_decode($token,true);			if( time()-$token['access_time'] < $token['expires_in']){				$isCurl = false;			}		}*/        if($isCurl || $getHTTP)		{			//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code			$cfg['ssl'] = true;			$token = $this->__curlOpen("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->APPID."&secret=".$this->APPSECRET."&code=".$this->CODE."&grant_type=authorization_code", $cfg);			$token = json_decode($token,true);			$token['access_time'] = time();			//file_put_contents($tokenfile, json_encode($token), LOCK_EX);		}				$this->_client['wx_id'] = $token['openid'];		$client = $this->wx_user();		if($client){			$this->_client = $client;		}else{			$this->wx_user('add');		}		return $token['access_token'];	}    		public function __curlOpen($url, $cfg)	{		$ch = curl_init();		curl_setopt($ch, CURLOPT_URL, $url);		isset($cfg['post']) && curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");		if($cfg['ssl'])		{			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);		}		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);		isset($cfg['post']) && curl_setopt($ch, CURLOPT_POSTFIELDS, $cfg['post']);		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);				$result = curl_exec($ch);		if (curl_errno($ch))		{			return curl_error($ch);		}		curl_close($ch);		return $result;	}		//微信用户信息操作	public function wx_user($act='')    {		if($this->_client['wx_id'])		{			$this->wxu_mod = &m("weixinuser");			if($act=='add')			{				$this->wxu_mod->add($this->_client);			}elseif($act=='edit'){				$this->wxu_mod->edit("wx_id='".$this->_client['wx_id']."'", $this->_client);			}else{				$client = $this->wxu_mod->get("wx_id='".$this->_client['wx_id']."'");				return $client;			}		}	}	/*$scope : snsapi_base / snsapi_userinfo*/	public function makeStartUrl($url, $state = '', $scope = 'snsapi_userinfo')	{		//https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect		$base_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->APPID}&redirect_uri=";		$base_url .= rawurlencode($url);		$base_url .= "&response_type=code&scope={$scope}&state={$state}#wechat_redirect";				return $base_url;	}}?>

也就是说要得到当前访问网页的微信用户的openid,就要先获取token,才能得到当前访问网页的微信用户的openid。
而这样,就每次都要去获取token。我保存下来也就没有意义了。。


详见:
http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

或者说是不是第一次获取到token和openid以后,把它们存起来。
再把用户的openid存到cookie里。。
下一次直接读cookie里的openid,和存储的openid对应的token,(相当于跳过获取token那一步),直接去获取用户信息??

但这样的话,如果客户端不支持cookie,结果就还是一样了。。。。

你是建立于什么目的需要进行用户统计的,如果只是为了第三方登录那你只要按照微信的第三方登录文档进行操作即可,如果你是想进行后台用户同步,那你就需要一个公众号啊。

做微信活动。。
这个不需要登陆,只需要每个访问网页的微信用户的openid,就可以了

没戏了。。。。哎

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor