手把手教你使用java对接微信公众号-获取微信用户基本信息
程序员文章站
2024-01-08 12:44:04
...
1、登录自己测试公众号,找到“网页服务”中的“网页授权获取用户基本信息”;进入。
2、看到接口文档的微信网页开发的步骤。
以上实现获取用户信息有5步骤,但在实际使用中,我们只使用了(1、2 、4)三个步骤即可。
3、首页实现第一步骤,写一个单点登录的页面。
图中是前端页面第一步骤单点登录的地址,其中的scope、redirect_uri最为重要,一个是获取用户基本信息的权限,一个是微信端跳转到你登录页面,然后会带入code和state字段给我们的页面。
编写我们登录页面基础逻辑是截取地址栏的code字段(如果有需要state字段也是同样取法),然后调用后台接口将code发过去,在使用第2、4步骤获取用户信息。
4、将前端页面的登录地址配置到测试号里面。
点击上图中的“修改”,如图
从图中可以看出,回调页面(前端的登录页面)可以写域名或者IP,正式环境只支持域名,这个地址必须是外网地址,本地的话可以使用内网穿通的工具实现。
5、编写后台接口,实现2、4步骤。
WxUserController类
package com.example.mybaties.controller;
import com.example.mybaties.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: 通过code获取用户信息
* @Author: lst
* @Date 2020-08-20
*/
@RestController
@Api(value = "WxUserController", tags = "通过code获取用户信息")
public class WxUserController {
@Autowired
private WxUserService wxUserService;
@GetMapping(value = "/get-user", produces = "application/json; charset=utf-8")
@ApiOperation(value = "通过code获取用户信息", notes = "通过code获取用户信息", code = 200, produces = "application/json")
@ApiImplicitParam(paramType = "query", dataType = "string", name = "code",required = true ,value = " code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。")
public String getUser(@RequestParam(name = "code",required = true) String code) {
return wxUserService.getUser(code);
}
}
WxUserServiceImpl实现类
package com.example.mybaties.service.impl;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.example.mybaties.entity.User;
import com.example.mybaties.entity.UserExcelProperty;
import com.example.mybaties.mapper.UserMapper;
import com.example.mybaties.service.UserService;
import com.example.mybaties.service.WxUserService;
import com.example.mybaties.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author lst
* @version 1.0
* @Description: 通过code获取用户信息
* @date 2020-08-20
*/
@Service
@Slf4j
public class WxUserServiceImpl implements WxUserService {
@Value("${wx.appid}")
public String appId;
@Value("${wx.appsecret}")
public String appSecret;
@Value("${wx.lang}")
public String lang;
@Override
public String getUser(String code) {
//TODO 1、通过code获取access_token
Map<String, Object> params = new HashMap<>();
String url = WxUtil.GET_ACCESS_TOKEN_URL;
params.put("appid",appId);
params.put("secret",appSecret);
params.put("code",code);
params.put("grant_type","authorization_code");
jsonObject = JSONObject.parseObject(HttpClientUtil.doHttpsGet(url,params));
log.info("token 获取:{}",jsonObject);
/**
* {
* "access_token":"ACCESS_TOKEN",
* "expires_in":7200,
* "refresh_token":"REFRESH_TOKEN",
* "openid":"OPENID",
* "scope":"SCOPE"
* }
*/
log.info("通过code获取access_token:{}",jsonObject);
String accessToken = (String) jsonObject.get("access_token");
if(StringUtil.isNotEmpty(accessToken)){
url = WxUtil.GET_SNS_USER_INFO_URL;
params = new HashMap<>();
params.put("access_token",accessToken);
params.put("openid",jsonObject.get("openid"));
params.put("lang",lang);
jsonObject = JSONObject.parseObject(HttpClientUtil.doHttpsGet(url,params));
log.info("用户信息:{}",jsonObject);
return jsonObject.toJSONString();
}
return "";
}
}
WxUtil类
package com.example.mybaties.utils;
import com.example.mybaties.entity.TextMessage;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description: 微信工具类
* @Author: lst
* @Date 2020-08-19
*/
public class WxUtil {
/**
* 获取code后,请求以下链接获取access_token:
* https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE
* &grant_type=authorization_code
*/
public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
/**
* https请求方式: GET
* https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
*/
public static final String GET_ACCESS_TOKEN_URL_BY_BACKSTAGE = "https://api.weixin.qq.com/cgi-bin/token";
/**
* https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
*/
public static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info";
/**
* https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
*/
public static final String GET_SNS_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
}
HttpClientUtil工具
@Slf4j
public class HttpClientUtil {
public static final String FH_WH = "?";
public static final int NUM200 = 200;
/**
* 20190621
*
* @param url
* @param params
* @return
*/
public static String doHttpsGet(String url, Map<String, Object> params) {
// 读取返回内容
StringBuffer buffer = new StringBuffer();
HttpsURLConnection con = null;
// 尝试发送请求
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},
new SecureRandom());
// 构建请求参数
StringBuffer sb = new StringBuffer();
if (params != null) {
for(Map.Entry<String, Object> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8"));
sb.append("&");
}
}
if (url.indexOf(FH_WH) > 0) {
url += "&";
} else {
url += "?";
}
url += sb.substring(0, sb.length() - 1).toString();
log.info("请求url:{}",url);
con = (HttpsURLConnection) new URL(url).openConnection();
con.setDoInput(true);
con.setUseCaches(false);
con.setConnectTimeout(10 * 60 * 1000);
con.setReadTimeout(10 * 60 * 1000);
con.setSSLSocketFactory(sc.getSocketFactory());
con.setHostnameVerifier(new TrustAnyHostnameVerifier());
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (con.getResponseCode() == NUM200) {
InputStream in = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
}
in.close();
br.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
return buffer.toString();
}
}
6、测试
打开微信开发工具,登录自己的微信,选择微信端。
在上图连接中输入(https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx29da6cd8e73183ba&redirect_uri=http://ycr7f4.natappfree.cc/login&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect)
然后看下后台日志
这样就获取到我的微信基本信息了。
下一篇: 有多组经纬度数据,如何找一个集中点