search
HomeBackend DevelopmentPHP Tutorialphp WeChat public account development to obtain user WeChat personal information


Many developers need to obtain the user's avatar when developing a WeChat official account. If it is a personal WeChat account, you need to apply for a "public platform test account" to obtain a WeChat official account. All interface permissions;

First, you need to obtain the access_token sent by WeChat, and then use the openid and access_token to obtain the user message in json format sent by the WeChat server. Finally, use josn_decode to convert it to obtain the user's details. News;

Before writing the code, you can test the interface operation as shown below:

First enter the WeChat public platform, as shown below:


Click on Developer Tools, and then click on Online Interface Debugging, as shown in the figure below, to enter the interface selection interface


Click Then enter the page below and select in the interface type: User management, select in the interface list: Get user profile information interface/user/info;

Then check the WeChat development documentation to obtain access_token and use the appid and appsecret as shown below




################# qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret" URL, where $appid is the appid string in the above picture, $appsecret is your developer password, replace the two with strings After the variable (be careful to remove the quotation marks), click the enter key to obtain the access_token and expires_in data sent by the WeChat server. Copy the obtained access_token string to the interface debugging page. Openid is the test account and the only ID after following the platform is encrypted. Yes, please see the previous article for the method of obtaining it, or you can also use Baidu. Enter the two parameters into the corresponding input boxes on the interface page (the green word "passed verification" will be displayed after the input is completed), and then click to detect the problem; ## #######The obtained information is as shown below: ##################This means that you have successfully obtained it. Let’s add the code to obtain the access_token and personal information; ###
public function getaccss_token(){
		$table = 'Access_token';
		$useraccess_token = Db::table('Access_token')->select();
		$appid = "你的appid";
		$appsecret = "你的appsecret";
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
		//判断是不是第一次获取access_token		
		if(!count($useraccess_token)){			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
			$jsoninfo = json_decode($output, true);
			$access_token = $jsoninfo["access_token"];			
			$data=['access_token'=>$access_token,'expires_time'=>($jsoninfo['expires_in']+time()-200)];
			Db::table($table)->insert($data);
			return $access_token;
	}else if($useraccess_token[0][&#39;expires_time&#39;]<time()){//判断是否过期
		
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
			$jsoninfo = json_decode($output, true);//转换格式
			$access_token = $jsoninfo["access_token"];			
			$data=[&#39;access_token&#39;=>$access_token,&#39;expires_time&#39;=>($jsoninfo[&#39;expires_in&#39;]+time()-200)];
			Db::table($table)->where(&#39;expires_time&#39;,$useraccess_token[0][&#39;expires_time&#39;])->update($data);//更新数据库;
			return $access_token;
	}else{	
		$access_token = $useraccess_token[0][&#39;access_token&#39;];
		return $access_token;
		
	}
	}
###Use the curl function to intercept the message sent by WeChat. Since the access_token obtained is only valid for 7200s, which is two hours, so every time the user makes an entry operation on the official account, it must be checked to see if it is It has expired. If it expires, it needs to be obtained again. The several if judgments in the picture above are used to judge. I save the access_token and time in the database, so that it can be taken out for detection every time. Of course, you can also use it from the cache. Call or put it into a file and call it from the file; ######After obtaining the access_token, obtain the user's personal information through access_token and openid, as shown below: ###
public function userinfo($openid){
		$access_token = $this->getaccss_token();
		//获取用户信息地址		
		$urlid = &#39;https://api.weixin.qq.com/cgi-bin/user/info?access_token=&#39;.$access_token.&#39;&openid=&#39;.$openid.&#39;&lang=zh_CN&#39;;
		$curl = curl_init(); // 启动一个CURL会话
		curl_setopt($curl, CURLOPT_URL, $urlid);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
		$tmpInfo = curl_exec($curl);     //返回api的json对象
		//关闭URL请求
		curl_close($curl);
                $userinfo = json_decode($tmpInfo,true);			
		return $userinfo;
	}
### is also related to the curl function Operate to intercept the information and convert the format. The last userinfo is the user's personal information array. You only need to call it; ######The above is the operation to obtain the user's personal information through access_token~! ######Related recommendations: #########php WeChat public account development, obtain user avatar, and download######

The above is the detailed content of php WeChat public account development to obtain user WeChat personal information. For more information, please follow other related articles on the PHP Chinese website!

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
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool