WeChat Mini Game Access WeChat Login

Foreword : For the content of the title, the official WeChat document only mentions a few key points, and the detailed process is vague. This blog post directly presents the entire login process. In addition, if you want to know about the mini game sharing function, please check the WeChat mini game sharing with friends or circle of friends article.
Tip: This article was written in 2019, and many interfaces have been deprecated (interface documents are no longer synchronized). From 24:00 on April 28, 2021, the interface related to mini-program login and user information has been adjusted. For example, the getUserInfo method has been changed to getUserProfile. Click here to view the Mini Program Announcement

1. Steps and ideas

1. Call the wx.login(object) interface to obtain the login credential code .
2. If step 1 is successful, call wx.getSetting(object) in " success " to check whether it has been authorized. 3. If authorized, you can directly call wx.getUserInfo(object) to get user information. 4. If not authorized, call wx.createUserInfoButton(object) to activate the authorization button, and the user information can be obtained after the authorization is successful. 5. The above 4 steps allow us to get the user's avatar, nickname, gender and other information, as well as code, encryptedData, iv, etc. If it does not need to be transmitted to the server, the current process has ended. 6. If you need to obtain the user's unionId ( unionId is only available for mini-games bound to official accounts ), you need to pass the code, encryptedData, iv , etc. of user information to the server. 7. After receiving the data, the server first calls " https://api.weixin.qq.com/sns/jscode2session ", this step requires code , mini game appId




and appSecret . After success, you can get sessionKey, etc., plus the code, encryptedData, and iv from the client , and decrypt them together to get unionId, openId , nickname, avatar, etc.
8. Tips: code e will be used to obtain sessionKey , and sessionKey, encryptedData, and iv will be used together to extract user's sensitive data (including unionId, etc.).

2. Code implementation

1. Click the callback function onWechatLogin() of the "WeChat Login" button

onWechatLogin ()
{
    
    
	var self = this;

	// 第1步:调用 wx.login(object) 接口获取登录凭证 code
	wx.login({
    
    
		success: function(result)
		{
    
    
			// result对象就包括我们所需的 code
			// 第2步,调用 wx.getSetting(object),检查是否已经授权,在 onGetSetting() 内。
			self.onGetSetting(result.code);
		},

		fail: function(result)
		{
    
    
			// 失败处理
		}
	});
}

2、onGetSetting(),处理wx.getSetting(object):

onGetSetting (code)
{
    
    
	wx.getSetting({
    
    
		success (res) 
		{
    
                    
			if(res.authSetting["scope.userInfo"]) 
			{
    
    
				// 第3步:如果已经授权,则可以直接调用 wx.getUserInfo(object) 拿到用户信息
				wx.getUserInfo({
    
    
					lang: "zh_CN",  // 返回信息的展示方式,en:英文类型,zh_CN:简体中文,zh_TW:繁体中文
					withCredentials: true,
					success: function(result)
					{
    
    
						console.log(">>>> result -> ", result);
						/**
						* 成功之后,result包含我们所需的信息,就可以在此处进行下一步的操作。
						* 这里的 result和 下面用到的createUserInfoButton 里的res 是相同的数据。
						* 如若存储到后台,将code,result.encryptedData、result.iv等发送到服务器
						*/ 
					},
					fail: function(result)
					{
    
    
						// 错误处理
					}
				});
			} else {
    
    
				// 第4步:未授权,调用 wx.createUserInfoButton(object)
				let sysInfo = wx.getSystemInfoSync();
				let button = wx.createUserInfoButton({
    
    
					lang: "zh_CN",  // 返回信息的展示方式,en:英文类型,zh_CN:简体中文,zh_TW:繁体中文
					type: "text",
					text: "微信登录",
					style: {
    
    
						left: sysInfo.windowWidth / 2 - 50,
						top: sysInfo.windowHeight / 2 - 30,
						width: 100,
						height: 60,
						backgroundColor: "#c7a976",
						borderColor: "#5c5941",
						textAlign: "center",
						fontSize: 16,
						borderWidth: 4,
						borderRadius: 4,
						lineHeight: 60,
					}
				});

				button.onTap((res) => {
    
    
					if(res.userInfo) {
    
    
						// 授权成功,把button去掉
						button.destroy();

						// 输出一下信息
						console.log(">>>> res -> ", res)
                            
						/**
						* 成功之后,res包含我们所需的信息,就可以在此处进行下一步的操作。
						* 这里的 res和 上面用到的getUserInfo 里的result 是相同的数据。
						* 如若存储到后台,将code,res.encryptedData、res.iv等发送到服务器
						*/ 
					} else {
    
    
						// 取消授权,弹出小提示
						wx.showModal({
    
    
							title: "温馨提示",
							content: "需要您的用户信息登录游戏!",
							showCancel: false
						}); 
					}
				});

				button.show();
			}
		}
	});
}

