最后有完整代码
1、获取code
onShow: function() {
var that = this;
//获取用户的本地缓存数据,userinfo信息是在用户授权登录时保存的
var n = wx.getStorageSync("userinfo");
//当本地缓存的用户名称不为""或者null时,设置userinfo信息
if(n.nickName != '' && n.nickName != null){
this.setData({
userinfo: n,
hasUserInfo:true,
canIUseGetUserProfile:true
})
// 通过wx.login获取登录凭证(code),然后通过code去获取我们用户的openid
wx.login({
success:(res)=>{
console.log(res);
that.getOpenId();
},
})
}
},
2、利用code获取sessionkey
小程序端:
getOpenId(){
var that=this
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: '自己的Control路径',
data: {
code: res.code
},
method: 'get',
header: {
'content-type': 'application/json' //默认值
},
success: function(res) { //res就是接收后台返回的数据
console.log(res.data);
that.setData({
sessionkey:res.data
})
},
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
Java后台:
@RequestMapping("名称") //获取sessionid
@ResponseBody
public static void getOpenId(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String appId="自己的appid";
String secret="小程序密钥";
String code=request.getParameter("code");
System.out.println(code);
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
+ "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
//这三个参数就是之后要填上自己的值。
//替换appid,appsecret,和code
String requestUrl = url;
//调用get方法发起get请求,并把返回值赋值给returnvalue
String returnvalue=GET(requestUrl);
System.out.println(requestUrl);//打印发起请求的url
System.out.println(returnvalue);//打印调用GET方法返回值
//定义一个json对象。
JSONObject convertvalue=new JSONObject();
//将得到的字符串转换为json
convertvalue=(JSONObject) JSON.parse(returnvalue);
System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
//把openid和sessionkey分别赋值给openid和sessionkey
String openid=(String) convertvalue.get("openid");
String sessionkey=(String) convertvalue.get("session_key");//定义两个变量存储得到的openid和session_key.
Gson gson=new Gson();
String json = gson.toJson(sessionkey);
Writer out = response.getWriter();
out.write(String.valueOf(json));
out.flush();
}
//发起get请求的方法。
public static String GET(String url) {
System.out.println("start");//打印发起请求的url
String result = "";
BufferedReader in = null;
InputStream is = null;
InputStreamReader isr = null;
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.connect();
Map<String, List<String>> map = conn.getHeaderFields();
is = conn.getInputStream();
isr = new InputStreamReader(is);
in = new BufferedReader(isr);
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
// 异常记录
} finally {
try {
if (in != null) {
in.close();
}
if (is != null) {
is.close();
}
if (isr != null) {
isr.close();
}
} catch (Exception e2) {
// 异常记录
}
}
return result;
}
获取小程序密钥:微信公众平台->开发管理->开发设置
3、获取iv和encryptedData并解密获取手机号
getPhoneNumber(e) {
var that=this;
console.log("手机号:")
wx.request({
url: '自己的Control路径',
data: {
sessionkey: that.data.sessionkey,
iv:e.detail.iv,
encryptedData:e.detail.encryptedData
},
method: 'get',
header: {
'content-type': 'application/json' //默认值
},
success: function(res) { //res就是接收后台返回的数据
console.log(res.data);
},
})
}
java后台:
@RequestMapping("decryptS5") //解密获取手机号
@ResponseBody
public static String decryptS5(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sSrc=request.getParameter("encryptedData");
String encodingFormat="utf-8";
String sKey=request.getParameter("sessionkey");
String ivParameter=request.getParameter("iv");
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] raw = decoder.decodeBuffer(sKey);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] myendicod = decoder.decodeBuffer(sSrc);
byte[] original = cipher.doFinal(myendicod);
System.out.println(new String(original, encodingFormat));
return new String(original, encodingFormat);
} catch (Exception ex) {
return null;
}
}
如果报错40029则可能是appid不对
4、完整代码
wxml:
<!--index.wxml-->
<view class="banner">
<view class="topContainer">
<view catchtap="showBcgImgArea">
<image class="userinfo-avatar" mode="aspectFill" src="{{userinfo.avatarUrl}}"></image>
</view>
<view>
<text class="userinfo-nickname">{{userinfo.nickName}}</text>
</view>
</view>
<button wx:if="{{!hasUserInfo && canIUseGetUserProfile}}" open-type="getUserInfo" bindtap="getUserProfile" class="userLogin">
点击登录
</button>
<button open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">获取用户手机号</button>
</view>
wxss:
.banner {
border-radius: 10rpx;
border: none;
box-sizing: content-box;
padding: 20rpx 0;
width: 90%;
height: 370rpx;
margin: 20rpx auto;
background:linear-gradient(109.6deg, rgb(204, 228, 247) 11.2%, rgb(237, 246, 250) 100.2%);
/* background-image:image("../../images/cloudbg.jpg"); */
text-align: center;
}
.topContainer {
width: 100%;
height: 260rpx;
background-size: 100%;
border-radius: 9px;
}
.userinfo-nickname {
color:black;
}
.userLogin{
width: 50%;
box-sizing: none;
font-size: medium;
}
.userinfo-avatar {
width: 150rpx;
height: 150rpx;
margin-bottom: 10rpx;
border-radius: 50%;
}
js:文章来源:https://www.toymoban.com/news/detail-523313.html
Page({
data: {
//用户基本信息(头像、昵称)
userinfo: {
avatarUrl:'../../images/ckbg1.png',
nickName:'未授权'
},
//是否已经获取用户信息
hasUserInfo: false,
//是否可以调用获取信息得函数
canIUseGetUserProfile: false,
sessionkey:"",
},
//第一次获取用户信息
getUserProfile : function(e){
wx.getUserProfile({
desc: '获取您的微信个人信息',
success:(res)=>{
this.setData({
userinfo:res.userInfo,
hasUserInfo:true
})
wx.setStorageSync('userinfo', res.userInfo)
},
fail:function(e){
wx.showToast({
title: '你选择了取消',
icon: "none",
duration: 1500,
mask: true
})
}
})
},
onLoad: function(n) {
this.setData({
canIUseGetUserProfile : true
})
},
onShow: function() {
var that = this;
//获取用户的本地缓存数据,userinfo信息是在用户授权登录时保存的
var n = wx.getStorageSync("userinfo");
//当本地缓存的用户名称不为""或者null时,设置userinfo信息
if(n.nickName != '' && n.nickName != null){
this.setData({
userinfo: n,
hasUserInfo:true,
canIUseGetUserProfile:true
})
// 通过wx.login获取登录凭证(code),然后通过code去获取我们用户的openid
wx.login({
success:(res)=>{
console.log(res);
that.getOpenId();
},
})
}
},
getOpenId(){
var that=this
wx.login({
success (res) {
if (res.code) {
wx.request({
url: ' ',
data: {
code: res.code
},
method: 'get',
header: {
'content-type': 'application/json' //默认值
},
success: function(res) { //res就是接收后台返回的数据
console.log(res.data);
that.setData({
sessionkey:res.data
})
},
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
getPhoneNumber(e) {
var that=this;
console.log("手机号:")
wx.request({
url: ' ',
data: {
sessionkey: that.data.sessionkey,
iv:e.detail.iv,
encryptedData:e.detail.encryptedData
},
method: 'get',
header: {
'content-type': 'application/json' //默认值
},
success: function(res) { //res就是接收后台返回的数据
console.log(res.data);
},
})
}
})
Java后台文章来源地址https://www.toymoban.com/news/detail-523313.html
@RequestMapping(" ") //获取sessinoid
@ResponseBody
public static void getOpenId(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String appId=" ";
String secret=" ";
String code=request.getParameter("code");
System.out.println(code);
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
+ "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
//这三个参数就是之后要填上自己的值。
//替换appid,appsecret,和code
String requestUrl = url;
//调用get方法发起get请求,并把返回值赋值给returnvalue
String returnvalue=GET(requestUrl);
System.out.println(requestUrl);//打印发起请求的url
System.out.println(returnvalue);//打印调用GET方法返回值
//定义一个json对象。
JSONObject convertvalue=new JSONObject();
//将得到的字符串转换为json
convertvalue=(JSONObject) JSON.parse(returnvalue);
System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
//把openid和sessionkey分别赋值给openid和sessionkey
String openid=(String) convertvalue.get("openid");
String sessionkey=(String) convertvalue.get("session_key");//定义两个变量存储得到的openid和session_key.
Gson gson=new Gson();
String json = gson.toJson(sessionkey);
Writer out = response.getWriter();
out.write(String.valueOf(json));
out.flush();
}
//发起get请求的方法。
public static String GET(String url) {
System.out.println("start");//打印发起请求的url
String result = "";
BufferedReader in = null;
InputStream is = null;
InputStreamReader isr = null;
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.connect();
Map<String, List<String>> map = conn.getHeaderFields();
is = conn.getInputStream();
isr = new InputStreamReader(is);
in = new BufferedReader(isr);
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
// 异常记录
} finally {
try {
if (in != null) {
in.close();
}
if (is != null) {
is.close();
}
if (isr != null) {
isr.close();
}
} catch (Exception e2) {
// 异常记录
}
}
return result;
}
/**
* 解密工具直接放进去即可
*/
@RequestMapping("decryptS5") //解密获取手机号
@ResponseBody
public static String decryptS5(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sSrc=request.getParameter("encryptedData");
String encodingFormat="utf-8";
String sKey=request.getParameter("sessionkey");
String ivParameter=request.getParameter("iv");
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] raw = decoder.decodeBuffer(sKey);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] myendicod = decoder.decodeBuffer(sSrc);
byte[] original = cipher.doFinal(myendicod);
System.out.println(new String(original, encodingFormat));
return new String(original, encodingFormat);
} catch (Exception ex) {
return null;
}
}
到了这里,关于微信小程序——获取用户手机号(Java后台)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!