1. What is the process of WeChat authorization to log in the small program
The process of WeChat authorization to log into the applet is a process that involves front-end and back-end interactions, the main purpose of which is to enable users to use their WeChat account to quickly log into the applet, avoiding the need to repeatedly enter usernames and passwords. The following are the detailed steps of the process:
1.1 Front-end operations
(1) Trigger login:
- When the user clicks the "Login" button in the app or enters the page that requires login, the system will automatically pop up the authorization login box (or pop up when the user enters the app for the first time).
- By clicking the "Agree" button, the user agrees to authorize the app to access his/her WeChat account information.
(2) Obtain temporary login credentials:
- Applet front-end calls
()
interface to send a login request to the WeChat server. - After the WeChat server verifies the user's identity, it returns a temporary login credential (code) to the applet front-end.
(3) Send the code to the backend:
- The applet front-end sends the fetched code to the developer's own back-end server.
1.2 Back-end operations
(1) Receive code
- The back-end server receives the code sent by the front-end.
(2) Swap openid and session_key:
- The back-end server calls WeChat's login credential verification interface using code (e.g.
/sns/jscode2session
), sends a request to the WeChat server. - The request needs to contain the applet's
appid
、secret
and the code sent by the front end. - After the WeChat server passes the verification, it will return to the back-end server the user's
openid
cap (a poem)session_key
。
(3) Generate customized login credentials (optional):
- The back-end server can use the
openid
cap (a poem)session_key
Generate a customized user login credential (e.g. token) for subsequent user authentication and data manipulation.
(4) Returns the login result:
- The back-end server returns the login results (which may include custom login credentials, user information, etc.) to the applet front-end.
1.3 Front-end follow-up
(1) Save login credentials:
- After the front-end of the applet receives the login result returned from the back-end, the custom login credentials (e.g., token) are saved locally (e.g., using the
()
)。
(2) Jump or display information:
- As needed, the applet front-end can jump to the main page or display user information.
1.4 Precautions
- user experience: The authorization process needs to be as simple as possible to avoid excessive steps and waiting time for the user.
- data security: In order to protect the security of user information, the authorization login process needs to use the HTTPS protocol for data transmission, and at the same time, appropriate encryption of the acquired user information.
- Adaptation to different devices: Considering the possible differences in different devices, developers need to conduct sufficient testing and debugging when implementing the authorization login function to ensure compatibility on different devices.
- Working with back-end servers: The authorization login process requires communication with the back-end server, so it is necessary to ensure that the interface protocols and data formats between the front-end and back-end servers are clearly defined to avoid errors.
- Handling of anomalies: In the process of authorization login, it is inevitable to encounter various abnormalities, such as network connection failure, server failure, etc., which require the development of appropriate handling strategies.
With the above steps, users can quickly log in to the small program using their WeChat account and enjoy a convenient service experience.
2. Java WeChat authorization login applet interface example
Directly provide a fully working Java backend service code sample involving the authorization login process for WeChat applets, which will involve multiple parts including Java backend, database (optional), WeChat applet frontend, etc., and will also require registering the WeChat applet and obtaining the necessary API keys and other information. Below I will outline the entire process and give key code samples for the Java backend which will be implemented based on the Spring Boot framework.
2.1 WeChat applet authorization login process overview
(1)The user clicks on the login button of the WeChat app: Trigger the login process.
(2)WeChat Small Program Call: Get
code
(temporary login credentials).
(3)The applet willcode
Send to backend: The back end is used to exchangesession_key
cap (a poem)openid
。
(4)Backend call to WeChat API: Useappid
、secret
respond in singingcode
give sth and get sth in returnsession_key
cap (a poem)openid
。
(5)Back-end generation of custom login states(e.g., JWT): theopenid
cap (a poem)session_key
(optional) and other information is encrypted into the JWT.
(6)The backend returns JWT to the applet: The applet stores JWT for authentication of subsequent requests.
2.2 Preparatory work
- Sign up for the WeChat app and get
appid
cap (a poem)secret
。 - Build a Java development environment and introduce the Spring Boot framework.
- Add the WeChat SDK (e.g.
weixin-java-tools
) to the project for simplifying API calls.
2.3 Back-end code example
2.3.1 Maven Dependencies
First, in theAdd the necessary dependencies to the
spring-boot-starter-web
cap (a poem)weixin-java-mp
As an example:
<dependencies>
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>weixin-java-mp</artifactId>
<version>Latest version number</version>
</dependency>
<!-- Other dependencies -->
</dependencies>
2.3.2 Controller
import ;
import ;
import ;
import .WxMpOAuth2AccessToken;
import ;
import ;
import ;
import ;
@RestController
public class WeChatController {
@Autowired
private WxMpService wxMpService; // Assuming you have configured thisBean
@GetMapping("/login")
public String login(@RequestParam("code") String code) throws Exception {
// utilizationcodegive sth and get sth in returnsessionKeyrespond in singingopenId
WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
String openId = ();
// Here you can generateJWTand return it to the front end
// The example does not directly generateJWT,return onlyopenIdas a demonstration
return "Login successful, openId: " + openId;
}
}
take note of: Here's theWxMpService
You are required to follow theweixin-java-mp
The library is configured to includeappid
、secret
and other information is set.
2.3.3 Configuring the WxMpService
Typically, you need to configure the Spring Boot configuration class in theWxMpService
bean, this includes loading the configuration file for theappid
cap (a poem)secret
etc.
2.4 Cautions
- Make sure your server IP address has been added to the WeChat app's server domain.
- Protect yours.
appid
cap (a poem)secret
, don't leak to the front end. - Considering the security, the front-end transmission of
code
The HTTPS protocol should be used.
Due to space and security considerations, here does not directly provide a complete configuration file containing sensitive information and JWT generation code. You need to configure and improve these parts according to the actual needs.
3. Java WeChat authorization login applet interface code example
To implement the authorization login interface for WeChat applets in Java, you usually need to process in the backend thecode
(temporary login credentials) and then use thiscode
Go ahead and call WeChat's API in exchange for thesession_key
cap (a poem)openid
. The following is a simplified Java back-end code example that uses the Spring Boot framework and theweixin-java-mp
(a popular WeChat Java SDK) to demonstrate the process.
First, make sure you have added the necessary dependencies to your project, such as the Spring Boot startup dependency and theweixin-java-mp
。
3.1 Maven Dependencies
in yourAdd the following dependencies (be careful to check for the latest version):
<dependencies>
<!-- Spring Boot initial reliance -->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- microsoftJava SDK -->
<dependency>
<groupId></groupId>
<artifactId>weixin-java-mp</artifactId>
<version>Your version number.</version>
</dependency>
<!-- Other dependencies... -->
</dependencies>
3.2 Configuring the WxMpService
Configure in your Spring Boot applicationWxMpService
This usually involves loading theappid
、secret
and other configuration information. It is assumed here that you are using a configuration file (e.g.maybe
) to store this information.
@Configuration
public class WechatConfig {
@Value("${}")
private String appid;
@Value("${}")
private String secret;
@Bean
public WxMpService wxMpService() {
WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
(appid);
(secret);
WxMpServiceImpl wxMpService = new WxMpServiceImpl();
(config);
return wxMpService;
}
}
3.3 Controller
Create a controller to handle login requests sent from an applet.
@RestController
@RequestMapping("/api/wechat")
public class WechatController {
@Autowired
private WxMpService wxMpService;
@GetMapping("/login")
public ResponseEntity<String> login(@RequestParam("code") String code) {
String code) { try {
// Use code to get access_token and openid information.
WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
String openId = ();
String sessionKey = (); // Note: session_key may be called sessionKey in some versions of the SDK
// Here you can generate the JWT or do other business logic.
// ...
// The response to the front-end (this information may not be returned directly in the actual project).
Map<String, String> result = new HashMap<>();
("openid", openId);
// You can also return the sessionKey if you want, but it's usually not recommended to return it directly to the frontend
// ("sessionKey", sessionKey); // The session key can be returned if desired, but it's not usually recommended to return it directly to the frontend.
return ((result)); // Assuming you're using Alibaba's fastjson library
} catch (WxErrorException e) {
// Handle the WeChat API call exception
return (HttpStatus.INTERNAL_SERVER_ERROR).body("WeChat login failure: " + ());
}
}
}
take note of:
(1) In the code example above, I have used the@Value
annotation to load theappid
respond in singingsecret
. You need to make sure that these values have been set correctly in the configuration file.
(2) I used thefastjson
library to convert the result to a JSON string, but you can use any JSON processing library you like.
(3) In real projects, you may also need to deal with additional security and authentication logic, such as checking that the requested IP address is within the allowed range and using HTTPS to protect data transmission.
(4)sessionKey
is a sensitive piece of information that should not normally be returned directly to the front-end. It can be used on the backend to decrypt user information (e.g., the user's encrypted data) or to generate JWTs, etc.
(5) Ensure that your Spring Boot application can handle cross-domain requests (if the front-end and applet are not deployed under the same domain). This can usually be accomplished by adding CORS support.