完整测试代码下载地址:http://www.jiajiajia.club/file/info/5SQzy7/120
首先配置微信公众平台测试账号
位置:微信公众号->开发->开发者工具->微信公众平台测试账号
1.修改接口配置信息
url 填外网可以访问的接口(必须是80端口),如果是本地测试的话可以用外网穿透。
例:http://aaaa.com/call/back
Token 可以任意填写,但要和接口中的配置一致
例:123123
2.配置后端接口,保证接口可以被外网访问 上述修改接口配置信息才可以成功。
//检查微信接口配置
@RequestMapping("/call/back")
public String checkUrl(HttpServletRequest request){
//获取参数配置
String signature = request.getParameter("signature");
//获取时间托
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
//获取echostr 字符
String echostr = request.getParameter("echostr");
// try ---- catch 捕捉异常
try {
//判断是否为空
if (null != signature) {
//声明一个存储数据字符数组
String token = “123123”//和微信配置一致
String[] ArrTmp = { token, timestamp, nonce };
Arrays.sort(ArrTmp);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ArrTmp.length; i++) {
sb.append(ArrTmp[i]);
}
//获取消息对象
MessageDigest md = MessageDigest.getInstance("SHA-1");
//声明一个字节流数组;
byte[] bytes = md.digest(new String(sb).getBytes());
//声明一个字符流
StringBuffer buf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
if (signature.equals(buf.toString())) {
return echostr;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//返回消息
return null;
}
公众号配置完成以后就可以在代码中获取用户信息,一共分四步
- 获取code
- 通过code,appid和secret获取openid
- 通过appid和secret获取access_token
- 通过openid和access_token获取用户信息
1.获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=URL&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
appid是你的appid,redirect_uri是你的项目的回调地址,微信服务端会去调这个接口,给你传个code参数。
2.获取openid
获取完code以后,通过code,appid和secret获取openid,接口如下
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
替换appid, secret, code参数
3.获取access_token
通过appid和secret获取access_token,接口如下
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
替换appid和secret参数
4.获取用户信息
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
替换上述获取的access_token,和openid,获取用户信息
整个过程大概就是这么多
请求工具类
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 微信登录获取信息工具类
*/
public class WeChatGetInfoUtil {
private static String appId = "12312312312312313213";//appId
private static String appSecret = "4564564564654564646546546546";//appSecret
private static String token = "789789";//此token跟需跟微信公众号的token一致;
private static String redirect_uri="http://aaaaa.com/call/openid";//回调地址,获取code
public static String getAppId(){
return appId;
}
/**
* 检查微信接口配置
* @param request
* @return
*/
public static String checkUrl(HttpServletRequest request){
//获取参数配置
String signature = request.getParameter("signature");
//获取时间托
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
//获取echostr 字符
String echostr = request.getParameter("echostr");
// try ---- catch 捕捉异常
try {
//判断是否为空
if (null != signature) {
//声明一个存储数据字符数组
String[] ArrTmp = { token, timestamp, nonce };
Arrays.sort(ArrTmp);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ArrTmp.length; i++) {
sb.append(ArrTmp[i]);
}
//获取消息对象
MessageDigest md = MessageDigest.getInstance("SHA-1");
//声明一个字节流数组;
byte[] bytes = md.digest(new String(sb).getBytes());
//声明一个字符流
StringBuffer buf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
if (signature.equals(buf.toString())) {
return echostr;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//返回消息
return null;
}
/**
* 请求微信跳转回调地址获取code
* @param request
* @param response
*/
public static void toRedirectUri(HttpServletRequest request,HttpServletResponse response){
try {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
String uri= URLEncoder.encode(redirect_uri, "UTF-8");//回调地址,获取code
StringBuffer url=new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri="+uri+
"&appid="+appId+"&response_type=code&scope=snsapi_base&state=1#wechat_redirect");//替换appid
response.sendRedirect(url.toString());//这里请不要使用get请求单纯的将页面跳转到该url即可
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取openId
* @param request
* @param response
* @return
*/
public static WeChatMessage getOpenId(HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
String code = request.getParameter("code");//获取code
Map params = new HashMap();
params.put("secret", appSecret);//你的secret
params.put("appid", appId);//你的appid
params.put("grant_type", "authorization_code");
params.put("code", code);
String result = HttpGetPostUtil.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params);
WeChatMessage message = null;
if(result != null){
message = JSONObject.parseObject(result,WeChatMessage.class);
message.setCode(code);
}
return message;
}
/**
* 获取access_token
* @return
*/
public static WeChatMessage getAccessToken(){
Map params = new HashMap();
params.put("secret", appSecret);
params.put("appid", appId);
params.put("grant_type", "client_credential");
String result = HttpGetPostUtil.doGet("https://api.weixin.qq.com/cgi-bin/token",params);
WeChatMessage message = null;
if(result != null){
message = JSONObject.parseObject(result,WeChatMessage.class);
}
return message;
}
/**
* 获取用户信息
* @param openId
* @param accessToken
* @return
*/
public static WeChatUserInfo getWeChatUserInfo(String openId,String accessToken){
String result = HttpGetPostUtil.doGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId);
WeChatUserInfo userInfo = null;
if(result != null){
userInfo = JSONObject.parseObject(result,WeChatUserInfo.class);
}
return userInfo;
}
}
控制器
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/call")
public class TestController {
//配置微信的接口
@RequestMapping("/back")
public String test(HttpServletRequest request){
//微信获取解析信息
String str = WeChatGetInfoUtil.checkUrl(request);
return str;
}
//微信需要访问的跳转地址
@RequestMapping("/transfer")
public void transfer(HttpServletRequest request, HttpServletResponse response) {
WeChatGetInfoUtil.toRedirectUri(request,response);
}
/**
* 获取openid,用户信息等
* @param request
* @param response
* @return
*/
@RequestMapping("/openid")
public WeChatUserInfo huidiao(HttpServletRequest request,HttpServletResponse response){
WeChatMessage open = WeChatGetInfoUtil.getOpenId(request,response);//获取openid
String openId = open.getOpenid();
System.out.println("得到的openid为:"+openId);
if(openId!=null){
WeChatMessage token = WeChatGetInfoUtil.getAccessToken();//获取access_token
System.out.println("获取access_token: "+token);
WeChatUserInfo userInfo = WeChatGetInfoUtil.getWeChatUserInfo(openId,token.getAccess_token());//获取用户信息
System.out.println("获取用户信息:"+userInfo);
return userInfo;
}
return null;//返回跳转页面
}
}
其中还包括http工具类和一些其他的类,如需要,请下载测试源码:http://www.jiajiajia.club/file/info/5SQzy7/120