Example method of obtaining user information in WeChat applet
This article mainly introduces in detail how the WeChat applet obtains user information. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
For example, in a browser we can get the DOM object of the page through document.getElementById. However, the DOM object cannot be obtained in the WeChat applet. document.getElementById() directly reports an error getElementById not function. I am also drunk. Without support for this, many interesting features cannot be implemented.
Getting back to business, let me talk about my thoughts on obtaining user information.
There are two options for obtaining user information.
1. A json object that does not contain the sensitive information openId (including basic information such as nickname, avatarUrl, etc.)
2. Contains the basic information of the sensitive information openId.
The first acquisition scheme
1. First call the wx.login() interface to allow user authorization verification, which is what we observe with the naked eye. Whether to authorize this information to xxxxx.
2. After the user is successfully authorized, call the wx.getUserInfo() interface to obtain user information.
The complete code is as follows
wx.login({ success:function(){ wx.getUserInfo({ success:function(res){ var simpleUser = res.userInfo; console.log(simpleUser.nickName); } }); } });
The second type is more complicated and requires interaction with the background to obtain userInfo, but the data obtained by this solution is complete (including openId).
1. Call the wx.login() interface to authorize and include code in the parameters of the success function.
2. Call the wx.getUserInfo() interface success function, which contains encryptedData and iv
3. Pass the above parameters to the background for analysis and generate userInfo
The code is as follows
js
var request = require("../../utils/request.js"); wx.login({ success:function(res_login){ if(res_login.code) { wx.getUserInfo({ withCredentials:true, success:function(res_user){ var requestUrl = "/getUserApi/xxx.php"; var jsonData = { code:res_login.code, encryptedData:res_user.encryptedData, iv:res_user.iv }; request.httpsPostRequest(requestUrl,jsonData,function(res){ console.log(res.openId); }); } }) } } })
Backend analysis
/** * 获取粉丝信息 * 其中的参数就是前端传递过来的 */ public function wxUserInfo($code,$encryptedData,$iv) { $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->wxConfig['appid']}&secret={$this->wxConfig['appsecret']}&js_code={$code}&grant_type=authorization_code"; $apiData = json_decode(curlHttp($apiUrl,true),true); if(!isset($apiData['session_key'])) { echoJson(array( "code" => 102, "msg" => "curl error" ),true); } $userInfo = getUserInfo($this->wxConfig['appid'],$apiData['session_key'],$encryptedData,$iv); if(!$userInfo) { echoJson(array( "code" => 105, "msg" => "userInfo not" )); } //$userInfo = json_decode($userInfo,true); //载入用户服务 //$userService = load_service("User"); //$userService->checkUser($this->projectId,$userInfo); echo $userInfo; //微信响应的就是一个json数据 }
getUserInfo function where wxBizDataCrypt.php is the material package officially provided by WeChat
curlHttp function is a custom function. For the source code of this function, check out my article Article curlHttp
//获取粉丝信息 function getUserInfo($appid,$sessionKey,$encryptedData,$iv){ require_once ROOTPATH . "/extends/wxUser/wxBizDataCrypt.php"; $data = array(); $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { return $data; } else { return false; } }
Write your own gadget request.js
var app = getApp(); //远程请求 var __httpsRequest = { //http 请求 https_request : function(obj){ wx.request(obj); }, //文件上传 upload_request : function(dataSource){ wx.uploadFile(dataSource); } }; module.exports = { //执行异步请求get httpsRequest:function(obj){ var jsonUrl = {}; jsonUrl.url = obj.url; if(obj.header)jsonUrl.header=obj.header; if(obj.type) jsonUrl.method = obj.type; else jsonUrl.method="GET"; if(obj.data)jsonUrl.data = obj.data; obj.dataType?(jsonUrl.dataType=obj.dataType):(jsonUrl.dataType="json"); jsonUrl.success = obj.success; jsonUrl.data.projectId = app.globalData.projectId; __httpsRequest.https_request(jsonUrl); }, //get 请求 httpsGetRequest:function(req_url,req_obj,res_func) { var jsonUrl = { url:app.globalData.host + req_url, header:{"Content-Type":"application/json"}, dataType:"json", method:"get", success:function(res) { typeof res_func == "function" && res_func(res.data); } } if(req_obj) { jsonUrl.data = req_obj; } jsonUrl.data.projectId = app.globalData.projectId; __httpRequest.https_request(jsonUrl); }, //post 请求 httpsPostRequest:function(req_url,req_obj,res_func) { var jsonUrl = { url:app.globalData.host + req_url, header:{"Content-Type":"application/x-www-form-urlencoded"}, dataType:"json", method:"post", success:function(res) { typeof res_func == "function" && res_func(res.data); } } if(req_obj) { jsonUrl.data = req_obj; } jsonUrl.data.projectId = app.globalData.projectId; __httpsRequest.https_request(jsonUrl); }, //文件上传 httpsUpload:function(uid,fileDataSource,res_func) { dataSource = { url:app.globalData.host + req_url, header:{ "Content-Type":"multipart/form-data" }, dataType:"json", formData : { "uid" : uid }, filePath : fileDataSource, name : "fileObj", success:function(res){ typeof res_func == "function" && res_func(res); } } __httpsRequest.upload_request(dataSource); } };
app.globalData.host is the domain name address such as https://xxxxx.com;
Related recommendations:
How to implement the WeChat applet to obtain user information
Thinkphp5 A case study on how to implement the WeChat applet to obtain user information interface
10 recommended articles about obtaining user information
The above is the detailed content of Example method of obtaining user information in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Using System Information Click Start and enter System Information. Just click on the program as shown in the image below. Here you can find most of the system information, and one thing you can find is graphics card information. In the System Information program, expand Components, and then click Show. Let the program gather all the necessary information and once it's ready, you can find the graphics card-specific name and other information on your system. Even if you have multiple graphics cards, you can find most content related to dedicated and integrated graphics cards connected to your computer from here. Using the Device Manager Windows 11 Just like most other versions of Windows, you can also find the graphics card on your computer from the Device Manager. Click Start and then

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

In iOS 17, there's a new AirDrop feature that lets you exchange contact information with someone by touching two iPhones. It's called NameDrop, and here's how it works. Instead of entering a new person's number to call or text them, NameDrop allows you to simply place your iPhone near their iPhone to exchange contact details so they have your number. Putting the two devices together will automatically pop up the contact sharing interface. Clicking on the pop-up will display a person's contact information and their contact poster (you can customize and edit your own photos, also a new feature of iOS17). This screen also includes the option to "Receive Only" or share your own contact information in response.

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

In iOS17, there is a new AirDrop feature that allows you to exchange contact information with someone by touching two iPhones at the same time. It's called NameDrop, and here's how it actually works. NameDrop eliminates the need to enter a new person's number to call or text them so they have your number, you can simply hold your iPhone close to their iPhone to exchange contact information. Putting the two devices together will automatically pop up the contact sharing interface. Clicking on the popup will display a person's contact information and their contact poster (a photo of your own that you can customize and edit, also new to iOS 17). This screen also includes "Receive Only" or share your own contact information in response

The reason for the delay in WeChat receiving information may be network problems, server load, version problems, device problems, message sending problems or other factors. Detailed introduction: 1. Network problems. The delay in receiving information on WeChat may be related to the network connection. If the network connection is unstable or the signal is weak, it may cause delays in information transmission. Please ensure that the mobile phone is connected to a stable network and the network signal strength is good. ; 2. Server load. When the WeChat server load is high, it may cause delays in information transmission, especially during busy periods or when a large number of users use WeChat at the same time, etc.

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.
