文章目錄
- 一、微信小程序開發
- 二、使用步驟
- 1.前端代碼
- 2.后臺配置
- 3.后臺代碼
- 總結
一、微信小程序開發
目前個人的小程序無法使用手機號碼授權登錄,可以使用測試號進行開發
二、使用步驟
1.前端代碼
代碼如下(示例):
<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);}})}
}}
2.后臺配置
# 小程序配置
applet:appId: wx53fda****c6b0a3appSecret: ade99d6dca77****f52fecd5d35039b5grantType: authorization_code
3.后臺代碼
代碼如下(示例):
/*** 微信小程序手機號碼授權登錄* @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;
}
總結
人生物語:別哭泣,別嘆息。悲傷喚不回逝去的時光。做一個簡單的人,看得清世間繁雜卻不在心中留下痕跡,保持平常心,簡單,快樂。請別把我當傻瓜,有些事不是我不知道,只是我看在眼里,埋在心里。一個人最好記性不要太好,因為回憶越多,幸福感越少。