WeChat webpage development (3)--WeChat webpage authorization

1. What is authorization

First explain what authorization is. Authorization refers to WeChat users, authorizing webpages to obtain user-related information.

That is to say, in order to protect the privacy rights of users, WeChat official does not allow web pages developed by us to obtain user information by default, and we need to allow users to authorize.

2. Two authorization methods

There are two authorization methods, snsapi_base and snsapi_userinfo.

snsapi_base is silently authorized, and does not require the user's manual consent, but this authorization method can only obtain access_token and openID.

snsapi_userinfo can obtain more user information, such as avatar, gender, nickname, but requires the user to manually confirm the authorization. Also note that if the user has followed the official account, the use of snsapi_userinfo is also a silent authorization when entering the official account webpage. WeChat officials believe that since the official account is concerned, the official account has the right to obtain user information.

3. Web page authorization access_token and ordinary access_token

This is a very confusing concept. The ordinary access_token is used by the public account interface, and the web page authorization access_token is used by calling the web interface. They are not the same and have different functions.

It's too easy to mislead developers by complaining about WeChat and making a name.

4. Web page authorization process

WeChat webpage authorization is implemented through OAuth2.0, and you are familiar with the easy-to-understand process of OAuth2.0. If you are not familiar with it, I will explain it here. It is really difficult to understand.

The first step is to construct a url to guide the user to authorize. After the user authorizes, the authorization code code will be sent to the callback address we specified.

The second step is to obtain web page authorization access_token and openid through code.

The third step is to obtain the JSSDK configuration information in order to call various WeChat JS interfaces.

5. Web page authorization code development

5.1 Project Construction

Create SpringBoot project and introduce WeChat public account and WeChat payment dependencies.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>cn.pandabrother</groupId>
	<artifactId>wx-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<!-- 添加swagger2相关功能 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- 添加swagger-ui相关功能 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- 微信公众号 -->
		<dependency>
			<groupId>com.github.binarywang</groupId>
			<artifactId>weixin-java-mp</artifactId>
			<version>4.1.0</version>
		</dependency>
		<!-- 微信支付 -->
		<dependency>
			<groupId>com.github.binarywang</groupId>
			<artifactId>weixin-java-pay</artifactId>
			<version>4.1.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

5.2 Modify the configuration file

Modify the configuration file application.yml, and set the startup port to access the path.

server:
   port: 80 #端口
   servlet:
      context-path: /wx-server

5.3 Development startup class

/**
 * SpringBoot启动类
 */
@SpringBootApplication
public class WxServerApplication {
    
    
	public static void main(String[] args) {
    
    
		SpringApplication.run(WxServerApplication.class, args);
	}
}

5.4 Develop public account configuration class

Develop a configuration class for the official account, and inject parameters such as the appid and appsecret of the official account into the container. Note that the code xxxneeds to be replaced with actual parameters.

/**
 * 微信公众平台配置
 */
@Configuration
public class WxMpConfig {
    
    

	@Bean
	public WxMpDefaultConfigImpl wxMpDefaultConfigImpl() {
    
    
		WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
		config.setAppId("xxx"); // 设置微信公众号的appid
		config.setSecret("xxx"); // 设置微信公众号的app corpSecret
		config.setToken("xxx"); // 设置微信公众号的token
		config.setAesKey("xxx"); // 设置微信公众号的EncodingAESKey
		return config;
	}

	@Bean
	public WxMpService wxMpService() {
    
    
		WxMpService wxMpService = new WxMpServiceImpl();// 实际项目中请注意要保持单例,不要在每次请求时构造实例,具体可以参考demo项目
		wxMpService.setWxMpConfigStorage(wxMpDefaultConfigImpl());
		return wxMpService;
	}
}

5.5 Developing the Controller

Develop the back-end controller WxPageController related to WeChat web pages:

/**
 * 微信网页控制器
 */
@Controller
public class WxPageController {
    
    
	@Autowired
	private WxMpService wxMpService;

	/**
	 * 第一步,引导用户授权
	 */
	@GetMapping("/wxAuth")
	public String wxAuth(HttpServletRequest request) throws Exception {
    
    
		String url = "http://easypanda.oicp.io/wx-server/wxUserInfo";
		String redirectUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
		return "redirect:" + redirectUrl;
	}

	/**
	 * 第二步,用户授权后,回调该方法,拿到code换取access_token
	 */
	@GetMapping("/wxUserInfo")
	public String userInfo(@RequestParam("code") String code, @RequestParam("state") String state) throws Exception {
    
    
		WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
		String openId = wxOAuth2AccessToken.getOpenId();
		// 返回我们开发的网页
		return "redirect:" + "http://easypanda.oicp.io/wx-server/wxpage.html?openid=" + openId;
	}

	/**
	 * 第三步,获取JSSDK配置信息
	 */
	@GetMapping("/wxJsapiSignature")
	@ResponseBody
	public WxJsapiSignature wxJsapiSignature(String url) throws Exception {
    
    
		return wxMpService.createJsapiSignature(url);
	}

}

It should be noted here that I use the domain name address accessible from the public network for the webpage addresses here, and the intranet penetration is used here. If you have a public network server, you can also choose to use the public network server to test directly.

5.6 Develop and test web pages

For the convenience of testing, we create a static folder in the resource directory and develop the wxpage.html page:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
	hello
</body>
</html>

6. Test

6.1 Web page authorization test

Open the developer tool, enter the address http://easypanda.oicp.io/wx-server/wxAuthto guide the user to authorize, and the developer tool prompts:
insert image description here
we log in to the official account, and add the current domain name in [Settings and Development]-[Official Account Settings]-[Function Settings]-[Webpage Authorization Domain Name] . Note that you need to download the txt file here and put it in the root directory of the domain name.
insert image description here
At this time, try again, note that the method at this time is SNSAPI_USERINFOthat WeChat reminds the user to authorize:
insert image description here
we replace it with SNSAPI_BASE, and request authorization again: at this time, you can directly enter the webpage we specified.

6.2 Get user code test

After entering our designated webpage, we copy the redirection address in the address bar:

http://easypanda.oicp.io/wx-server/wxpage.html?openid=oINiq6UqTiKqfXN3H6RmeKvvRnmw

It can be seen that the user's openid has been successfully obtained, that is, after the user is authorized, it will automatically be directed to the wxUserInfomethod and pass the code parameter.

6.3 Get JSSDK configuration information test

At this time http://easypanda.oicp.io/wx-server/wxJsapiSignature, you can access the JSSDK configuration information, as follows:

{
    
    "appId":"wxa0168d6e3b5547ff","nonceStr":"AbMcd6UcZNgmBcSa","timestamp":1643016353,"url":null,"signature":"91073ffc3ef83f88908356be7fbee0c01a65c5ff"}

We can call JSSDK through this configuration information.

7. Local address test problem

We can access http://127.0.0.1/wx-server/wxAuth, but if the callback address fills in the local address, WeChat will prompt that the redirect_uri parameter is wrong, so it is inconvenient to use the local address to test.

8. Summary

The process of WeChat webpage authorization is indeed quite winding, but this function is more important, including the follow-up WeChat public account payment development, which also requires webpage authorization.

In addition, in most cases, the SNSAPI_BASEauthorization method can be used, and the silent experience is better than the pop-up prompt for authorization!

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/122670090