微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。

时间:2023-03-09 08:37:17
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。

在这里给大家分享下我的心得,1.写代码前一定要对整个流程有个了解。我就是因为在先不了解整个过程中去ctrl+c+v他人的博客代码,花费很多无用的时间去处理还不知道能不能跑的起来的代码。

              2.本人比较喜欢手画图理解,本人亲测,印象很深刻。

              

在此声明因为是后端所以前端的代码就不写在上面了,有疑问留言,能帮我会帮。

谢谢这个博主:(解密+post大家可以看这个博主的代码)https://blog.****.net/guochanof/article/details/80189935

微信服务端api:https://developers.weixin.qq.com/miniprogram/dev/api-backend/auth.code2Session.html

请求微信api接口:GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

1.根据前端用户授权即会产生一个code用户登陆时获取的标识(这个code的声明周期是存活5分钟,5分钟过后就没用了)。

2.开发者服务器即我获取到前端传过来的code,另外还有3个固定的一个是appid(小程序的appid)、secret(小程序appSecret)、grant_type(授权类型,authorization_code)

3.根据2中的code+appid+secret+grant_type调用微信api接口返回的是JSON数据包:openid(用户唯一标识)、session_key(会话密钥)

a:首先我定义一个常量类,里面写有appid、secret、authorization_code这三个是固定不变的。

/**
*
* 用于微信授权:固定不变的常量
*
* */ public class WeiXin { public static final String APPID = "xxxxxx"; public static final String APP_SECRECT = "xxxxxx"; public static final String AUTHORIZATION_CODE = "authorization_code"; }

添加一个工具类即获取资源路径的工具

b、HttpRequest.java 工具类 (整段复制即可无需修改)

package com.zzh.demo.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map; public class HttpRequest { public static void main(String[] args) {
//发送 GET 请求
String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
System.out.println(s); // //发送 POST 请求
// String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
// JSONObject json = JSONObject.fromObject(sr);
// System.out.println(json.get("data"));
} /**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
} C:这个类里我把code写死了目的是为了便于测试是否能获取到微信服务器的用户唯一标识openid和会话密钥session_key
注意一下:要导入这个包字符串转json格式数据时
import org.json.JSONObject;
下面是代码:
import com.zzh.demo.base.common.WeiXin;
import com.zzh.demo.base.utils.HttpRequest;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap;
import java.util.Map; @Controller
@RequestMapping("/api/Autozi")
public class TestWxAuthorization {
/**
    * @Title: decodeUserInfo
    * @author:lizheng
    * @date:2018年3月25日
    * @Description: 解密用户敏感数据 * @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET)
@ResponseBody
public Map decodeUserInfo() { Map map = new HashMap(); /////////////////////////////////////////////////////////////////////////自己定义的code String code = "xxxxxxx"; // 登录凭证不能为空
if (code == null || code.length() == 0) {
map.put("status", 0);
map.put("msg", "code 不能为空");
return map;
} // 小程序唯一标识 (在微信小程序管理后台获取)
String wxspAppid = WeiXin.APPID;
// 小程序的 app secret (在微信小程序管理后台获取)
String wxspSecret = WeiXin.APP_SECRECT;
// 授权(必填)
String grant_type = WeiXin.AUTHORIZATION_CODE; //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
// 请求参数
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
+ grant_type;
// 发送请求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params); //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
try {
// 解析相应内容(转换成json对象)
JSONObject json = new JSONObject(sr);
// 获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
// 用户的唯一标识(openid)
String openid = (String) json.get("openid").toString(); map.put( "session_key",session_key);
map.put( "openId",openid );
} catch (Exception e) {
e.printStackTrace();
}
return map;
} } 下面是运行获取到的数据。有些的不对的地方请指正一定改。

微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。