获取用户的头像昵称等信息
首先获取用户授权,授权允许之后则获取用户的userinfo
获取之后可以直接控制台输出,或者存储到全局变量中globelData
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
that.globalData.userInfo = res.userInfo
console.log(res.userInfo)
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
如果需要获取用的openid则需要调用自己的后台来解码微信提供的信息
package openid;
import net.sf.json.JSONObject;
public class getid {
public String getopenid(String code) {
String appid="自己的appid";
String secret="自己的secret";
getopenid getopenid=new getopenid();
//调用访问微信服务器工具方法,传入三个参数获取带有openid、session_key的json字符串
String jsonId=getopenid.getopenid(appid,code,secret);
JSONObject jsonObject = JSONObject.fromObject(jsonId);
//从json字符串获取openid和session_key
String openid=jsonObject.getString("openid");
String session_key=jsonObject.getString("session_key");
return openid;
}
}
package openid;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class getopenid {
public String getopenid(String appid,String code,String secret) {
BufferedReader in = null;
//appid和secret是开发者分别是小程序ID和小程序密钥,开发者通过微信公众平台-》设置-》开发设置就可以直接获取,
String url="https://api.weixin.qq.com/sns/jscode2session?appid="
+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
try {
URL weChatUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = weChatUrl.openConnection();
// 设置通用的请求属性
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e1) {
throw new RuntimeException(e1);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
通过上面两个类就可以获取到小程序用户的openid,每个用户对应不同的openid