微信小游戏官方文档写得确实有点深奥了,给大家整理了一篇简单易读的,只需要跟着操作就可以实现微信 UnionID 和微信昵称的获取。
已经实机测试过,可以直接复制使用!
获取 UnionID
开发者可以直接通过 wx.login +
code2Session
获取到该用户 UnionID,无须用户授权。
具体流程为:
-
在客户端调用微信 SDK 中的 WX.Login 方法,在成功回调中得到 res.code
-
请求微信提供的接口,得到 UnionID 等信息
- 接口: api.weixin.qq.com/sns/jscode2…
- 参数:上一步骤中得到的 res.code、微信小游戏 AppID 和 AppSecret
- 说明:因为请求接口需要用到微信小游戏的敏感信息,不推荐在客户端调用,容易泄露信息。更好的用法是将微信小游戏 AppID 和 AppSecret 放在服务端,服务端请求微信接口,并提供一个接口给客户端。
客户端直接请求(不推荐)
注意:此处微信 AppID 和 AppSecret 在微信公众平台(mp.weixin.qq.com)登录后,点击【管理-开发管理】,找到【开发者 ID 】一项。
// namespace:
// using UnityEngine;
// using WeChatWASM;
// using System.Threading.Tasks;
// using UnityEngine.Networking;
/// <summary>
/// 获取微信 UUID
/// </summary>
public static async Task<string> GetWechatUUID()
{
var tcs = new TaskCompletionSource<string>();
WX.Login(new LoginOption()
{
success = async (res) =>
{
Debug.Log("微信获取 code 成功");
Debug.Log(res.code);
var appID = "wxxxx";
var appSecret = "xxxxxxxx";
var uri =
$"https://api.weixin.qq.com/sns/jscode2session?appid={appID}&secret={appSecret}&js_code={res.code}&grant_type=authorization_code";
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// 发送请求并等待响应
var operation = webRequest.SendWebRequest();
// 等待请求完成
while (!operation.isDone)
{
await Task.Yield(); // 让出控制权,直到请求完成
}
// 检查是否有错误
if (webRequest.result != UnityWebRequest.Result.Success)
{
Debug.LogError($"Error: {webRequest.error}");
tcs.SetResult("");
}
else
{
var result = JsonUtility.FromJson<WeixinLoginResult>(webRequest.downloadHandler.text);
tcs.SetResult(result.openid);
}
}
},
fail = (err) =>
{
Debug.Log("微信获取 code 失败");
Debug.Log(err.errMsg);
tcs.SetResult("");
}
});
return await tcs.Task;
}
获取微信昵称
获取微信昵称需要用户授权,需要先配置《用户隐私保护指引》并开启隐私授权弹窗。 然后在客户端中,通过 wx.getSetting 判断是否已授权。若已授权,调用 wx.getUserInfo 获取信。若未授权,调用 wx.createUserInfoButton 创建按钮,用户主动点击后授权后获取信息。若用户未授权,需要做好兜底。
具体流程如下:
1. 配置《用户隐私保护指引》
- 登录小游戏后台 mp.weixin.qq.com
- 点击左下角账户头像,弹出菜单,选择【账号设置】
- 在【基本设置】tab 中,往下翻到【服务内容声明】部分
- 点击【用户隐私保护指引】的【去完善】按钮
-
勾选实际用到的用户信息类型
-
按照要求填写并生成协议
2. 开启【隐私授权弹窗】
还是服务内容声明的位置,点击【隐私授权弹窗】,点击【设置】按钮
3. 客户端检查授权,获取用户信息
-
通过 wx.getSetting 判断是否已授权
- 已授权,调用 wx.getUserInfo 获取信息
- 未授权,调用 wx.createUserInfoButton 创建按钮,用户主动点击后授权后获取信息
- 用户未授权,则需要有兜底逻辑
C# 代码参考:
// namespace:
// using UnityEngine;
// using WeChatWASM;
// using System.Threading.Tasks;
/// <summary>
/// 获取微信 userinfo
/// </summary>
private Task<UserInfo> GetWechatUserInfo()
{
var tcs = new TaskCompletionSource<UserInfo>();
WX.GetSetting(new GetSettingOption()
{
fail = (err) =>
{
Debug.Log("get setting fail");
Debug.Log(err.errMsg);
tcs.SetResult(null);
},
success = (res) =>
{
if (res.authSetting.TryGetValue("scope.userInfo", out var hasUserInfo))
{
if (hasUserInfo)
{
// 已授权
WX.GetUserInfo(new GetUserInfoOption()
{
success = userInfoRes =>
{
Debug.Log("get user info success. nickname:");
Debug.Log(userInfoRes.userInfo.nickName);
tcs.SetResult(userInfoRes.userInfo);
},
fail = err =>
{
tcs.SetResult(null);
}
});
}
}
// 未授权
if (!hasUserInfo)
{
// 绘制全屏区域按钮
var button = WX.CreateUserInfoButton(0, 0, Screen.width, Screen.height, "", true);
button.OnTap((tapRes) =>
{
Debug.Log("press button");
button.Hide();
WX.GetUserInfo(new GetUserInfoOption()
{
success = userInfoRes =>
{
// 用户授权
Debug.Log("get user info success. nickname:");
Debug.Log(userInfoRes.userInfo.nickName);
tcs.SetResult(userInfoRes.userInfo);
},
fail = (err) =>
{
// 用户未授权
Debug.Log("get user info fail");
Debug.Log(err.errMsg);
tcs.SetResult(null);
}
});
});
}
},
});
return tcs.Task;
}
4. 关于迷人的 wx.createUserInfoButton 的用法
简单一点,直接全屏区域触发,可以节省从屏幕坐标到 unity canvas 坐标转换之间复杂的计算。
WX.CreateUserInfoButton(0, 0, Screen.width, Screen.height, "", true);
5. 关于无需授权方式的说明【能力已收回】
文档中提到了有不需要用户授权的方式,但是仔细查阅其他文档,发现该能力已经收回。(如下图,详见:developers.weixin.qq.com/community/d…
而且该方法也仅用于展示,开发者提供绘制的 canvas,微信 SDK 将昵称等绘制在其上。开发者无法直接获得微信昵称,用途很局限,使用起来也麻烦。
参考资料
获取微信 UnionID:developers.weixin.qq.com/minigame/de…