Obtain openId from Weixin Java MP (Weixin java tools) to realize Spring Boot 2.0 integration from zero for wechat authorization

**
Steps:**

1, * intranet penetration application for secondary domain name (those with server and domain name can be omitted)*

2, * apply for wechat public platform test number * (those with * certified * wechat service number can skip)**

3, Build Spring Boot 2.0 project to obtain openId

1, Intranet penetration:

Because it is necessary to directly use the intranet to develop and debug the local machine, and the wechat web page authorization needs to access the local machine during callback, it is necessary to make an intranet penetration directly, so you can directly access the local machine on the Internet. The method is as follows:

1. Login https://natapp.cn/ (I use natapp.cn. You can use other similar ones. Personally, I think this is good)

2. Purchase tunnel:

You need to authenticate before you buy. Don't use free ones, because free ones are randomly assigned domain names, which will change every time_ Type 1 is 5 yuan, but now it has risen to 9 yuan. Choose by yourself (official 10% discount code 709ABD4F). I bought VIP_ Type 2, as shown in the figure below after purchase:

Usage after purchase: https://natapp.cn/article/natapp_newbie

After use, you will get the website assigned by natapp, such as XXX natapp. Cn, this address can access the development machine.

2, Application wechat public platform test number:

Wechat public platform test application address: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

After opening it, click "login" to display a QR code and directly scan wechat. After login, it is as follows:

The above appID and appsecret are what we will use later. Then scan the QR code of the following test number to pay attention to:

Finally, bind the domain name of the authorization callback page:

XXX above natapp. Cn fill in the domain name you obtained above

3, Build Spring Boot 2.0 project

IDEA new project:

Lombok was chosen for convenience

After construction, it is as follows:

pom.xml (relying on Weixin Java MP 2.9.0)

<?xml version="1.0" encoding="UTF-8"?>



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"



	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">



	<modelVersion>4.0.0</modelVersion>



 



	<groupId>com.wechat</groupId>



	<artifactId>auth</artifactId>



	<version>0.0.1-SNAPSHOT</version>



	<packaging>jar</packaging>



 



	<name>auth</name>



	<description>Demo project for Spring Boot</description>



 



	<parent>



		<groupId>org.springframework.boot</groupId>



		<artifactId>spring-boot-starter-parent</artifactId>



		<version>2.0.0.RELEASE</version>



		<relativePath/> <!-- lookup parent from repository -->



	</parent>



 



	<properties>



		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>



		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>



		<java.version>1.8</java.version>



	</properties>



 



	<dependencies>



		<dependency>



			<groupId>org.springframework.boot</groupId>



			<artifactId>spring-boot-starter-web</artifactId>



		</dependency>



 



        <dependency>



            <groupId>org.projectlombok</groupId>



            <artifactId>lombok</artifactId>



            <optional>true</optional>



        </dependency>



 



		<dependency>



			<groupId>com.github.binarywang</groupId>



			<artifactId>weixin-java-mp</artifactId>



			<version>2.9.0</version>



		</dependency>



 



		<dependency>



			<groupId>org.springframework.boot</groupId>



			<artifactId>spring-boot-starter-test</artifactId>



			<scope>test</scope>



		</dependency>



	</dependencies>



 



	<build>



		<plugins>



			<plugin>



				<groupId>org.springframework.boot</groupId>



				<artifactId>spring-boot-maven-plugin</artifactId>



			</plugin>



		</plugins>



	</build>



 



</project>

application.yml (formerly application.properties, directly changed to. yml, concise and convenient)

In the two values, fill in the mpAppId and mpAppSecret obtained above

wechat:



  mpAppId: xxxxxxxxxxxx



  mpAppSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxx

WechatAccountConfig.java (convert the above configuration to Bean)

package com.wechat.config;



 



import lombok.Data;



import org.springframework.boot.context.properties.ConfigurationProperties;



import org.springframework.stereotype.Component;



 



@Data



@Component



@ConfigurationProperties(prefix = "wechat")



