[WeChat login] WeChat scan code login for APP/website applications

table of Contents

1. Development documentation

1. WeChat login on the mobile application APP (Android/Apple)

2. Website application PC-side WeChat scan code login

3. Apply for an account on the WeChat open platform

Two, business interface development

1. Configuration

2. The first step: request CODE

3. Step 2: Obtain access_token through code

4. Tool method

5. Test


1. Development documentation

1. WeChat login on the mobile application APP (Android/Apple)

Ready to work

Mobile application WeChat login is a WeChat OAuth2.0 authorized login system based on the OAuth2.0 protocol standard .

Before performing WeChat OAuth2.0 authorized login access, register a developer account on the WeChat open platform, have an approved mobile application, and obtain the corresponding AppID and AppSecret. After applying for WeChat login and passing the audit, you can start to access Into the process .

  1. At present, WeChat login on mobile applications only provides native login methods, which require users to install a WeChat client to cooperate.
  2. For Android applications, it is recommended to always display the WeChat login button. When the WeChat client is not installed on the user's mobile phone, please guide the user to download and install the WeChat client.
  3. For iOS apps, considering the relevant regulations in the iOS App Store Review Guidelines, it is recommended that developers first check the user's mobile phone when logging in to WeChat

Authorization process description

WeChat OAuth2.0 authorized login allows WeChat users to securely log in to third-party applications or websites using WeChat identity. After the WeChat user is authorized to log in to third-party applications that have access to WeChat OAuth2.0, the third party can obtain the user's interface call credentials ( access_token) ), through access_token, we can call the authorization relationship interface of the WeChat open platform, so as to obtain basic open information of WeChat users and help users realize basic open functions.

WeChat OAuth2.0 authorized login currently supports authorization_code mode, which is suitable for application authorization with server side. The overall process of this model is:

  1.  The third party initiates a WeChat authorization login request. After the WeChat user allows the third-party application to be authorized, WeChat will launch the application or redirect to the third-party website, and bring the authorization temporary ticket code parameter;
  2.  Add AppID and AppSecret through the code parameter and exchange for access_token through API;
  3.  Interface calls are made through access_token to obtain user basic data resources or help users implement basic operations.

Get access_token sequence diagram:

Note: Please refer to the official website development document for details, here is only an excerpt: https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html

2. Website application PC-side WeChat scan code login

Website application WeChat login is a WeChat OAuth2.0 authorized login system based on the OAuth2.0 protocol standard. Before performing WeChat OAuth2.0 authorization login access, register a developer account on the WeChat open platform, and have an approved website application, and obtain the corresponding AppID and AppSecret . After applying for WeChat login and passing the audit, you can start to access Into the process.

The PC terminal is actually similar to the mobile application terminal. When we develop the back-end, we provide a unified interface for the PC and APP terminals. Some differences are dealt with in the specific business logic layer. To connect to WeChat, please refer to the official website: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html

3. Apply for an account on the WeChat open platform

In the above development document for the WeChat login interface, the preparation work has clearly stated: Before the WeChat OAuth2.0 authorized login access, register a developer account on the WeChat open platform, and have an approved mobile application/web application. And get the corresponding AppID and AppSecret, apply for WeChat login and pass the review, you can start the access process. For details, please log in to apply: https://open.weixin.qq.com/

The following is a website application that I have applied for approval. Just create it step by step and fill it out step by step. The final authorized callback domain can be written in your own website domain name, without adding http or https, such as: www.baidu.com

Two, business interface development

Note: Because the front and back ends are separated, only the business development process that provides back-end interfaces is shown here.

The project is built using SpringBoot , and the configuration center and registration center use nacos , and some configuration information can be placed on nacos.

1. Configuration

(1) Website application-PC

Put the relevant information of the website application (PC) applied for on the WeChat open platform into the configuration file (appId, appSercet, etc.). Of course, the interface address of WeChat is basically fixed and can also be written in the constant class.

Among them, the callBack configuration is the callback address (public network address) after obtaining the code authorized by WeChat, which can be a back-end interface or a front-end interface (the front and the back are separated, and the front-end will adjust the back-end).

