Using WxJava to implement website integration with WeChat login function, the core code should not exceed 10 lines

Posted by tuneout on Thu, 29 Aug 2019 04:44:27 +0200

Recently, the website PC-side integrated WeChat scanner login, stepped on a number of pits, and recorded the implementation process and considerations.

Table of Contents

1. Operational steps of WeChat Open Platform1. Create a Web Site Application2. Get AppID and AppSecret2. Development Guidelines3. Development of Actual Warfare1. pom.xml introduced jar package2. Configuration File Add Corresponding Configuration3. Initialize Configuration4. Control Layer Core CodeIV. Operational results1. Construct pc-side links2. Two-dimensional code generated by WeChat scanning3. Get information about WeChat users

1. Operational steps of WeChat Open Platform

WeChat Open Platform Address: https://open.weixin.qq.com

It is important to note that the site integration of WeChat login requires operation on the open platform of WeChat, which is different from the public platform of WeChat. Although the unique identity of the last user of both sides is openId, it is not interoperable.If the development platform wants to communicate with the public platform, the two platforms must bind to each other and obtain unionId s that are uniquely identified.

Here are the steps to operate on an open platform:

1. Create a Web Site Application

Since you logged in to the docking PC website, create a "Web Site Application" with the following screenshots:



New Site Application Screenshot

2. Get AppID and AppSecret

After the WeChat approval, the corresponding AppId will be assigned, AppSecret needs administrator to scan and generate, and the generated screenshots are as follows:


View AppId Screenshot

 

2. Development Guidelines

WeChat OAuth2.0 authorized login enables WeChat users to login securely to third-party applications or websites using their WeChat identity. After a WeChat user authorizes a third-party application that has access to WeChat OAuth2.0, the third party can obtain the user's interface call credentials (access_token) and authorize the WeChat Open Platform through access_token.Relational interface calls, which can achieve access to basic open information of micro-credit users and help users to achieve basic open functions, etc. The overall process is:

1. After a third party initiates a WeChat authorized login request, WeChat will pull up the application or redirect to the third party website with the code parameter of the authorized temporary ticket when a WeChat user allows authorized third party applications;
2. Exchange access_token through API with code parameter plus AppID, AppSecret, etc.
3. Make interface calls through access_token to get users'basic data resources or to help users achieve basic operations.

3. Development of Actual Warfare

The project uses the open source project WxJava, WxJava source address (https://github.com/Wechat-Group/WxJava);

Create a new Spring Boot project first, referring to the article I wrote earlier Getting Started with Spring Boot - Quick Building a web Project

Once you have created a new project, follow the steps below.

1. pom.xml introduced jar package

<!-- WeChat Login jar -->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-mp</artifactId>
    <version>3.3.0</version>
</dependency>

2. Configuration File Add Corresponding Configuration

Configure appId and appSecret, as follows within application.yml:

wx:
  mp:
    configs:
        - appid: wx1*********
          secret: ***********
          token: 
          aesKey: 
          msgDataFormat: 

3. Initialize Configuration

The WxMpProperties.java code is as follows:

@Data
@ConfigurationProperties(prefix = "wx.mp")
public class WxMpProperties {

    private List<MpConfig> configs;

    @Data
    public static class MpConfig {
        /**
         * appid to set the WeChat public number
         */

        private String appId;

        /**
         * app secret to set WeChat public number
         */

        private String secret;

        /**
         * Set token for WeChat public number
         */

        private String token;

        /**
         * EncodingAESKey Setting the WeChat Public Number
         */

        private String aesKey;
    }

}

The WxMpConfiguration.java code is as follows:

@Slf4j
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {

    private static Map<String, WxMpService> mpServices = Maps.newHashMap();

    public static Map<String, WxMpService> getMpServices() {
        return mpServices;
    }

    @Autowired
    private WxMpProperties properties;

    @Autowired
    private WxMpInRedisConfigStorageMy configStorage;

    @PostConstruct
    public void initServices() {
        //The students who made mistakes in the getConfigs() code, please read the project instructions carefully, your IDE needs to introduce lombok plug-in!!!!
        final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("Big Brother, please see the instructions on the first page of the project first ( readme File), add the relevant configuration, be careful not to mismatch!");
        }

        mpServices = configs.stream().map(a -> {
            //redis
            configStorage.setAppId(a.getAppId());
            configStorage.setSecret(a.getSecret());
            configStorage.setToken(a.getToken());
            configStorage.setAesKey(a.getAesKey());

            WxMpService service = new WxMpServiceImpl();
            service.setWxMpConfigStorage(configStorage);
            log.info("Configured appId={}",a.getAppId());
            return service;
        }).collect(Collectors.toMap(s -> s.getWxMpConfigStorage().getAppId(), a -> a, (o, n) -> o));
    }
}

