一、功能需求
用户打开微信小程序弹出登录页面。点击头像框后底部弹出用户的微信头像;点击昵称输入框后底部弹出用户的微信名。用户可以选择使用自己的微信信息进行填充,也可以选择填写新的信息。用户登录后,后端可以获取用户的oppenid并保存在数据库中。
补充:新版本的微信API不能强制获取用户的头像昵称等信息,用户信息只能由用户自己填写。
二、实现过程
1、用户信息填写组件
<template>
<button open-type="chooseAvatar" @chooseavatar="getAvatar">
<view class="avatar">
<view>头像</view>
<view>
<image :src="customerInfo.avatarUrl"></image>
</view>
</view>
</button>
<view>
昵称<input placeholder="请输入昵称" type="nickname" v-model="customerInfo.nickname">
</view>
<button size="default" type="primary" @click="saveCustomerInfo">保存</button>
</template>
<script>
export default {
data() {
return {
customerInfo:
{
nickname: '',
avatarUrl: '',
session_key: ''
}
}
},
}
</script>
2、获取用户登录凭证
uni.login({
success: function (res) {
console.log(res.code);
}
});
补充:后端需要使用登录凭证code才能换取用户的openid 和session_key等信息。
3、前端完整代码
<template>
<button open-type="chooseAvatar" @chooseavatar="getAvatar">
<view class="avatar">
<view>头像</view>
<view>
<image :src="customerInfo.avatarUrl"></image>
</view>
</view>
</button>
<view>
昵称<input placeholder="请输入昵称" type="nickname" v-model="customerInfo.nickname">
</view>
<button size="default" type="primary" @click="saveCustomerInfo">保存</button>
</template>
<script>
export default {
data() {
return {
customerInfo:
{
nickname: '',
avatarUrl: '',
session_key: ''
}
}
},
methods: {
getAvatar(res) {
this.customerInfo.avatarUrl = res.detail.avatarUrl;
},
saveCustomerInfo() {
uni.login({
success: function(res) {
uni.request({
url:'https://localhost:7106/WXLogin/GetKeyOfOpenId?authorizationCode='+res.code,
method:'POST',
success:function(res){customerInfo.session_key = res.data;},
});
}
}
}
</script>
4、获取用户的openid
openid是用户使用某一个小程序的唯一标识符,openid可以在某个小程序内唯一标识一个用户。(同一用户在不同的小程序中会有不同的openid)
此项目后端使用.net core框架开发。后端获接收登录凭证code,以code、小程序的appId和secretkey为参数向腾讯服务器发送请求换取oppenid。
[ApiController]
[Route("[controller]/[action]")]
public class WXLoginController:ControllerBase
{
private readonly IDistributedCache redis_cache;
private readonly IConfiguration configuration;
public WXLoginController(IDistributedCache redis_cache, IConfiguration configuration)
{
this.redis_cache = redis_cache;
this.configuration = configuration;
}
[HttpPost]
public async Task<ActionResult> GetKeyOfOpenId(string authorizationCode)
{
//从secret.json配置文件中获取appId和secretKey
string appId = configuration.GetValue<string>("appId");
string secretKey = configuration.GetValue<string>("secretKey");
//腾讯服务器提供的API
var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secretKey}&js_code={authorizationCode}&grant_type=authorization_code";
//发送请求
string res = await new HttpClient().GetStringAsync(url);
Console.WriteLine(res);
if (!string.IsNullOrEmpty(res))
{
//反序列化res
Res json = Newtonsoft.Json.JsonConvert.DeserializeObject<Res>(res);
//将openid存入redis中,设置过期时间
var options = new DistributedCacheEntryOptions();
options.SlidingExpiration = TimeSpan.FromDays(1);
redis_cache.SetString(json.Session_key, json.Openid, options);
return Ok(json.Session_key);
}
else
{
return BadRequest("openid获取失败!");
}
}
}
Console.WriteLine(res)的结果如下,腾讯服务器返回的session_key和openid。
{"session_key":"GyYAdclCKqR27ILK0LWccw==","openid":"oroJg5LB7cYJUvGhlUQsc_Oa****"}
5、补充说明
openid泄露泄露可能导致用户在小程序的账号被其他人登录,微信官方文档不建议将oppenid保存在前端。因此本项目将session_key和oppenid设为键值对存入redis中,只返回具有过期时间的session_key给前端。
appId和secretKey是小程序的重要信息,可以在微信开发者平台查看。本项目为了防止appId和secretKey泄露,将其写在了secret.json配置文件中。