.NET6+uniapp微信小程序获取用户手机号

2022年7月4日 206点热度 0人点赞 0条评论

最近一个朋友要去给他做个微信小程序,会涉及到获取用户手机号的场景,这里,我前端用的uniapp,后端则用的.NET6,如果用.NET开发微信公众号或小程序的话,我相信大部分人应该都有听说过盛派微信SDK

引入盛派SDK

这里先引入Senparc.Weixin.AspNetSenparc.Weixin.WxOpen两个包,安装完成后进入appsetting.json配置小程序的相关信息,

1
2
3
4
5
"SenparcWeixinSetting": {
"IsDebug": false,
"WxOpenAppId": "小程序appId",
"WxOpenAppSecret": "小程序Secret"
}

图片

再进入Program.cs注册盛派微信SDK的相关配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
builder.Services.AddMemoryCache();
builder.Services.AddSenparcWeixinServices(builder.Configuration);
var app = builder.Build();

var senparcWeixinSetting = app.Services.GetService<IOptions<SenparcWeixinSetting>>()!.Value;
//启用微信配置(必须)
var registerService = app.UseSenparcWeixin(app.Environment,
null /* 不为 null 则覆盖 appsettings 中的 SenpacSetting 配置*/,
null /* 不为 null 则覆盖 appsettings 中的 SenpacWeixinSetting 配置*/,
register => { },
(register, weixinSetting) =>
{
//注册公众号信息(可以执行多次,注册多个小程序)
register.RegisterWxOpenAccount(weixinSetting, "小程序");
});

图片

现在,我们可使用盛派微信SDK提供的API来获取手机号了。新建一个controller来调用API

1
2
3
4
5
6
7
8
9
10
11
12
13
public class WxOpenController : ControllerBase
{
public static readonly string WxOpenAppId = Config.SenparcWeixinSetting.WxOpenAppId;
public static readonly string WxOpenAppSecret = Config.SenparcWeixinSetting.WxOpenAppSecret;

[HttpGet("get-phone/{Code}")]
public string GetUserPhone(string Code)
{
//通过`getPhoneNumber`得到的Code来获取手机号
var result = BusinessApi.GetUserPhoneNumber(WxOpenAppId, Code);
return result.phone_info.phoneNumber;
}
}

图片

uniapp获取code

在2.21.2版本之后,获取手机号不需要提前调用login进行登录,直接通过按钮触发getPhoneNumber获得的code去换取手机号或者是encryptedDataIV去解密,
图片
我们先在界面新增一个按钮

1
2
3
4
5
6
<template>
<view class="content">
<u-button size="normal" icon="account-fill" plain type="warning" open-type="getPhoneNumber"
@getphonenumber="getPhoneNumber" text="获取手机号"></u-button>
</view>
</template>

然后,编写getPhoneNumber方法

1
2
3
4
5
6
7
8
9
10
11
12
getPhoneNumber(e) {
console.log(e);
if (e.detail.errMsg != 'getPhoneNumber:ok') {
uni.$u.toast("获取手机号失败");
return;
}
console.log(e.detail.code);
let url = `http://localhost/api/WxOpen/get-phone/${e.detail.code}`;
uni.$u.http.get(url).then(result => {
console.log(result);
});
},

这里的$u.http.getuView里面的工具类,如果没有用到uView就直接用uniapp里面的请求方法。

图片
图片

这里,我们是用的code获取手机号的方式。盛派SDK也提供了encryptedDataIV解密的API,使用起来还是非常方便。

46730.NET6+uniapp微信小程序获取用户手机号

这个人很懒,什么都没留下

文章评论