


Using JAVA to develop WeChat public platform (1) - environment construction and development access
1. Initial WeChat Public Platform
The WeChat public platform, which is what we usually call "public account", was once named "official platform" and "media platform", but it was finally named "public platform". From the naming of WeChat, I can find that the public platform is not just a platform used by officials and media, but a unified platform open to all the public.
WeChat public platform address: https://mp.weixin.qq.com/
WeChat public platform has four major sections: subscription account, service account, mini program, and enterprise account. According to WeChat’s 2016 open course plan, the Enterprise Account will be merged with Enterprise WeChat in the future, so we will mainly start to explain the first three parts:
Account registration
Enter the WeChat public platform https://mp.weixin.qq.com and click Register now in the upper right corner, select "Service Account" or "Subscription Account" to register (service accounts are only available for institutionsuser registration, individual users can only choose subscription accounts)
You need to fill in one when registering Just fill in the series information according to the prompts and will not be repeated here. 2. Test account application If you do not want to register an account for the time being, or cannot register a service account, you can choose to apply for an official test account. Application address: http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login Click and scan the QR code to get a test account with all the permissions of the service account.Development environment preparation
1. External network mapping tool When the WeChat public platform accesses the backend, it must provide an external network address that can be correctly accessed. The WeChat platform has two requirements for the backend URL:① It must be able to use the public network Access ② must use port 80
To achieve the above two points, we can choose to purchase an external network server, such as Alibaba Cloud, Baidu Cloud, Tencent Cloud... are all good choices. If there is no server, you can choose to use an external network mapping tool to map our internal network link to the public network. Good mapping software includes: peanut shell, ngrok, nat123, etc...These softwares can all be used It is easy tosearch on Baidu and download it. Here is a brief explanation of how to use it:
① Ngrock:
Enter the dos environment and switch to the disk where ngrock is located character, enter ngrock8080 and press Enter:
②Peanut shell and nat123 can be installedAfter the software is installed, operate it in the software. For details, please check Baidu experience: http: //jingyan.baidu.com/article/363872ec361d3f6e4ba16ff9.html I won’t go into details here
4. WeChat public platform data interaction principleAfter setting up the public network access address, we developed it ourselves The background code can be placed on the public network address, so how do users access our code?Let’s take a look at the data interaction principle of the WeChat public platform:
1. Fill in the server configurationEnter the WeChat public platform, click [Development - Basic Configuration] on the left, and select [Server Configuration]. You can enter the configuration page:
URL: That is what we mentioned above The public network access address of the backend server Token: the developer’s customized verification password EncodingAES2. Verify whether the message is validWhen we click submit, the WeChat server will send a Get Request, go to our above address, and pass four parameters at the same time:Key: a random string , if The message encryption and decryption method adopts security mode only requires verification
1. Use MyEclipse to create a Web project and create a new servlet:
2. In the doGet method of the servlet, obtain the above four verification parameters:
3. Write a tool class to operate the verification method:
4. Call the verification method in the Servlet and verify the result . If the verification is successful, the obtained random string eahostr will be returned to the WeChat platform in the original way:
5. Start Tomcat and map the local address of the Servlet (for example, this machine is: localhost:8080/WeiXin/servlet/WeiXinServlet) to the public network. Refer to the third part above. , perform public network mapping to ensure that the public network address can be accessed correctly.
I will directly put the code on the public network server for access. Get the following address7. Configure the public platform backend
Enter the WeChat backend configuration related information:
WeChat backend configuration related information
Click submit, WeChat will send the Get command to the Servlet, and call the doGet method to perform the verification operation we wrote. Finally, if a random string is returned successfully, the binding is successful.
8. Source code sharing
1. Servlet source code (only keep the doGet part):
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); if(CheckUtil.checkSignature(signature, timestamp, nonce)){ //如果校验成功,将得到的随机字符串原路返回 out.print(echostr); } }Copy after login
2. CheckUtil source code (can be directly CopygetSha1 encryption method):
package com.jredu.util; import java.security.MessageDigest; import java.util.Arrays; public class CheckUtil { public static final String tooken = "jredu100"; //开发者自行定义Tooken public static boolean checkSignature(String signature,String timestamp,String nonce){ //1.定义数组存放tooken,timestamp,nonce String[] arr = {tooken,timestamp,nonce}; //2.对数组进行排序 Arrays.sort(arr); //3.生成字符串 StringBuffer sb = new StringBuffer(); for(String s : arr){ sb.append(s); }Copy after login
//4.sha1加密,网上均有现成代码 String temp = getSha1(sb.toString()); //5.将加密后的字符串,与微信传来的加密签名比较,返回结果 return temp.equals(signature); } public static String getSha1(String str){ if(str==null||str.length()==0){ return null; } char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA1"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char buf[] = new char[j*2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf];}Copy after login
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA1"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char buf[] = new char[j*2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (Exception e) { // TODO: handle exception return null; } } }Copy after login
The above is the detailed content of Using JAVA to develop WeChat public platform (1) - environment construction and development access. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