(2) Mobile applications-Android, IOS

Among them, the interface address of WeChat is the same as that of PC, so there is no need to configure

2. The first step: request CODE

The configuration information here is uniformly obtained and provided by the back-end interface, without the front-end hardcoded, so that you can directly modify the configuration center in the future; then the front-end initiates a call to the WeChat party. After the user is authorized, it will call back and return the code .

(1) Website application-PC

    /**
     * pc端获取微信二维码地址
     * <p>
     * 返回code地址等参数给前端,由前端js请求跳转二维码
     * 用户扫码确认授权后,微信会回调返回code、state
     * <p>
     *
     * @return
     * @throws
     */
    @RequestMapping("/pc/weixin/login/getCodeUrl")
    public Result getCodeUrl() throws Exception {
        //String codeUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE";
        String codeUrl = pcConfig.getCodeUrl();

        // state用于保持请求和回调的状态,授权请求后原样带回给第三方。
        // 该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验
        // 注:这里采用AES加密,使用当前时间作为明文加密,x小时内有效
        String encryptState = AesUtils.encrypt(DateUtils.getNowYYYYMMdd(), AesUtils.getAssetsDevPwdField());

        Map<String,String> map = new HashMap<>();
        map.put("appId",pcConfig.getAppId());
        map.put("redirectUrl",pcConfig.getCallBack());
        map.put("scope",pcConfig.getScope());
        map.put("state",encryptState);
        map.put("codeUrl",codeUrl);

        return Result.success(map);
    }

(2) Mobile applications-Android, IOS

    /**
     * APP获取移动应用的appId等配置
     *
     * @return
     * @throws
     */
    @RequestMapping("/app/weixin/login/getAppConfig")
    public Result getAppConfig() throws Exception {

        String appId = appConfig.getAppId();

        // 采用AES加密,使用当前时间作为明文加密,x小时内有效
        String encryptState = AesUtils.encrypt(DateUtils.getNowYYYYMMdd(), AesUtils.getAssetsDevPwdField());
        Map<String, String> map = new HashMap<>();
        map.put("appId", appId);
        map.put("state", encryptState);

        return Result.success(map);
    }

When the user authorizes WeChat to log in, WeChat will call back and return the code and state

Return description

After the user allows authorization, it will be redirected to the URL of redirect_uri (that is, the callBack we configured above) with the code and state parameters

redirect_uri?code=CODE&state=STATE

If the user prohibits authorization, the code parameter will not be taken after redirection, only the state parameter will be taken

redirect_uri?state=STATE

3. Step 2: Obtain access_token through code

Get access_token through code

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

Parameter Description

parameter Do you have to Description
appid Yes The unique identification of the application, which is obtained after the application is reviewed and approved on the WeChat open platform
secret Yes App Secret AppSecret, obtained after submitting the application for approval on the WeChat open platform
code Yes Fill in the code parameters obtained in the first step
grant_type Yes 填authorization_code

Because the project adopts front-end and back-end separation, here the callBack callback address on the PC side is the front-end address filled in, and the front-end calls the back-end interface ( /weixin/login/callBack )

