Home  >  Article  >  WeChat Applet  >  Author webpage authorization developed by WeChat

Author webpage authorization developed by WeChat

高洛峰
高洛峰Original
2017-02-15 11:15:212184browse

In WeChat development, there are often such needs: obtaining user avatars, binding WeChat ID to send messages to users... Then the prerequisite for achieving these is authorization!

1. Configure the security callback domain name:

微信开发之Author网页授权

Before the WeChat official account requests user webpage authorization, Developers need to first go to the "Development - Interface Permissions - Web Services - Web Accounts - Web Authorization to Obtain Basic User Information" configuration options on the official website of the public platform to modify the authorization callback domain name. It is worth noting that the full domain name is written directly here. For example: www.liliangel.cn. However, when we develop h5, we generally use second-level domain names, such as h5.liliangel.cn, which is also in the safe callback domain name.

2. User-level authorization and silent authorization

1. Web page authorization initiated with snsapi_base as scope is used to obtain The openid of the user who enters the page is silently authorized and automatically jumps to the callback page. What the user perceives is that they directly enter the callback page.

2. Web page authorization initiated with snsapi_userinfo as the scope is used to obtain the user's basic information. However, this kind of authorization requires manual consent from the user, and since the user has agreed, the basic information of the user can be obtained after authorization without paying attention.

3. The difference between web page authorization access_token and ordinary access_token

1. WeChat web page authorization is implemented through the OAuth2.0 mechanism. After the user authorizes the official account, The official account can obtain a web page authorization-specific interface call credential (web page authorization access_token). Through the web page authorization access_token, the post-authorization interface call can be made, such as obtaining basic user information;

2. Other WeChat interfaces need to be passed The "get access_token" interface in basic support is used to obtain the ordinary access_token call.

4. Guide the user to enter the authorization page to agree to the authorization and obtain the code

微信开发之Author网页授权

After the WeChat update, the authorization page has also changed. In fact, I am used to the green classic page..

js:


