JAVA微信公众号开发第6篇网页授权


简介

网页授权开通条件:已开通微信认证的服务号
如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

关于网页授权回调域名的说明

1、在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
2、授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.htmlhttp://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.comhttp://music.qq.comhttp://qq.com无法进行OAuth2.0鉴权
3、如果公众号登录授权给了第三方开发者来进行管理,则不必做任何设置,由第三方代替公众号实现网页授权即可
这里写图片描述
读者请不要忽略第三步,网页授权域名域名只可设置一个,所以笔者建议redirect_uri使用后台接口,方便在redirect_uri上拼接参数和后台获取用户信息、一些必要的逻辑处理。

关于网页授权的两种scope的区别说明

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
3、用户管理类接口中的“获取用户基本信息接口”,是在用户和公众号产生消息交互或关注后事件推送后,才能根据用户OpenID来获取用户基本信息。这个接口,包括其他微信接口,都是需要该用户(即openid)关注了公众号后,才能调用成功的。

关于网页授权access_token和普通access_token的区别

1、微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息;
2、其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。

关于UnionID机制

1、请注意,网页授权获取用户基本信息也遵循UnionID机制。即如果开发者有在多个公众号,或在公众号、移动应用之间统一用户帐号的需求,需要前往微信开放平台(open.weixin.qq.com)绑定公众号后,才可利用UnionID机制来满足上述需求。
2、UnionID机制的作用说明:如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众帐号),unionid是相同的。

关于特殊场景下的静默授权(未关注公众号的用户获取用户信息需使用静默授权scope=snsapi_userinfo)

1、上面已经提到,对于以snsapi_base为scope的网页授权,就静默授权的,用户无感知;
2、对于已关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权,用户无感知。
具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

接口地址

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

参数说明

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

网页授权开发

本文涉及到的JAVA URL(编码、解码、参数解析),请点击。

snsapi_base方式

生成授权url

wxServiceDtoService.oauth2buildAuthorizationUrl(environment.getProperty(“wx.redirect.uri”)+”?wxsystoken=”+environment.getProperty(“wx.wxsystoken”)+”?r_url=”+r_url, “snsapi_base”,”/tab/home”);