3. Small expansion: When calling wx.createUserInfoButton() above, only the " text " type is used . Next, we will replace it with the image type.

let button = wx.createUserInfoButton({
    
    
	lang: "zh_CN",  // 返回信息的展示方式,en:英文类型,zh_CN:简体中文,zh_TW:繁体中文
	type: "image",
	// 下面的资源路径不是项目内的路径,而是构建好build,其内部相对根目录的路径。
	// 也可以直接写远程资源路径,如:https://www.xxx.com/images/wechatLogin.png
	image: "images/wechatLogin.png",	
	style: {
    
    
		left: 0,
		top: 0,
		width: btnWidth,
		height: btnHeight
	}
});

4. After getting the user information, we can output it and check it, as shown in the figure below. avatarUrl is the remote address of the avatar, and the others are nicknames, provinces, etc.
insert image description here
5. Next, we need to load the remote avatar resource. Before that, we need to configure the "legal domain name" on the "WeChat public platform", otherwise even if there is a remote address, it will not be accessible. Which domain name to configure specifically can be added according to the error message.
insert image description here
6. Everything is ready, we only need to load the remote avatar resource through cc.loader.load , or the new version of cc.assetManager , the code is as follows.

cc.loader.load({
    
    url: userInfo["avatarUrl"], type: "png"}, (err, tex) => {
    
    
	if(err) {
    
    
		// 错误处理
	} else {
    
                    
		let spriteFrame:cc.SpriteFrame = new cc.SpriteFrame(tex);
                
		// 有了 spriteFrame,我们就可以设置到头像上了,例如头像是headSprite。
		headSprite.getComponent(cc.Sprite).spriteFrame = spriteFrame;
	}
});

So far, it is enough to obtain the most basic nickname, gender, profile picture, etc. of WeChat. Let's look at the third part to learn how to get the user's unionId .

3. Simulation server

Tips: This part is just a brief description of the operation process of the server, and the code is only for reference of key points. If server-side processing is not required, the first two parts can already meet the requirements.

import https from "https";
import iconv from "iconv-lite";
import WXBizDataCrypt from "WXBizDataCrypt"; // 微信提供的模块,用来执行解密

// APP_ID 是小游戏的appId,APP_SECRET是小游戏的appSecret,code是客户端传来的
let url = "https://api.weixin.qq.com/sns/jscode2session"
		+ "?appid=" + APP_ID 
		+ "&secret=" + APP_SECRET 
		+ "&code=" + CODE;
		
let req = https.get(url, function (res) {
    
    
    let datas = [];
    let size = 0;
    res.on("data", function (data) {
    
    
        datas.push(data);
        size += data.length;
    });

    res.on("end", function (){
    
    
        let buff = Buffer.concat(datas, size);
        let result = iconv.decode(buff, "utf8");

        try {
    
    
            let d = JSON.parse(result);
            if( d.session_key ) {
    
    
                try {
    
                        
                    let wxCrypt = new WXBizDataCrypt(APP_ID, d.session_key);

                    // encryptedData, iv是客户端传递来的。
                    // 得到的res包含了openId、unionId、nickName等信息.
                    let res = wxCrypt.decryptData(encryptedData, iv);

                    /**
                     * 此时登录操作数据已经完成,可以正常进去游戏。
                     */
                } 
                catch (e) {
    
    
                    // 错误处理
                }
            } else {
    
    
                // 错误处理
            }
        }
        catch (e) {
    
    
            // 错误处理
        }
    });
});

4. Get the source code for free

I applied for and registered a WeChat public platform account, which was specially used to investigate its rules and restrictions. The following QR code is a small game demo written by myself, with login and sharing functions. For beginners, you can also private message me to get the source code and distribute it for free, just want to be able to scan the code to experience it (the message reply may not be timely, but I will definitely reply), so that I can explore later and share it with everyone .
insert image description here

Guess you like

Origin blog.csdn.net/HYNN12/article/details/109615046