Table of Contents
1. Configure the security callback domain name:
2. User-level authorization and silent authorization
3. The difference between web page authorization access_token and ordinary access_token
4. Guide the user to enter the authorization page to agree to the authorization and obtain the code
js:
getWxUserInfo method:
5.Background restful-- / wechat/authorization, exchange user information according to code
6: Save user information
Home WeChat Applet WeChat Development Author webpage authorization developed by WeChat

Author webpage authorization developed by WeChat

Feb 15, 2017 am 11:15 AM
java WeChat public account development

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();
}
Copy after login

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
                    }
                }
            }
        });
    },
Copy after login

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();
        }
    }
Copy after login

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;
    }
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles