


Detailed explanation of java WeChat development API server access
Mar 15, 2017 pm 05:10 PMThis article mainly shares with you the detailed explanation of server access for java WeChat development API. Interested friends can refer to
How to access the server through WeChat development API, as follows Let me introduce it to you
1. Description
* This example is based on the WeChat development document:http://mp.weixin.qq. com/wiki/home/index.html latest version (4/3/2016 5:34:36 PM) for development demonstration.
* Editing platform: myeclipse10.7+win32+jdk1.7+tomcat7.0
* Server: Alibaba Cloud windows server 2008 64bits
* Platform requirements :servletUse annotation method, platform requirements: j2ee6.0+, jdk6.0+, tomcat7.0+
* The demonstration focuses more on api analysis.
* In order to facilitate test description, each test case is independent and does not depend on other methods. Don't think much about packaging.
* The demonstration should be carried out in accordance with the API requirements as much as possible. The purpose is to understand how to use the document and achieve the effect of drawing inferences from one example.
* Knowledge requirements: solid java foundation, understanding of http network communication knowledge, sufficient understanding of javaweb, jsonanalysis
* Current time: 4/3/2016 5:32:57 PM , based on this time.
2. Original document (Abstract)
Document address: http://mp.weixin.qq.com/wiki /8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html
##To access the WeChat public platform for development, developers need to follow the following steps:
2. Verify the validity of the server address
3. Implement business logic based on the
interface document
1. The API is introduced as follows:
After the developer submits the information, the WeChat server will send a GET request to the filled in server address URL. The GET request carries four parameters: signature,timestamp, nonce, echostr Developers verify the request by checking the signature (the verification method is below).
If it is confirmed that this GET request comes from the WeChat server, please return the echostr parameter content as it is, then the access will take effect and become a developer successfully, otherwise the access will fail.
The encryption/verification process is as follows:
1) Sort the three parameters token, timestamp, and nonce in lexicographic order
2) Splice the three parameters
strings into one The string is sha1encrypted3). The encrypted string obtained by the developer can be compared with the signature to identify that the request comes from WeChat
2. Understanding
indicates that the request is in "GET" mode, and accessing the request will return four parameters: signature, timestamp, nonce, and echostr.We need to accept these parameters and then process them. If the verification is successful, return the received "echostr", otherwise the verification fails.
The verification method is to sort the received three parameters of token, timestamp, and nonce in lexicographic order, then perform sha1 encryption, and finally compare it with the signature.
*The encrypted string can be compared with the signature. If they are equal [the API may not be explained clearly], "echostr" will be returned and the verification is successful.
3. Implementation
#Create a servlet CoreServlet to implement HttpServlet,overload the doGet method. Parameter preparation
// 設(shè)置一個(gè)全局的token,開發(fā)者自己設(shè)置。api這樣解釋:Token可由開發(fā)者可以任意填寫, // 用作生成簽名(該Token會(huì)和接口URL中包含的Token進(jìn)行比對(duì),從而驗(yàn)證安全性) String token = "wgyscsf"; // 根據(jù)api說明,獲取上述四個(gè)參數(shù) String signature = req.getParameter("signature"); String timestamp = req.getParameter("timestamp"); String nonce = req.getParameter("nonce"); String echostr = req.getParameter("echostr");Proceed according to the three steps mentioned in the api
// 第一步:將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 String[] parms = new String[] { token, timestamp, nonce };// 將需要字典序排列的字符串放到數(shù)組中 Arrays.sort(parms);// 按照api要求進(jìn)行字典序排序【百度:什么是字典序排序】 // 第二步:將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密【百度:java sha1加密】 // 拼接字符串 String parmsString = "";// 注意,此處不能=null。 for (int i = 0; i < parms.length; i++) { parmsString += parms[i]; } // sha1加密 String mParms = null;// 加密后的結(jié)果 ... //該地方是sha1加密的實(shí)現(xiàn),不再貼代碼 mParms = hexString.toString();// 加密結(jié)果 /* * api要求: 若確認(rèn)此次GET請(qǐng)求來自微信服務(wù)器,請(qǐng)?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容, 則接入生效, 成為開發(fā)者成功,否則接入失敗。 */ // 第三步: 開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來源于微信接入成功。 System.out.println(TAG + ":" + mParms + "---->" + signature); if (mParms.equals(signature)) { // System.out.println(TAG + ":" + mParms + "---->" + signature); printWriter.write(echostr); } else { // 接入失敗,不用回寫 // System.out.println(TAG + "接入失敗"); }
4. Fill in the server configuration
1), including content The server configuration is mainly the server and the configuration that we need to configure after we write our own code to access the WeChat development platform. WeChat access interface.
2) Server operation
Open the tomcat of the server and put the written code under the webapps file.
3), WeChat public platform operation
* Apply for a WeChat test account (you can log in by scanning directly with WeChat):
http://ipnx.cn/
* Open the WeChat public platform test account and configure the interface configuration information. The configuration is as follows
URL: http://ipnx.cn/
Token:wgyscsf*Submit, there will be reminders for successful and failed configurations.
該部分所有操作源碼,可以直接使用
package com.gist.servlet; import java.io.IOException; import java.io.PrintWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author 高遠(yuǎn)</n> 郵箱:wgyscsf@163.com</n> 博客 http://ipnx.cn/;/n> * 編寫時(shí)期 2016-4-3 下午4:34:05 */ @WebServlet("/CoreServlet") public class CoreServlet extends HttpServlet { String TAG = "CoreServlet"; /* * 第二步:驗(yàn)證服務(wù)器地址的有效性 開發(fā)者提交信息后,微信服務(wù)器將發(fā)送GET請(qǐng)求到填寫的服務(wù)器地址URL上, * GET請(qǐng)求攜帶四個(gè)參數(shù):signature、timestamp、nonce、echostr * 開發(fā)者通過檢驗(yàn)signature對(duì)請(qǐng)求進(jìn)行校驗(yàn)(下面有校驗(yàn)方式)。 若確認(rèn)此次GET請(qǐng)求來自微信服務(wù)器,請(qǐng)?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容, * 則接入生效, 成為開發(fā)者成功,否則接入失敗。 * * 加密/校驗(yàn)流程如下: 1. 將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 2. * 將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密 3. 開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來源于微信 */ /* * 字典排序(lexicographical * order)是一種對(duì)于隨機(jī)變量形成序列的排序方法。其方法是,按照字母順序,或者數(shù)字小大順序,由小到大的形成序列。 */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設(shè)置編碼 req.setCharacterEncoding("utf-8"); resp.setContentType("html/text;charset=utf-8"); resp.setCharacterEncoding("utf-8"); // 獲取輸出流 PrintWriter printWriter = resp.getWriter(); // 設(shè)置一個(gè)全局的token,開發(fā)者自己設(shè)置。api這樣解釋:Token可由開發(fā)者可以任意填寫, // 用作生成簽名(該Token會(huì)和接口URL中包含的Token進(jìn)行比對(duì),從而驗(yàn)證安全性) String token = "wgyscsf"; // 根據(jù)api說明,獲取上述四個(gè)參數(shù) String signature = req.getParameter("signature"); String timestamp = req.getParameter("timestamp"); String nonce = req.getParameter("nonce"); String echostr = req.getParameter("echostr"); // // temp:臨時(shí)打印,觀看返回參數(shù)情況 // System.out.println(TAG + ":signature:" + signature + ",timestamp:" // + timestamp + ",nonce:" + nonce + ",echostr:" + echostr); // 根據(jù)api所說的“加密/校驗(yàn)流程”進(jìn)行接入。共計(jì)三步 // 第一步:將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 String[] parms = new String[] { token, timestamp, nonce };// 將需要字典序排列的字符串放到數(shù)組中 Arrays.sort(parms);// 按照api要求進(jìn)行字典序排序 // 第二步:將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密 // 拼接字符串 String parmsString = "";// 注意,此處不能=null。 for (int i = 0; i < parms.length; i++) { parmsString += parms[i]; } // sha1加密 String mParms = null;// 加密后的結(jié)果 MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } digest.update(parmsString.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字節(jié)數(shù)組轉(zhuǎn)換為 十六進(jìn)制 數(shù) for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } mParms = hexString.toString();// 加密結(jié)果 /* * api要求: 若確認(rèn)此次GET請(qǐng)求來自微信服務(wù)器,請(qǐng)?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容, 則接入生效, 成為開發(fā)者成功,否則接入失敗。 */ // 第三步: 開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來源于微信接入成功。 System.out.println(TAG + ":" + mParms + "---->" + signature); if (mParms.equals(signature)) { // System.out.println(TAG + ":" + mParms + "---->" + signature); printWriter.write(echostr); } else { // 接入失敗,不用回寫 // System.out.println(TAG + "接入失敗"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
java微信開發(fā)API的第一篇內(nèi)容就為大家介紹到這里,希望大家繼續(xù)關(guān)注之后的更新內(nèi)容,謝謝!
The above is the detailed content of Detailed explanation of java WeChat development API server access. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

PaymentHandlerAPI is part of the WebPayments standard, as an extension of PaymentRequestAPI, and its core role is to allow developers to register a "payment processor" to implement custom payment processes. It registers payment methods through ServiceWorker and combines the payment application manifest file under the .well-known directory to declare payment processor information. When used, the payment request is initiated through the PaymentRequest interface, the registered payment processor is called, and the complete() method is called after the payment is completed. Common precautions include: 1. Ensure HTTPS deployment; 2. Properly configure Service

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
