微信公众号 第三方登录 获取微信用户信息(java版)

  


(1) 第一步 去微信公众平台申请一个测试公众号

 http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index


  (2)  关注测试公众号

      用户只有关注了这个公众号了,才能通过打开有公众号信息的链接去授权第三方登录,并获取用户信息的操作。(还需要绑定开放平台账号才能获取 unionid)

   

  (3) 设置回调函数

  这个回调函数 填写域名即可 不需要在域名后添加项目名称 方法名,


 (4)   绑定开放平台

    开放平台地址 :https://open.weixin.qq.com

   不绑定开放平台获取不到 unionid  (同一微信关注不同的公众号 unionid  是不变的 是唯一的

       


  配置好完成后 接下来就开发啦。。

 

一。授权开发的流程(详情的东西请以官网为准,在此就不多说了):具体而言,网页授权流程分为四步:

1、引导用户进入授权页面同意授权,获取code

2、通过code换取网页授权access_token(与基础支持中的access_token不同)

3、如果需要,开发者可以刷新网页授权access_token,避免过期

4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

二。 代码如下

 第一步 : 引入用户进入授权页面

    

  /**
	 * 访问登录页
	 * @return
	 */
	@RequestMapping(value="/login_toLogin")
	public String  toLogin()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();

		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称

		//WxConfigLoadUtil.getWxConfigValueByKey("AppID")  即测试公众号的appid

                //URLEncoder.encode(WxConfigLoadUtil.getWxConfigValueByKey("backUrl")) == http\://wb.free.ngrok.cc/mp/wx/callBack

		
        // 第一步:用户同意授权,获取code
     String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxConfigLoadUtil.getWxConfigValueByKey("AppID")
                + "&redirect_uri="+URLEncoder.encode(WxConfigLoadUtil.getWxConfigValueByKey("backUrl"))
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";


        logger.info("forward重定向地址{" + url + "}");
        //response.sendRedirect(url);
        return "redirect:"+url;//必须重定向,否则不能成功
    }   

 第二步: 用户同意后返回的参数

       /**
	 * 公众号微信登录授权回调函数
	 * @param modelMap
	 * @param req
	 * @param resp
	 * @return
	 * @author   
	 * @throws Exception 
	 * @date 创建时间:2018年1月18日 下午7:33:53  
	 * @parameter
	 */
	 @RequestMapping(value = "/callBack", method = RequestMethod.GET)
	 public String callBack(ModelMap modelMap,HttpServletRequest req, HttpServletResponse resp) throws Exception {
		 
		ModelAndView mv = this.getModelAndView();
	    String code =req.getParameter("code");
	    
	    //第二步:通过code换取网页授权access_token
        JSONObject jsonObject = WxConfigLoadUtil. getAccessTokenByAuthorizationCode(code);


        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        String refresh_token = jsonObject.getString("refresh_token");
        
        //第五步验证access_token是否失效;展示都不需要
        JSONObject chickuserInfo = WxConfigLoadUtil. chickAccessToken(access_token,openid);


        if(!"0".equals(chickuserInfo.getString("errcode"))){
            // 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
        	 JSONObject refreshInfo  = WxConfigLoadUtil.getAccessTokenByRefreshToken(openid,refresh_token);
            //重新复值
             access_token=refreshInfo.getString("access_token");
        }
       
        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        JSONObject userInfo = WxConfigLoadUtil.getUserInfo(access_token,openid);
        
        //获取到用户信息 接下来 就写自己的业务逻辑了
        /*{
            "subscribe": 1, 
            "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", 
            "nickname": "Band", 
            "sex": 1, 
            "language": "zh_CN", 
            "city": "广州", 
            "province": "广东", 
            "country": "中国", 
            "headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
            
        }*/
        
        return "app/index/index";

	 }

工具类:

package com.skzc.util;


import java.io.FileReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.ResourceBundle;


import javax.servlet.ServletContext;


import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;


import net.sf.json.JSONObject;


public class WxConfigLoadUtil {
	private final static ResourceBundle resource;
	private static Properties props = new Properties();
	
	static{
		resource = ResourceBundle.getBundle("conf/wx");
	}
	
	public static String getWxConfigValueByKey(String keyWord){
		return resource.getString(keyWord);
	}
	
	public static String getBestNewConfig(String str){
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();
		try {
			props.load(new FileReader(servletContext.getRealPath("/sysconfig")+"/wxconfig.properties"));
			return props.getProperty(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	//SHA1加密算法
	public static String SHA1(String decript) {  
	    try {  
	        MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");  
	        digest.update(decript.getBytes());  
	        byte messageDigest[] = digest.digest();  
	        // Create Hex String  
	        StringBuffer hexString = new StringBuffer();  
	        // 字节数组转换为 十六进制 数  
	            for (int i = 0; i < messageDigest.length; i++) {  
	                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);  
	                if (shaHex.length() < 2) {  
	                    hexString.append(0);  
	                }  
	                hexString.append(shaHex);  
	            }  
	            return hexString.toString();  
	   
	        } catch (NoSuchAlgorithmException e) {  
	            e.printStackTrace();  
	        }  
	        return "";  
	}
    
	
	/**
     * 使用Authorization_code来获取Access Token。
     * 
     * @param code 授权码Authorization Code
     * @return AccessToken对象的封装。
     * @throws BaiduOAuthException OAuthException异常类
     */
	public static JSONObject getAccessTokenByAuthorizationCode(String code) throws Exception {
		
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WxConfigLoadUtil.getWxConfigValueByKey("AppID")
			        + "&secret="+WxConfigLoadUtil.getWxConfigValueByKey("AppSecret")
			        + "&code="+code
			        + "&grant_type=authorization_code";
		
		 JSONObject jsonObject = HttpsUtils.findWxAccessToken(url, "GET");
		
		return jsonObject;
	}
	
	
    /**
     * 检查 AccessToken 是否过期
     * @param access_token
     * @param openid
     * @return
     * @throws Exception 
     */
	public static JSONObject chickAccessToken(String access_token, String openid) throws Exception {
		
		String chickUrl="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
		
		JSONObject chickuserInfo = HttpsUtils.findWxAccessToken(chickUrl, "GET");
		
		return chickuserInfo;
	}


	/**
	 * 使用Refresh Token来获取Access Token
	 * @param openid
	 * @param refresh_token
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getAccessTokenByRefreshToken(String openid, String refresh_token) throws Exception {
		
		 String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+openid+"&grant_type=refresh_token&refresh_token="+refresh_token;


         JSONObject refreshInfo = HttpsUtils.findWxAccessToken(refreshTokenUrl, "GET");
         
		return refreshInfo;
	}
	
	
    /**
     * 获取用户信息
     * @param access_token
     * @param openid
     * @return
     * @throws Exception 
     */
	public static JSONObject getUserInfo(String access_token, String openid) throws Exception {
		
		 String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
	                + "&openid="+openid
	                + "&lang=zh_CN";
	     
	     JSONObject userInfo = HttpsUtils.findWxAccessToken(infoUrl, "GET");
	     
		return userInfo;
	} 
	
}

 小白第一次编写,有错误地方大家联系小编QQ53886428 ,写的不好,多多担待。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值