微信小程序 springboot后台如何获取用户的openid
作者:SupermanH 时间:2023-01-13 17:07:42
openid可以标识一个用户,session_key会变,所以来获取一下openid。
openid不能在微信小程序中直接获取,需要后台发送请求到微信的接口,然后微信返回一个json格式的字符串到后台,后台处理之后,再返回到微信小程序。
发布的小程序需要https的域名,而测试的时候可以使用http。
小程序在app.js中,修改login()中的内容:
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
wx.request({
url: 'http://localhost:84/user/login',
method: 'POST',
data: {
code: res.code
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success(res) {
console.log("openid:"+res.data.openid);
if (res.data.openid != "" || res.data.openid!=null){
// 登录成功
wx.setStorageSync("openid", res.data.openid);//将用户id保存到缓存中
wx.setStorageSync("session_key", res.data.session_key);//将session_key保存到缓存中
}else{
// 登录失败
// TODO 跳转到错误页面,要求用户重试
return false;
}
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
这里请求的http://localhost:84/user/login
后台的处理类:
package com.ft.feathertrade.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ft.feathertrade.entity.OpenIdJson;
import com.ft.feathertrade.utils.HttpUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class LoginHandler {
private String appID = "";
private String appSecret = "";
@PostMapping("/user/login")
public String userLogin(@RequestParam("code") String code) throws IOException {
String result = "";
try{//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
result = HttpUtil.doGet(
"https://api.weixin.qq.com/sns/jscode2session?appid="
+ this.appID + "&secret="
+ this.appSecret + "&js_code="
+ code
+ "&grant_type=authorization_code", null);
}
catch (Exception e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);
System.out.println(result.toString());
System.out.println(openIdJson.getOpenid());
return result;
}
}
HttpUtil工具类:
package com.ft.feathertrade.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.httpclient.HttpStatus;//此类需要添加maven依赖或jar包
/** 将此依赖添加到pom.xml中
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
**/
public class HttpUtil {
public static String doGet(String urlPath, HashMap<String, Object> params)
throws Exception {
StringBuilder sb = new StringBuilder(urlPath);
if (params != null && !params.isEmpty()) { // 说明有参数
sb.append("?");
Set<Entry<String, Object>> set = params.entrySet();
for (Entry<String, Object> entry : set) { // 遍历map里面的参数
String key = entry.getKey();
String value = "";
if (null != entry.getValue()) {
value = entry.getValue().toString();
// 转码
value = URLEncoder.encode(value, "UTF-8");
}
sb.append(key).append("=").append(value).append("&");
}
sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
}
// System.out.println(sb.toString());
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 5s超时
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpStatus.SC_OK) {// HttpStatus.SC_OK ==
// 200
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sbs = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sbs.append(line);
}
return sbs.toString();
}
return null;
}
}
OpenIdJson的实体类:
package com.ft.feathertrade.entity;
public class OpenIdJson {
private String openid;
private String session_key;
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key;
}
}
来源:https://www.cnblogs.com/to-red/p/11563854.html
标签:微信,小程序,spring,boot,获取,openid
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringMVC实现数据绑定及表单标签
2022-03-24 18:06:47
![](https://img.aspxhome.com/file/2023/8/68568_0s.png)
Android编程之消息机制实例分析
2023-07-28 07:24:38
超详细的Spring Boot入门笔记(总结)
2022-10-26 18:44:21
![](https://img.aspxhome.com/file/2023/4/61254_0s.png)
Java中synchronized关键字修饰方法同步的用法详解
2022-03-05 07:11:22
java中javaBean与Bean的深入理解
2021-11-27 13:19:11
Spring MVC学习教程之视图深入解析
2021-12-16 23:37:55
深入理解Spring事务原理
2022-01-18 04:16:39
![](https://img.aspxhome.com/file/2023/7/61777_0s.jpg)
详解基于spring多数据源动态调用及其事务处理
2023-06-23 14:37:25
![](https://img.aspxhome.com/file/2023/0/57530_0s.png)
springboot+log4j.yml配置日志文件的方法
2023-08-07 11:33:17
![](https://img.aspxhome.com/file/2023/5/67955_0s.png)
C#将html table 导出成excel实例
2023-12-20 04:58:55
Jenkins的安装配置详解
2023-08-27 11:31:42
![](https://img.aspxhome.com/file/2023/6/62166_0s.png)
一篇文章带你入门Java基本概念
2023-11-26 01:17:08
![](https://img.aspxhome.com/file/2023/8/60318_0s.png)
探讨:android项目开发 统筹兼顾 需要考虑的因素
2023-08-05 11:21:32
Mybatis配置解析看这一篇就够了
2023-05-15 22:42:12
![](https://img.aspxhome.com/file/2023/1/64551_0s.png)
在IntelliJ IDEA中使用gulp的方法步骤(图文)
2022-10-12 06:29:08
![](https://img.aspxhome.com/file/2023/0/60770_0s.png)
微信小程序获取手机号,后端JAVA解密流程代码
2023-11-29 07:57:26
学生视角带你了解Java内部类
2022-09-29 17:51:04
![](https://img.aspxhome.com/file/2023/9/62429_0s.png)
Android 实现可任意拖动的悬浮窗功能(类似悬浮球)
2023-08-07 10:19:05
Hibernate环境搭建与配置方法(Hello world配置文件版)
2022-07-31 06:26:04
详解SpringBoot注册Windows服务和启动报错的原因
2022-12-28 17:10:09
![](https://img.aspxhome.com/file/2023/1/63431_0s.jpg)