微信登录获取openid和用户信息(后端java)

硅谷探秘者 2315 0 0

完整测试代码下载地址: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


评论区
请写下您的评论...
暂无评论...
猜你喜欢
微信 java 1557 自动openid 测试代码
工具 2088 1.修改接口配置url填外网可以访问的接口(必须是80口),如果是本地测试的话可以外网穿透。例:http://aaaa.com/call/backToken可以任意填写,但要接口中的配置一致例
框架 1638 springboot项目中所有对外提供的接口@ComponentpublicclassTestimplementsApplicationRunner
weblog 1795 在ngxin代理的配置文件的location块中添加如下配置proxy_set_headerHost$host; proxy_set_headerX-Real-IP$remote_addr; proxy_set_headerREMOTE-HOST$remote_addr; proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;整体如下l
前端,java基础 1436 一、pom依赖二、接口示例三、前页面  有些场景需要生成带参数的小程序二维码,比如商城为每个商品生成小程序二维码,通过扫码直接跳转到该商品所在的展示页面。为开发者们提供了相应接口
工具 2895 计算机的ip地址的方法1.过滤器packagecn.com.dzqc.interceptor;importjava.io.IOException
java基础 6143 一、系统临时文件目二、java的系统属性有哪些File.createTempFile创建临时文件一、系统临时文件目通过java的系统属性Stringtmpdir
工具 1861 于分布式站点的单点陆(SSO)场景。JWT的声明一般被来在身份提供者服务提供者间传递被认证的身份,以便于从资源服务器资源,也可以增加一些额外的其它业务逻辑所必须的声明,该tok
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。