4. Control Layer Core Code

@Slf4j
@Controller
@RequestMapping("/redirect/{appid}")
public class WxRedirectController {

    /**
     * Get user information
     *
     */

    @RequestMapping("/getUserInfo")
    public void getBase(HttpServletRequest request, HttpServletResponse response, @PathVariable String appid, @RequestParam("code") String code) {
        WxMpService mpService = WxMpConfiguration.getMpServices().get(appid);
        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            log.info("accessToken={}", JSON.toJSONString(accessToken));
            WxMpUser wxMpUser = mpService.oauth2getUserInfo(accessToken, null);
            log.info("wxMpUser={}", JSON.toJSONString(wxMpUser));
        } catch (Exception e) {
            log.error("Get user information exception!", e);
        }
    }
}

IV. Operational results

1. Construct pc-side links

https://open.weixin.qq.com/connect/qrconnect?appid=wx12345678redirect_uri=http%3a%2f%2fwww.test.com%2fredirect%2fwx12345678%2fgetUserInfo&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect

Open the link above and take the following screenshot:


2. Two-dimensional code generated by WeChat scanning

The screenshots of the mobile phone end after WeChat scan are as follows:


When WeChat users scan QR codes and confirm their login, the PC will jump to

http://www.test.com/redirect/wx12345678/getUserInfo?code=CODE&state=STATE

3. Get information about WeChat users

The control layer code can receive the above code and state parameters, which can be used to obtain micro credit user information. The log of user information after request is printed is as follows:

[http-nio-8104-exec-2] INFO  c.t.m.s.c.WxRedirectController - accessToken={"accessToken":"24_vWnvRSV9vmR7qOqhJKRoER93bhsPg","expiresIn":7200,"openId":"oRXsdsUh6scaKof3D1I4d3c","refreshToken":"24_WmknxCn9ff2Pl2xhLFw-kY96p6zgiqFJy8LMIOP_CaMZOHEM","scope":"snsapi_login","unionId":"oJxUkwfFOSyu1oC6oF2h6pTI"}
[http-nio-8104-exec-2] INFO  c.t.m.s.c.WxRedirectController - wxMpUser={"city":"","country":"","headImgUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4ibeAsuoVIf3qr4QxjnNWh4Q1WiawCFNfzkGMzVqubPOnr0hA3Micwsu1LtblQ7phImdYSC2nic6OUicQ/132","language":"","nickname":"Albert","openId":"oRXsdsUh6scaKof3D1I4d3c","privileges":[],"province":"","sex":0,"sexDesc":"Unknown","unionId":"oaDUkwVfCpMJOSyu1oC2oF2h6pTI"}

The integration of WeChat login on this PC website has been completed. If you have any questions, please leave a message to communicate.

Recommended reading

1.Spring Boot 2.X Integrated Redis
2.How does Spring Boot 2.X gracefully solve cross-domain problems?
3.Spring Boot 2.X Integrated spring session for session sharing
4.Spring Conditional Comment@Conditional
5.SpringBoot 2.X from 0 to 1 for mail delivery
6.Redis's tips for deleting key s in bulk, you know?
7. How does Spring Boot 2.X integrate jpa quickly?
8. Profile of Spring Boot--Quick multi-environment use and switching
9.Spring Boot Fast Integration kaptcha Generate Authentication Code
10.Spring Boot 2.X Integrates Spring-cache to make your site fly faster

Free Java-related materials are available within a time limit, covering technologies such as Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo/Kafka, Hadoop, Hbase, Flink, high concurrent distribution, big data, machine learning, etc.
Pay free attention to the following public numbers:


 

Topics: Java Spring Redis xml