General process : User authorization--->code--->get access_token, openid, etc.--->get basic information of WeChat users--->register/login

    /**
     * 授权回调,微信返回code、state---【PC端、APP端公用】
     * <p>
     * 1、然后通过code、appid、secret去请求获取access_token、openid
     * 2、最后通过access_token、openid去获取用户信息(unionid)
     * <p>
     */
    @RequestMapping("/weixin/login/callBack")
    public Result callBack(@RequestBody WeixinLoginDTO dto, HttpServletRequest request) throws Exception {
        log.info("【微信登录】回调,code:{},state:{}", dto.getCode(), dto.getState());

        try{
            // AES解密state
            boolean b = checkState(dto.getState());
            if(!b){
                log.error("【微信登录】回调异常,state已失效或被篡改:{}", dto.getState());
                return Result.error(ResultCode.STATE_IS_INVALID);
            }

            // 先判断缓存中是否已存在(微信获取access_token的接口code只能使用一次)
            String weixinUserJson = (String) redisUtils.get(RedisPrefix.weixin_user_info, dto.getCode());
            if (StringUtils.isNotBlank(weixinUserJson)) {
                // 直接登录
                return this.weixinLogin(dto.getCode(),weixinUserJson, dto.getSource(), request);
            }

            //1.通过code获取access_token
            //String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
            String accessTokenUrl = pcConfig.getAccessTokenUrl();

            if ("PC".equals(dto.getSource())) {//pc端
                accessTokenUrl = accessTokenUrl.replace("APPID", pcConfig.getAppId()).replace("SECRET", pcConfig.getAppSecret()).replace("CODE", dto.getCode());
            } else {// app端
                accessTokenUrl = accessTokenUrl.replace("APPID", appConfig.getAppId()).replace("SECRET", appConfig.getAppSecret()).replace("CODE", dto.getCode());
            }

            HttpClientResult tokenResult = HttpClientUtils.doGet(accessTokenUrl);
            log.info("【微信登录】获取access_token结果:{}",tokenResult);
            if (200==tokenResult.getCode()) {
                JSONObject tokenInfoObject = JSON.parseObject(tokenResult.getContent());

                if (StringUtils.isNotEmpty(tokenInfoObject.getString("errcode"))) {
                    log.error("【微信登录】获取access_token失败:{}", tokenInfoObject.getString("errmsg"));
                    return Result.error(ResultCode.WEIXIN_LOGIN_ERROR);
                }

                //2.通过access_token和openid获取用户信息
                //String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
                String userInfoUrl = pcConfig.getUserInfoUrl();
                userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN", tokenInfoObject.getString("access_token")).replace("OPENID", tokenInfoObject.getString("openid"));
                HttpClientResult weixinUserResult = HttpClientUtils.doGet(userInfoUrl);
                log.info("【微信登录】获取微信用户信息结果:{}",weixinUserResult);
                if (200==weixinUserResult.getCode()) {

                    JSONObject weixinUserObject = JSON.parseObject(weixinUserResult.getContent());

                    if (StringUtils.isNotEmpty(weixinUserObject.getString("errcode"))) {
                        log.error("【微信登录】获取微信用户信息失败:{}", weixinUserObject.getString("errmsg"));
                        return Result.error(ResultCode.WEIXIN_LOGIN_ERROR);
                    }
                    // todo 登录或注册
                    return this.weixinLogin(dto.getCode(),weixinUserResult.getContent(), dto.getSource(), request);
                }
            }
        }catch (Exception e){
            log.error("================【微信登录】回调接口异常:{}",e.getMessage());
        }
        log.error("【微信登录】回调失败!");
        return Result.error(ResultCode.WEIXIN_LOGIN_ERROR);
    }

Among them, " todo login or registration " means that you need to develop specific registration/login business logic based on your business needs.

Return description: Obtain user information through access_token and openid

The correct Json returns the result:

{
    "openid":"OPENID",
    "nickname":"NICKNAME",
    "sex":1,
    "province":"PROVINCE",
    "city":"CITY",
    "country":"COUNTRY",
    "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
    "privilege":[
        "PRIVILEGE1",
        "PRIVILEGE2"
    ],
    "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

}

4. Tool method

5. Test

Scan the authorized login on the PC to see if the WeChat user information can be obtained after the callback

Note: As the project adopts the separation of front and back ends, this article only provides back-end interface development instructions. The general process is similar. For specific request parameters and response information, please refer to the official website.

reference:

https://open.weixin.qq.com/

https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html

●The strongest Tomcat8 performance optimization in history

Why can Alibaba resist 10 billion in 90 seconds? --The evolution of server-side high-concurrency distributed architecture

B2B e-commerce platform--ChinaPay UnionPay electronic payment function

Learn Zookeeper distributed lock, let interviewers look at you with admiration

SpringCloud e-commerce spike microservice-Redisson distributed lock solution

Check out more good articles, enter the official account--please me--excellent in the past

A deep and soulful public account 0.0

Guess you like

Origin blog.csdn.net/a1036645146/article/details/111227147