• java调用微信公众平台授权登录


    记得看开发文档

    公众平台后台修改接口权限:

    网页授权 网页授权获取用户基本信息 无上限 已获得   修改

    修改:

      .cn,开发版可以使ip,正式版要用域名

    1、第一步:用户同意授权,获取code

      一般由前段调用,拿到code,传给后端。

      https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirec

     

    参数是否必须说明
    appid 公众号的唯一标识
    redirect_uri 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
    response_type 返回类型,请填写code
    scope 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
    state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
    #wechat_redirect 无论直接打开还是做页面302重定向时候,必须带此参数

     

     用户同意授权后

      如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

      code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
    
    
    

    2、通过code换取网页授权access_token

      获取code后,请求以下链接获取access_token:  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    参数是否必须说明
    appid 公众号的唯一标识
    secret 公众号的appsecret
    code 填写第一步获取的code参数
    grant_type 填写为authorization_code

     

    3、第三步:刷新access_token(如果需要)

      由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。

      请求方法

      获取第二步的refresh_token后,请求以下链接获取access_token:
      https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

    参数是否必须说明
    appid 公众号的唯一标识
    grant_type 填写为refresh_token
    refresh_token 填写通过access_token获取到的refresh_token参数

    4、第四步:拉取用户信息(需scope为 snsapi_userinfo)

      如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。

      请求方法

      http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

      参数说明 

    参数描述
    access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
    openid 用户的唯一标识
    lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

    附:检验授权凭证(access_token)是否有效

      请求方法

      http:GET(请使用https协议) https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
    

      参数说明

    参数描述
    access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
    openid 用户的唯一标识

    我的代码:

       //wxLoginInfo 是后端自己测试时,传url,可以直接请求,拿到code,重定向到callBackInfo


       @RequestMapping("/wxLoginInfo")
       @ResponseBody
    public void wxLoginInfo(HttpServletRequest req,HttpServletResponse resp) throws IOException {
            String parameter = req.getParameter("url");
            //String backUrl = AuthUtil.WEIXINURL+"xxxx/weixin/callBackInfo";
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtil.APPID
                    + "&redirect_uri="+URLEncoder.encode(parameter)
                    + "&response_type=code"
                    + "&scope=snsapi_userinfo"//弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息
                    + "&state=STATE#wechat_redirect";
            System.out.println("url=="+url);
            /*
             * https://open.weixin.qq.com/connect/oauth2/authorize?
             * appid=myAppid&
             * redirect_uri=https://xxxx.cn&
             * response_type=code&
             * scope=snsapi_userinfo&
             * state=STATE#wechat_redirect
             * 
             * String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtil.APPID
                    + "&redirect_uri="+URLEncoder.encode(backUrl)
                    + "&response_type=code"
                    + "&scope=snsapi_base"
                    + "&state=STATE#wechat_redirect";*/
            resp.sendRedirect(url);
        }
        

      //拿到code后请求接口,拿到用户数据,关联公众平台后会拿到unionid,然后是进行的数据操作 @SuppressWarnings(
    "unchecked") @RequestMapping("/callBackInfo") @ResponseBody public void callBackInfo(HttpServletRequest req,HttpServletResponse resp) throws IOException { BaseResponse<Object> result = new BaseResponse<Object>(StatusCode.Success); String code = req.getParameter("code"); String codeUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID + "&secret="+AuthUtil.APPSECRET + "&code="+code + "&grant_type=authorization_code"; JSONObject codeJson = AuthUtil.doGetJson(codeUrl); System.out.println("codeJson= "+codeJson); String openid = codeJson.getString("openid"); String unionid = "" ; Set<Object> keySet = codeJson.keySet(); for (Object object : keySet) { if(object.equals("unionid")){ unionid = codeJson.getString("unionid"); System.out.println("unionid==="+unionid); } } String accessToken = codeJson.getString("access_token"); String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken + "&openid="+openid + "&lang=zh_CN"; JSONObject info = AuthUtil.doGetJson(infoUrl); System.out.println("info= "+info); String nickname = info.getString("nickname"); String sex = info.getString("sex"); String city = info.getString("city"); String headimgurl = info.getString("headimgurl"); String openId = info.getString("openid"); System.out.println("openid= "+openId); System.out.println("sex= "+sex); System.out.println("city= "+city); System.out.println("nickname= "+nickname); System.out.println("headimgurl= "+headimgurl);

    }

      AuthUtil.APPID,AuthUtil.APPSECRET:公众平台的appid和APPSECRET

    package com.fltd.tourism.util;
    
    
    import java.io.IOException;
    
    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.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    
    import net.sf.json.JSONObject;
    
    public class AuthUtil {
        
        public static final String WEIXINURL= "https://xxxxx.cn/";
        
        public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException{
            JSONObject jsonObject = null;
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String result = EntityUtils.toString(entity,"UTF-8");
                jsonObject = JSONObject.fromObject(result);            
            }
            httpGet.releaseConnection();
            return jsonObject;
        }
    }

    总结:

      1、其中 AuthUtil.APPID,AuthUtil.APPSECRET是微信公众号正式的,不要弄错了,很容易和小程序、开放平台、开发环境等弄混,回报错。

      2、wxLoginInfo中url,一定要看清楚是否和公众号上的一致,不然也会报错:redirect_url域名与后台配置不一致。

      3、unionid正常情况是没有的,要关联上才会有。具体看微信的文档

  • 相关阅读:
    微信小程序学习Course 9-2 云存储功能
    微信小程序学习Course 9-1 云数据库功能
    微信小程序学习Course 9 云开发功能
    微信小程序学习Course 6 界面交互API函数
    微信小程序学习Course 3-3 JS时间类型学习
    微信小程序案例TODO备忘录
    微信小程序学习Course 3-2 JS数组对象学习
    微信小程序学习Course 8 本地缓存API
    微信小程序学习Course 7 定时器功能
    常用excel函数语法及说明
  • 原文地址:https://www.cnblogs.com/zmjc/p/12020929.html
Copyright © 2020-2023  润新知