目前个人的小程序无法使用手机号码授权登录,可以使用测试号进行开发
代码如下(示例):
<button open-type="getPhoneNumber" bindgetphonenumber="getUserPhoneNumber">立即登录button>
Page({
getUserPhoneNumber(event) {
if(event.detail.errMsg != "getPhoneNumber:ok") {
// 授权失败
return false;
}
// 发起请求,进行授权登录
wx.request({
url: app.globalData.basePath + "/system/applet/login",
data: {
phoneCode: event.detail.code
},
method:"POST",
success: res => {
console.log(res.data);
wx.setStorageSync("applet", res.data);
}
})
}
}}
# 小程序配置
applet:
appId: wx53fda****c6b0a3
appSecret: ade99d6dca77****f52fecd5d35039b5
grantType: authorization_code
代码如下(示例):
package com.ruoyi.system.domain.io;
public class AppletLoginInput {
private String phoneCode;
private String iv;
private String encryptedData;
public String getPhoneCode() {
return phoneCode;
}
public void setPhoneCode(String phoneCode) {
this.phoneCode = phoneCode;
}
public String getIv() {
return iv;
}
public void setIv(String iv) {
this.iv = iv;
}
public String getEncryptedData() {
return encryptedData;
}
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
}
package com.ruoyi.system.domain.io;
public class AppletLoginOutput {
/**
* token信息
*/
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
/**
* 微信小程序手机号码授权登录
* @param input
*/
@Anonymous
@PostMapping("/login")
public AppletLoginOutput login(@RequestBody AppletLoginInput input) {
AppletLoginOutput appletLoginOutput = new AppletLoginOutput();
// 首先获取最新的token信息
String tokenParam = "appid=" + appletConfig.getAppId() + "&secret=" + appletConfig.getAppSecret() + "&grant_type=client_credential";
String tokenResult = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", tokenParam);
JSONObject tokenJSONObject = JSONObject.parseObject(tokenResult);
// 通过登录信息获取用户的手机号码
// 获取token 信息
String body = "{\"code\": \"" + input.getPhoneCode() + "\"}";
HttpRequest post = HttpUtil.createPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + tokenJSONObject.getString("access_token"));
post.header("Content-Type", "application/json");
post.body(body);
HttpResponse execute = post.execute();
AppletResultModel resultModel = JSONObject.parseObject(execute.body(), AppletResultModel.class);
String jsonString = JSONObject.toJSONString(resultModel);
System.out.println(jsonString);
// {"errcode":0,"errmsg":"ok","phone_info":{"countryCode":"86","phoneNumber":"178****3721","purePhoneNumber":"178****3721","watermark":{"appid":"wx53fda****1c6b0a3","timestamp":1754865784}}}
return appletLoginOutput;
}