關于小程式如何擷取使用者手機号問題,後端是springboot
第一次寫,還是關于小程式,不善于表達,是以直接傻瓜式代碼扔過來
首先,我以下的所有代碼都是開發模式下的,請自動忽略域名問題
另外,如果覺得寫的還可以,麻煩給個贊+好評
小程式端代碼:
wxml——頁面代碼
<button style="width:60%" class="bindwx1" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">
手機号一鍵登入
</button>
js——代碼
onLoad方法獲得code值
onLoad: function (options) {
var that = this;
wx.login({
success: function(res) {
console.log("onLoad=============="+res.code)//這就是code
that.setData({
code: res.code
})
},
})
},
然後是getPhoneNumber方法
getPhoneNumber: function (e) {
var that = this;
var phone = '';
if (e.detail.errMsg == "getPhoneNumber:ok") {
wx.request({
url: 'https://IP+端口号(或者你的域名)/webserviceImpl(你的接口)/obtainPhone(你的方法名)',//你的接口位址
data: {
encryptedData: e.detail.encryptedData,
iv: e.detail.iv,
code: that.data.code,
uid: "",
},
method: "post",
success: (res) =>{
console.log("getPhoneNumber傳回結果===============" +JSON.stringify(res));
//以下是代碼傳回的解析
if(res.data.code == "200"){
var phone = res.data.phone;
var showState = res.data.showState;
var openId = res.data.openId;
that.setData({
phone: phone
})
wx.navigateTo({
url: '../IndexPage/IndexPage?phone=' + phone
});
}else{
wx.showToast({
title: res.data.msg,
})
}
}
})
}
},
**
Java背景代碼
請注意,參數的接收方式一定要是json格式,此方法就是調用微信小程式的接口擷取到資訊,需要啥自己解析就可以,我這裡隻解析了openID,手機号
**
@RequestMapping(method = RequestMethod.POST,value = "/obtainPhone")
@ResponseBody
public JSONObject obtainPhone(HttpServletRequest request, HttpServletResponse response,
@RequestBody(required = true) String jsonStr) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
/*星号表示所有的域都可以接受,*/
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
JSONObject obj = new JSONObject();
JSONObject jsonStrs = JSONObject.parseObject(jsonStr);
String iv = (String) jsonStrs.get("iv");
String encryptedData = (String) jsonStrs.get("encryptedData");
String code = (String) jsonStrs.get("code");
String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";
String param = "appid="+APP_ID+"&secret="+SECRET+"&js_code="+code+"&grant_type=authorization_code";
String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
JSONObject json = JSONObject.parseObject(jsonString);
String sessionkey = json.getString("session_key");
String openId = json.getString("openid");
obj.put(CODE,CODE_0);
obj.put(MSG,MSG_0);
obj.put("openId",openId);
AESUtils aes = new AESUtils();
Base64 decoder = new Base64();
byte[] result = AESUtils.decrypt(decoder.decode(encryptedData), decoder.decode(sessionkey),
AESUtils.generateIV(decoder.decode(iv)));
//判斷傳回參數是否為空
if (null != result && result.length>0) {
Long orderinfo_id;
String phone = "";
try {
String jsons = new String(result, "UTF-8");
JSONObject json2 = JSONObject.parseObject(jsons);
//json解析phoneNumber值
phone = (String) json2.get("phoneNumber");
obj.put("phone",phone);
}catch (JSONException e){
e.printStackTrace();
}
}else{
obj.put(CODE,CODE_1);
obj.put(MSG,MSG_7);
return obj;
}
System.out.print("obtainPhone==============="+obj.toJSONString());
return obj;
}