Home  >  Article  >  WeChat Applet  >  Detailed explanation of java WeChat development API server access

Detailed explanation of java WeChat development API server access

高洛峰
高洛峰Original
2017-03-15 17:10:361718browse

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");

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 + "接入失败");
}

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);
  }

}

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