/**
     * Ajoauth redirect.
     *
     * @return the string
     */
    @RequestMapping("/ajoauthredirect")
    public void ajoauthRedirect(String m, String wxsystoken, String r_url, HttpServletRequest request,
            HttpServletResponse response) {
        try {
        //菜单地址跳转传参使用state
        //state 否   重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
            String state = request.getParameter("state");
            if (StringUtils.isEmpty(state)) {
                state = "/tab/home";
            } else {
                String[] states = state.split(";");
                if (states.length > 0) {
                    state = states[0];
                } else if (states.length > 1) {
                    if (StringUtils.isEmpty(m)) {
                        m = states[1];
                    } else {
                        logger.info("接收到参数m:" + m);
                    }
                }
            }
            String code = request.getParameter("code");
            System.out.println("授权完成获取CODE:" + code);
            WxOAuth2AccessTokenResult wxOAuth2AccessTokenResult = wxServiceDtoService.oauth2ToGetAccessToken(code);
            String openId = wxOAuth2AccessTokenResult.getOpenid();
            System.out.println("授权完成获取OPENID:" + openId);
            System.out.println("授权完成获取OACCESSTOKEN:" + wxOAuth2AccessTokenResult.getAccess_token());
            String unionId = wxOAuth2AccessTokenResult.getUnionid();
            //获取页面地址
            String distUrl = environment.getProperty("lh.host.dist");
            r_url= StringUtils.isEmpty(r_url) ? state :UrlUtil.getURLDecoderString(r_url);
            WxUser wxUser = null;
            try {
                String wxto="";
                if (r_url.contains("wxto")) {
                    //url参数解析
                    wxto=UrlUtil.getUrlParameterReg(r_url,"wxto");
                }
                if(StringUtils.isEmpty(wxto)){
                    wxto=wxsystoken;
                }
                System.out.println("授权r_url:" + r_url);
                System.out.println("授权wxto:" + wxto);
                //获取微信用户信息
                    wxUser = wxService.userInfo(wxOAuth2AccessTokenResult.getOpenid(), "zh_CN");
                    //判断用户是否关注公众号
                if (wxUser != null &&!wxUser.isSubscribe()&& StringUtils.isEmpty(wxUser.getNickname())) {
                        //snsapi_userinfo静默授权通过access_token和openid获取用户信息
    wxUser=wxServiceDtoService.oauth2ToGetUserInfo(wxOAuth2AccessTokenResult.getAccess_token(),wxOAuth2AccessTokenResult.getOpenid());
                }
            } catch (Exception e) {
                System.out.println("授权微信用户信息Exception:" + e.getMessage());
            }
            //判断用户是否关注公众号
            if (wxUser != null && !wxUser.isSubscribe()&& StringUtils.isEmpty(wxUser.getNickname())) {
                r_url = UrlUtil.getURLEncoderString(r_url);     distUrl=wxServiceDtoService.oauth2buildAuthorizationUrl(environment.getProperty("wx.redirect.uri")+"?wxsystoken="+environment.getProperty("wx.wxsystoken")+"?r_url="+r_url, "snsapi_userinfo","");
                System.out.println("未关注用户去授权重定向URL:" + distUrl);
                response.sendRedirect(distUrl);
                return;
            }else{
                System.out.println("拉取用户信息:" + new Gson().toJson(wxUser));
            }
            distUrl +=r_url;
            StringBuffer parameters = new StringBuffer();
            if (distUrl.contains("timestamp")) {
                distUrl = UrlUtil.replaceUrlParameterReg(distUrl, "timestamp", new Date().getTime() + "");
            } else {
                parameters.append("timestamp=");
                parameters.append(new Date().getTime());
            }
            if (distUrl.contains("openid")) {
                distUrl = UrlUtil.replaceUrlParameterReg(distUrl, "openid", openId);
            } else {
                parameters.append("&openid=");
                parameters.append(openId);
            }
            if (distUrl.contains("unionid")) {
                distUrl = UrlUtil.replaceUrlParameterReg(distUrl, "unionid", unionId);
            } else {
                parameters.append("&unionid=");
                parameters.append(unionId);
            }
            if (distUrl.contains("oaccesstoken")) {
                distUrl = UrlUtil.replaceUrlParameterReg(distUrl, "oaccesstoken",
                        wxOAuth2AccessTokenResult.getAccess_token());
            } else {
                parameters.append("&oaccesstoken=");
                parameters.append(wxOAuth2AccessTokenResult.getAccess_token());
            }
            if (distUrl.contains("wxt=")) {
                distUrl = UrlUtil.replaceUrlParameterReg(distUrl, "wxt", wxsystoken);
            } else {
                parameters.append("&wxt=");
                parameters.append(wxsystoken);
            }
            distUrl += distUrl.contains("?") ? "&" + parameters.toString() : "?" + parameters.toString();
            System.out.println("授权完成重定向URL:" + distUrl);
            response.sendRedirect(distUrl);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

snsapi_userinfo方式

scope等于snsapi_userinfo时会提示用户的的授权页面:
这里写图片描述

生成授权url

wxServiceDtoService.oauth2buildAuthorizationUrl(environment.getProperty(“wx.redirect.uri”)+”?wxsystoken=”+environment.getProperty(“wx.wxsystoken”)+”?r_url=”+r_url, “snsapi_userinfo”,”/tab/home”);
处理方式同上

微信Service拓展

WxServiceDtoService.java

package com.bigbigbu.service;


import java.io.IOException;

import javax.inject.Inject;

import com.bigbigbu.model.WxConstsDto;
import com.bigbigbu.model.result.WxOAuth2AccessTokenResult;
import me.chanjar.weixin.api.WxInMemoryConfigStorage;
import me.chanjar.weixin.api.WxServiceImpl;
import me.chanjar.weixin.bean.result.WxError;
import me.chanjar.weixin.bean.result.WxUser;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.exception.WxErrorException;
import me.chanjar.weixin.util.http.SimpleGetRequestExecutor;

/**
* @Title: WxServiceDtoService
* @Description: 微信Service拓展
* @Company: 卜凡起的博客
* @author    FANQIBU
* @date       2018年2月1日
*/
public class WxServiceDtoService {
    private @Inject WxInMemoryConfigStorage wxInMemoryConfigStorage;
    private @Inject WxServiceImpl wxService;
    /**   
     * @Title: oauth2buildAuthorizationUrl   
     * @Description: TODO 获取授权url
     * @param: @param redirectUri
     * @param: @param scope
     * @param: @param state
     * @param: @return      
     * @return: String      
     */  
    public String oauth2buildAuthorizationUrl(String redirectUri, String scope, String state) {
        redirectUri = URIUtil.encodeURIComponent(redirectUri);
        String url = WxConstsDto.URL_OAUTH2_GET_CODE.replace("APPID",wxInMemoryConfigStorage.getAppId())
                .replace("REDIRECT_URI", redirectUri).replace("SCOPE", scope).replace("STATE", state);
        return url;
    }
    /**   
     * @Title: oauth2ToGetAccessToken   
     * @Description: TODO 通过授权code获取授权token
     * @param: @param code
     * @param: @return
     * @param: @throws WxErrorException      
     * @return: WxOAuth2AccessTokenResult      
     */  
    public WxOAuth2AccessTokenResult oauth2ToGetAccessToken(String code) throws WxErrorException{
        WxOAuth2AccessTokenResult result = null;
        try {
            String url = WxConstsDto.URL_OAUTH2_GET_ACCESSTOKEN.replace("APPID",wxInMemoryConfigStorage.getAppId())
                    .replace("SECRET", wxInMemoryConfigStorage.getSecret()).replace("CODE", code);
            String getResult =wxService.execute(new SimpleGetRequestExecutor(),url, null);
            result = WxOAuth2AccessTokenResult.fromJson(getResult);
        } catch (IOException e) {
            WxError error=new WxError();
            error.setErrcode(-33333);
            error.setErrmsg("[wx-tools]oauth2ToGetAccessToken failure.");
            throw new WxErrorException(error);
        }
        return result;
    }
    /**   
     * @Title: oauth2ToGetUserInfo   
     * @Description: TODO 静默授权通过access_token和openid获取用户信息
     * @param: @param access_token
     * @param: @param openid
     * @param: @return
     * @param: @throws WxErrorException      
     * @return: WxUser      
     */  
    public WxUser oauth2ToGetUserInfo(String access_token, String openid) throws WxErrorException {
        WxUser user = null;
        try {
                if(user == null){
                    String url = WxConstsDto.URL_OAUTH2_GET_USER_INFO.replace("ACCESS_TOKEN", access_token)
                            .replace("OPENID", openid);
                    String getResult = wxService.execute(new SimpleGetRequestExecutor(),url, null);
                    user = WxUser.fromJson(getResult);  
                }
        } catch (Exception e) {
            WxError error=new WxError();
            error.setErrcode(-33333);
            error.setErrmsg("[wx-tools]oauth2ToGetAccessToken failure.");
            throw new WxErrorException(error);
        }
        return user;
    }
}

WxOAuth2AccessTokenResult.java

package com.bigbigbu.model.result;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.bigbigbu.model.WxAccessToken;



/**
 * OAuth2.0 认证 access_token
 * @author FANQIBU
 *
 */
public class WxOAuth2AccessTokenResult extends WxAccessToken{
    private String refresh_token;
    private String openid;
    private String scope;
    private String unionid;


    public String getUnionid() {
        return unionid;
    }
    public void setUnionid(String unionid) {
        this.unionid = unionid;
    }
    public String getRefresh_token() {
        return refresh_token;
    }
    public void setRefresh_token(String refresh_token) {
        this.refresh_token = refresh_token;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
    public String getScope() {
        return scope;
    }
    public void setScope(String scope) {
        this.scope = scope;
    }
    public static WxOAuth2AccessTokenResult fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(json, WxOAuth2AccessTokenResult.class);
    }
    @Override
    public String toString() {
        return "WxOAuth2AccessTokenResult [refresh_token=" + refresh_token + ", openid=" + openid + ", scope=" + scope
                + ", unionid=" + unionid + "]";
    }


}

接口地址

//######菜单相关######
    public static final String URL_CREATE_MENU = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    //######用户相关######
    public static final String URL_OAUTH2_GET_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
    public static final String URL_OAUTH2_GET_ACCESSTOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    public static final String URL_OAUTH2_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

总结

  • 链接生成
    scope应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
  • 微信信息获取
    首先了解网页授权access_token和普通access_token的区别
    一、 微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息;
    二、其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。
    snsapi_userinfo静默授权通过access_token和openid获取用户信息 >wxUser=wxServiceDtoService.oauth2ToGetUserInfo(wxOAuth2AccessTokenResult.getAccess_token(),wxOAuth2AccessTokenResult.getOpenid());
    snsapi_base静默授权通过openid获取用户信息
    wxUser = wxService.userInfo(wxOAuth2AccessTokenResult.getOpenid(), “zh_CN”);
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值