Home WeChat Applet WeChat Development Detailed explanation of java WeChat development API server access

Detailed explanation of java WeChat development API server access

Mar 15, 2017 pm 05:10 PM
api java WeChat development

This 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:

1. Fill in the server configuration

2. Verify the validity of the server address
3. Implement business logic based on the
interface document

3. Document understanding

Verify the validity of the server address

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


// 设置一个全局的token,开发者自己设置。api这样解释:Token可由开发者可以任意填写,
// 用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)
String token = "wgyscsf";
// 根据api说明,获取上述四个参数
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
Copy after login

Proceed according to the three steps mentioned in the api


// 第一步:将token、timestamp、nonce三个参数进行字典序排序
String[] parms = new String[] { token, timestamp, nonce };// 将需要字典序排列的字符串放到数组中
Arrays.sort(parms);// 按照api要求进行字典序排序【百度:什么是字典序排序】




// 第二步:将三个参数字符串拼接成一个字符串进行sha1加密【百度:java sha1加密】
// 拼接字符串
String parmsString = "";// 注意,此处不能=null。
for (int i = 0; i < parms.length; i++) {
  parmsString += parms[i];
}
// sha1加密
String mParms = null;// 加密后的结果

... //该地方是sha1加密的实现,不再贴代码    

mParms = hexString.toString();// 加密结果




/*
 * api要求: 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容, 则接入生效, 成为开发者成功,否则接入失败。
 */
// 第三步: 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信接入成功。
System.out.println(TAG + ":" + mParms + "---->" + signature);
if (mParms.equals(signature)) {
  // System.out.println(TAG + ":" + mParms + "---->" + signature);
  printWriter.write(echostr);
} else {
  // 接入失败,不用回写
  // System.out.println(TAG + "接入失败");
}
Copy after login

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://www.php.cn/
* Open the WeChat public platform test account and configure the interface configuration information. The configuration is as follows

URL: http://www.php.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 高远</n> 邮箱:wgyscsf@163.com</n> 博客 http://www.php.cn/;/n>
 *     编写时期 2016-4-3 下午4:34:05
 */
@WebServlet("/CoreServlet")
public class CoreServlet extends HttpServlet {
  String TAG = "CoreServlet";

  /*
   * 第二步:验证服务器地址的有效性 开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,
   * GET请求携带四个参数:signature、timestamp、nonce、echostr
   * 开发者通过检验signature对请求进行校验(下面有校验方式)。 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,
   * 则接入生效, 成为开发者成功,否则接入失败。
   * 
   * 加密/校验流程如下: 1. 将token、timestamp、nonce三个参数进行字典序排序 2.
   * 将三个参数字符串拼接成一个字符串进行sha1加密 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
   */
  /*
   * 字典排序(lexicographical
   * order)是一种对于随机变量形成序列的排序方法。其方法是,按照字母顺序,或者数字小大顺序,由小到大的形成序列。
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // 设置编码
    req.setCharacterEncoding("utf-8");
    resp.setContentType("html/text;charset=utf-8");
    resp.setCharacterEncoding("utf-8");
    // 获取输出流
    PrintWriter printWriter = resp.getWriter();

    // 设置一个全局的token,开发者自己设置。api这样解释:Token可由开发者可以任意填写,
    // 用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)
    String token = "wgyscsf";
    // 根据api说明,获取上述四个参数
    String signature = req.getParameter("signature");
    String timestamp = req.getParameter("timestamp");
    String nonce = req.getParameter("nonce");
    String echostr = req.getParameter("echostr");
    // // temp:临时打印,观看返回参数情况
    // System.out.println(TAG + ":signature:" + signature + ",timestamp:"
    // + timestamp + ",nonce:" + nonce + ",echostr:" + echostr);
    // 根据api所说的“加密/校验流程”进行接入。共计三步

    // 第一步:将token、timestamp、nonce三个参数进行字典序排序
    String[] parms = new String[] { token, timestamp, nonce };// 将需要字典序排列的字符串放到数组中
    Arrays.sort(parms);// 按照api要求进行字典序排序
    // 第二步:将三个参数字符串拼接成一个字符串进行sha1加密
    // 拼接字符串
    String parmsString = "";// 注意,此处不能=null。
    for (int i = 0; i < parms.length; i++) {
      parmsString += parms[i];
    }
    // sha1加密
    String mParms = null;// 加密后的结果
    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();
    // 字节数组转换为 十六进制 数
    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();// 加密结果

    /*
     * api要求: 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容, 则接入生效, 成为开发者成功,否则接入失败。
     */
    // 第三步: 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信接入成功。
    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);
  }

}
Copy after login

java微信开发API的第一篇内容就为大家介绍到这里,希望大家继续关注之后的更新内容,谢谢!

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

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 vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

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.

See all articles