var center = {
        init: function(){
            .....
        },
        enterWxAuthor: function(){
            var wxUserInfo = localStorage.getItem("wxUserInfo");
            if (!wxUserInfo) {
                var code = common.getUrlParameter('code');
                if (code) {
                    common.getWxUserInfo();
                    center.init();
                }else{
                    //没有微信用户信息,没有授权-->> 需要授权,跳转授权页面
                    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ WX_APPID +'&redirect_uri='+ window.location.href +'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
                }
            }else{
                center.init();
            }
        }
}
$(document).ready(function() { 
    center.enterWxAuthor();
}

Take scope=snsapi_userinfo as an example. When the page is loaded, the authorization method is entered. First, the wxUserInfo object is obtained from the cache. If there is a description that it has been authorized before, directly enter the initialization method. If not, determine whether the URL contains a code. If there is a code, it indicates that it is the page after entering the callback of the authorization page. Then the code can be exchanged for user information. There is no code, that is, the user enters the page for the first time and is directed to the authorization page. The redirect_uri is the current page address.

getWxUserInfo method:


/**
     * 授权后获取用户的基本信息
     */
    getWxUserInfo:function(par){
        var code = common.getUrlParameter("code");
        
        if (par) code = par;
        
        $.ajax({
            async: false,
            data: {code:code},
            type : "GET",
            url : WX_ROOT + "wechat/authorization",
            success : function(json) {
                if (json){
                    try {
                        //保证写入的wxUserInfo是正确的
                        var data = JSON.parse(json);
                        if (data.openid) {
                            localStorage.setItem('wxUserInfo',json);//写缓存--微信用户信息
                        }
                    } catch (e) {
                        // TODO: handle exception
                    }
                }
            }
        });
    },

5.Background restful-- / wechat/authorization, exchange user information according to code


  /**
     * 微信授权
     * @param code 使用一次后失效
     * 
     * @return 用户基本信息
     * @throws IOException 
     */
    @RequestMapping(value = "/authorization", method = RequestMethod.GET)    public void authorizationWeixin(
            @RequestParam String code,
            HttpServletRequest request, 
            HttpServletResponse response) throws IOException{
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 

        PrintWriter out = response.getWriter();
        LOGGER.info("RestFul of authorization parameters code:{}",code);        
        try {
            String rs = wechatService.getOauthAccessToken(code);
            out.write(rs);
            LOGGER.info("RestFul of authorization is successful.",rs);
        } catch (Exception e) {
            LOGGER.error("RestFul of authorization is error.",e);
        }finally{
            out.close();
        }
    }

There is an authorization access_token here, remember : Authorize access_token non-global access_token, which requires the use of cache. I am using redis here. I will not go into the specific configuration and will write a related configuration blog later. Of course, you can also use ehcache. The ehcahe configuration is described in detail in my first blog.


  /**
     * 根据code 获取授权的token 仅限授权时使用,与全局的access_token不同
     * @param code
     * @return
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public String getOauthAccessToken(String code) throws ClientProtocolException, IOException{
        String data = redisService.get("WEIXIN_SQ_ACCESS_TOKEN");
        String rs_access_token = null;
        String rs_openid = null;
        String url = WX_OAUTH_ACCESS_TOKEN_URL + "?appid="+WX_APPID+"&secret="+WX_APPSECRET+"&code="+code+"&grant_type=authorization_code";        if (StringUtils.isEmpty(data)) {            synchronized (this) {                //已过期,需要刷新
                String hs = apiService.doGet(url);
                JSONObject json = JSONObject.parseObject(hs);
                String refresh_token = json.getString("refresh_token");
    
                String refresh_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+WX_APPID+"&grant_type=refresh_token&refresh_token="+refresh_token;
                String r_hs = apiService.doGet(refresh_url);
                JSONObject r_json = JSONObject.parseObject(r_hs);
                String r_access_token = r_json.getString("access_token");
                String r_expires_in = r_json.getString("expires_in");
                rs_openid = r_json.getString("openid");
                
                rs_access_token = r_access_token;
                redisService.set("WEIXIN_SQ_ACCESS_TOKEN", r_access_token, Integer.parseInt(r_expires_in) - 3600);
                LOGGER.info("Set sq access_token to redis is successful.parameters time:{},realtime",Integer.parseInt(r_expires_in), Integer.parseInt(r_expires_in) - 3600);
            }
        }else{            //还没有过期
            String hs = apiService.doGet(url);
            JSONObject json = JSONObject.parseObject(hs);
            rs_access_token = json.getString("access_token");
            rs_openid = json.getString("openid");
            LOGGER.info("Get sq access_token from redis is successful.rs_access_token:{},rs_openid:{}",rs_access_token,rs_openid);
        }        
        return getOauthUserInfo(rs_access_token,rs_openid);
    }
  /**
     * 根据授权token获取用户信息
     * @param access_token
     * @param openid
     * @return
     */
    public String getOauthUserInfo(String access_token,String openid){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ access_token +"&openid="+ openid +"&lang=zh_CN";        
        try {
            String hs = apiService.doGet(url);            
            //保存用户信息            
            saveWeixinUser(hs);            
            return hs;
        } catch (IOException e) {
            LOGGER.error("RestFul of authorization is error.",e);
        }        
        return null;
    }

I was in a hurry and the code naming was confusing. As you can see, I used a synchronous method. First, I obtained the key WEIXIN_SQ_ACCESS_TOKEN from the cache. If the obtained instructions are not expired, I directly called the interface provided by WeChat through httpclient and returned the string of user information to the front end. If it is not obtained, it means that it does not exist or has expired. Then refresh the access_token according to the refresh_token and then write the cache. Since the access_token has a short validity period, in order to be safe, I set the cache expiration time here and subtract one hour from the time given by WeChat. Looking back at the code, I found that there is a slight problem with the above logic. Writing it this way will cause the access_token to be refreshed for the first time or after the cache expires. It does not affect the use for the time being. We will make optimization and modification TODO later.

6: Save user information

Normally, after authorization, we will save the user information in the database table, openid is the only primary key, and the foreign key is associated with our own user table. In this way , no matter what business is to be carried out in the future, or whether it is to do operational data statistics, there is a relationship with the WeChat official account. It is worth noting that the headimgurl we obtained is a url address provided by WeChat. When the user modifies the avatar, the original address may become invalid, so it is best to save the image to the local server and then save the local address url. !

Value returned by WeChat:

微信开发之Author网页授权

For more related articles on Author webpage authorization for WeChat development, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn