How to obtain user information through WeChat applet
Recently I am studying how to play the WeChat applet. After contacting it, I found many pitfalls. This article will teach you how to obtain user information through WeChat applet.
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 kind of 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 Among them, 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:
Thinkphp5 case study on how to implement the WeChat applet to obtain user information interface
10 articles on obtaining user information Recommendation
How to obtain user information through web page authorization
The above is the detailed content of How to obtain user information through 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











Microsoft Word documents contain some metadata when saved. These details are used for identification on the document, such as when it was created, who the author was, date modified, etc. It also has other information such as number of characters, number of words, number of paragraphs, and more. If you might want to remove the author or last modified information or any other information so that other people don't know the values, then there is a way. In this article, let’s see how to remove a document’s author and last modified information. Remove author and last modified information from Microsoft Word document Step 1 – Go to

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

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

Current image 3D reconstruction work usually uses a multi-view stereo reconstruction method (Multi-view Stereo) that captures the target scene from multiple viewpoints (multi-view) under constant natural lighting conditions. However, these methods usually assume Lambertian surfaces and have difficulty recovering high-frequency details. Another approach to scene reconstruction is to utilize images captured from a fixed viewpoint but with different point lights. Photometric Stereo methods, for example, take this setup and use its shading information to reconstruct the surface details of non-Lambertian objects. However, existing single-view methods usually use normal map or depth map to represent the visible

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

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

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
