微信小程序 springboot后台如何获取用户的openid

网友投稿 441 2022-12-26


微信小程序 springboot后台如何获取用户的openid

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: reshttp://.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{KDCdN//请求微信服务器,用code换取openid。HttpUtil是工具http://类,后面会给出实现,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中

commons-httpclient

commons-httpclient

3.1

**/

public class HttpUtil {

public static String doGet(String urlPath, HashMap params)

throws Exception {

StringBuilder sb = new StringBuilder(urlPath);

if (params != null && !params.isEmpty()) { // 说明有参数

sb.append("?");

Set> setKDCdN = params.entrySet();

for (Entry 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;

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:用户系统接口设计(接口设计用户接口)
下一篇:免费api测试工具(常见的api自动化测试工具)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~