关于微信公众号网页授权获取用户信息(微信授权登录)

1.登录微信公众平台配置相关信息
登录成功后再左侧菜单选择开发者工具,点击图中测试账号
关于微信公众号网页授权获取用户信息(微信授权登录)_第1张图片

设置相关信息
在这里插入图片描述

接口配置信息设置
关于微信公众号网页授权获取用户信息(微信授权登录)_第2张图片

URL地址为服务器对应接口地址(域名地址必须是外网地址,如果没有外网服务器,推荐使用natapp进行内网穿透),目的是正确响应微信发送的Token,接口代码如下,因为只做简单测试,所以直接返回echostr

	@RequestMapping(value = "/wx",method = RequestMethod.GET)
    @ResponseBody
    public String wxTest(@RequestParam("signature") String signature,
                                 @RequestParam("timestamp") String timestamp,
                                 @RequestParam("nonce") String nonce,
                                 @RequestParam("echostr") String echostr){

        logger.info(signature+"****"+timestamp+"****"+nonce+"****"+echostr);
        return echostr;
    }

关于微信公众号网页授权获取用户信息(微信授权登录)_第3张图片

修改网页账号
关于微信公众号网页授权获取用户信息(微信授权登录)_第4张图片
关于微信公众号网页授权获取用户信息(微信授权登录)_第5张图片

到此测试参数配置完毕。下面上代码

接口类WxController:

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
/**
 * @program: integral_wall
 * @description: 微信登录授权相关
 * @author: Chenjf
 * @create: 2018-09-25 17:40
 **/
@RestController
@RequestMapping("/Api/wx")
public class WxController {


    private static final Logger logger = Logger.getLogger(WxController.class);

    /** 公众号微信登录授权
    * @Description:
    * @Param: [request, response]
    * @return: java.lang.String
    * @Author: Chenjf
    * @Date: 2018/9/27
    */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        //这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
        String backUrl= Constant.server_url + "/Api/wx/callBack";
        // 第一步:用户同意授权,获取code
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WXAuthUtil.APPID
                + "&redirect_uri="+ URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";
        logger.info("forward重定向地址{" + url + "}");
        //response.sendRedirect(url);
        return url;//必须重定向,否则不能成功
    }

    /**
    * @Description: 公众号微信登录授权回调函数
    * @Param: [modelMap, req, resp]
    * @return: java.lang.String
    * @Author: Chenjf
    * @Date: 2018/9/25
    */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public String callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       //start 获取微信用户基本信息
       String code =req.getParameter("code");
       //第二步:通过code换取网页授权access_token
       String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WXAuthUtil.APPID
               + "&secret="+WXAuthUtil.APPSECRET
               + "&code="+code
               + "&grant_type=authorization_code";
       System.out.println("url:"+url);
       JSONObject jsonObject = WXAuthUtil.doGetJson(url);
       String openid = jsonObject.getString("openid");
       String access_token = jsonObject.getString("access_token");
       String refresh_token = jsonObject.getString("refresh_token");
       //第五步验证access_token是否失效;展示都不需要
       String chickUrl="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
       JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
       System.out.println(chickuserInfo.toString());
       if(!"0".equals(chickuserInfo.getString("errcode"))){
            // 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
            String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+openid+"&grant_type=refresh_token&refresh_token="+refresh_token;
            JSONObject refreshInfo = WXAuthUtil.doGetJson(chickUrl);
            System.out.println(refreshInfo.toString());
            access_token=refreshInfo.getString("access_token");
       }

       // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
       String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
                + "&openid="+openid
                + "&lang=zh_CN";
       System.out.println("infoUrl:"+infoUrl);
       JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
       System.out.println("JSON-----"+userInfo.toString());
       System.out.println("名字-----"+userInfo.getString("nickname"));
       System.out.println("头像-----"+userInfo.getString("headimgurl"));

       //end 获取微信用户基本信息

       //获取到用户信息后就可以进行重定向,走自己的业务逻辑了。。。。。。
       //接来的逻辑就是你系统逻辑了,请自由发挥

       return "login";
    }

}

网络工具类WXAuthUtil:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
/**
 * @program: integral_wall
 * @description: 网络请求工具类(微信登录使用)
 * @author: Chenjf
 * @create: 2018-09-25 19:44
 **/
public class WXAuthUtil {

    public static final String APPID="***********";
    public static final String APPSECRET ="**************";
    private static final String TOKEN = "*********";
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject =null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet =new HttpGet(url);
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity =response.getEntity();
        if(entity!=null){
            //把返回的结果转换为JSON对象
            String result =EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSON.parseObject(result);
        }

        return jsonObject;
    }

}

至此所有准备就绪。只需在微信打开wxLogin方法返回的url就可以进行测试了。

你可能感兴趣的:(笔记)