小程序基于java后台获取openid和sessionkey
背景:因为业务功能需要获取到用户的openid和sessionkey,
通过openid我们可以唯一识别每一个用户,进而提供个性化服务。
前提限制:
微信不允许小程序直接获取openid等加密信息,必须通过后台来获取。想通过小程序获取到openid是不可能的。
因为:在后台配置服务器域名时:如果写“api.weixin.qq.com”会报错的。
所以我们在小程序可以得到的是code,然后将code发送到后台服务器。
wx.login({
success: function(res) {
if (res.code) { //wx.login获取code。
//发起网络请求
wx.request({
url: '-填写后台服务器地址-',
data: {
code: res.code //将code发送到后台服务器。
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
}
这个是官方介绍:官方文档地址
获取用户openid,
①首先通过wx.login获取到用户的登陆凭证code,
同一个用户每次通过wx.login获取到的code是不相同的,然后小程序将code发送到后台,后台通过此code结合开发者的appid和appsecret向微信服务器获取到此用户的openid和其他信息,同一个用户获取到的openid总是相同的(是code不相同)。
java后台代码
需要引入的jar包:
import java.net.URL;
import java.net.URLConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@ResponseBody
@RequestMapping("---------")//此处填自己要用到的项目名。
public static void getOpenid(@RequestParam(value="code",required=false)String getcode) {//接收用户传过来的code,required=false表明如果这个参数没有传过来也可以。
// String code=getcode;
//接收从客户端获取的code
//向微信后台发起请求获取openid的url
String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
//这三个参数就是之后要填上自己的值。
//替换appid,appsecret,和code
String requestUrl = WX_URL.replace("APPID", "------------------").//填写自己的appid
replace("SECRET", "----------------------").replace("JSCODE", code).//填写自己的appsecret,
replace("authorization_code", "authorization_code");
//调用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.
return openid;//返回openid
}
//发起get请求的方法。
public static String GET(String 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;
}
/*此方法没有用到。就先放在这吧
public static String jedisOperate(String Session_key, String openid) {
//这里需要引入一下jedis的dependenicy
Jedis jedis = new Jedis("localhost");
String openid = openid;
String session_key = session_key;
String uid = UUID.randomUUID().toString();
StringBuffer sb = new StringBuffer();
sb.append(openid);
sb.append(","+session_key);
jedis.set(uid, sb.toString());
return uid;
//如果需要获取登录用户的用户名和昵称,我们就需要注意一个问题,如果昵称中有中文就会出现乱码,这是因为微信对于中文是按照ISO-8859-1来进行编码的而我们需要的utf8编码,对于获取用户昵称出现乱码这个问题我们做一下简单的处理就可以解决:
//String nickNameDecode = new String(nickName.getBytes("ISO-8859-1"),"utf-8");
}*/
更多推荐
所有评论(0)