public class WechatAccountConfig {



 



    private String mpAppId;



 



    private String mpAppSecret;



 



}

WeChatMpConfig.java (configure WxMpService Bean)

package com.wechat.config;



 



import me.chanjar.weixin.mp.api.WxMpConfigStorage;



import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;



import me.chanjar.weixin.mp.api.WxMpService;



import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;



import org.springframework.beans.factory.annotation.Autowired;



import org.springframework.context.annotation.Bean;



import org.springframework.stereotype.Component;



 



@Component



public class WeChatMpConfig {



 



    @Autowired



    private WechatAccountConfig wechatAccountConfig;



 



    @Bean



    public WxMpService wxMpService(){



        WxMpService wxMpService = new WxMpServiceImpl();



        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());



        return wxMpService;



    }



 



    @Bean



    public WxMpConfigStorage wxMpConfigStorage(){



        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();



        wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());



        wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());



        return wxMpConfigStorage;



    }



}

WechatController.java (change xxx.natapp.cn to the domain name obtained with natapp)

package com.wechat.controller;



 



import lombok.extern.slf4j.Slf4j;



import me.chanjar.weixin.common.api.WxConsts;



import me.chanjar.weixin.common.exception.WxErrorException;



import me.chanjar.weixin.mp.api.WxMpService;



import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;



import org.springframework.beans.factory.annotation.Autowired;



import org.springframework.stereotype.Controller;



import org.springframework.web.bind.annotation.GetMapping;



import org.springframework.web.bind.annotation.RequestMapping;



import org.springframework.web.bind.annotation.RequestParam;



 



import java.net.URLEncoder;



 



@Controller



@RequestMapping("/wechat")



@Slf4j



public class WechatController {



 



    @Autowired



    private WxMpService wxMpService;



 



    @GetMapping("/authorize")



    public String authorize(@RequestParam("returnUrl") String returnUrl){



        String url = "http://xxx.natapp.cn/wechat/userInfo";



        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));



        log.info("[Wechat web page authorization] acquisition code,redirectURL={}", redirectURL);



        return "redirect:" + redirectURL;



    }



 



    @GetMapping("/userInfo")



    public String userInfo(@RequestParam("code") String code,



                         @RequestParam("state") String returnUrl) throws Exception {



        log.info("[Wechat website authorization] code={}", code);



        log.info("[Wechat website authorization] state={}", returnUrl);



        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;



        try {



            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);



        } catch (WxErrorException e) {



            log.info("[Wechat website authorization]{}", e);



            throw new Exception(e.getError().getErrorMsg());



        }



        String openId = wxMpOAuth2AccessToken.getOpenId();



        log.info("[Wechat website authorization] openId={}", openId);



        return "redirect:" + returnUrl + "?openid=" + openId;



    }



}

Start the Spring Boot project:

Visit xxx.com via wechat natapp. cn/wechat/authorize? Returnurl = 'callback address', you can see that openId is printed on the console. After callback, you can operate your own business.

Wechat web page authorization] state={}", returnUrl);

    WxMpOAuth2AccessToken wxMpOAuth2AccessToken;



    try {



        wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);



    } catch (WxErrorException e) {



        log.info("[Wechat website authorization]{}", e);



        throw new Exception(e.getError().getErrorMsg());



    }



    String openId = wxMpOAuth2AccessToken.getOpenId();



    log.info("[Wechat website authorization] openId={}", openId);



    return "redirect:" + returnUrl + "?openid=" + openId;



}

}



start-up Spring Boot Project:

[External chain picture transfer...(img-nruVUCuM-1621151172831)]



Access via wechat xxx.natapp.cn/wechat/authorize?returnUrl='Address of callback' You can see that the console prints out openId´╝îAfter callback, you can operate your own business.



On request Gitee On: https://gitee.com/antma/SpringBootGetOpenId.git

Keywords: Spring Framework

Added by Canabalooza on Fri, 11 Feb 2022 05:34:33 +0200