Java Micro-Trust Development API First step server access _java

Source: Internet
Author: User
Tags arrays sha1 sha1 encryption stringbuffer

Micro-Credit Development API How to access the server, the following for you to introduce

I. Description

* This sample develops a demo based on the micro-trust Development Documentation:http://mp.weixin.qq.com/wiki/home/index.html latest edition (4/3/2016 5:34:36 PM).
* Editing Platform: myeclipse10.7+win32+jdk1.7+tomcat7.0
* Server: Aliyun Windows Server 2008 64bits
* Platform requirements: servlet use annotation mode, platform requirements: j2ee6.0+, jdk6.0+, tomcat7.0+
* Demos are more focused on API parsing.
* For ease of testing, each test case is independent and does not depend on other methods. For encapsulation, do not consider.
* Demo as far as possible according to API requirements, the purpose: To understand how the document is used to achieve extrapolate effect.
* Knowledge Requirements: Solid Java Foundation, understanding of HTTP network communication knowledge, enough knowledge for Javaweb, JSON parsing
* Current time: 4/3/2016 5:32:57 PM, whichever is the time.

Second, the original document (abstract)

Document Address:http://mp.weixin.qq.com/wiki/8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html
with the development of the public platform, developers need to complete the following steps:

1, fill in the server configuration
2, verify the validity of the server address
3. Implement business logic according to interface document

Third, document understanding

Verify the validity of the server address

1, the API this introduction:

After the developer submits the information, the micro-server sends the GET request to the completed server address URL, and the GET request carries four parameters: signature, timestamp, nonce, echostr
The developer verifies the request by checking the signature (there is a check method below).
If you confirm this get request from the micro-trust server, please return the ECHOSTR parameter content, then the access is effective, the developer succeeds, otherwise the access failed.
The encryption/validation process is as follows:
1), the token, timestamp, nonce three parameters to order the dictionary order
2), the three parameter string concatenation into a string for SHA1 encryption
3, the developer obtains the encrypted string can compare with the signature, the identification this request originates from the micro-letter

2. Understand

Describes the request as a "get" method, and accessing the request returns four parameters: Signature, timestamp, nonce, Echostr.
We need to accept these parameters and then do the processing. If the validation succeeds, the received "ECHOSTR" is returned, or the validation fails.
The method of authentication is to sort the token, timestamp, nonce three parameters and then sha1 the encryption, and then compare it with signature.
* The encrypted string can be compared to the signature, and if the equivalence "where the API may explain is not too clear", return "ECHOSTR" to verify success.

3. Realize

Create a servlet Coreservlet implement HttpServlet, overload the Doget method.
Parameter preparation

Set up a global token, the developer sets itself. The API explains this: token can be filled out by the developer,
////used as a generating signature (the token is compared to the token contained in the interface URL to verify security)
String token = "WGYSCSF";
According to the API description, get the above four parameters
String signature = req.getparameter ("signature");
String timestamp = req.getparameter ("timestamp");
String nonce = Req.getparameter ("nonce");
String echostr = Req.getparameter ("Echostr");

Follow the three steps that the API says

Step One: Sort token, timestamp, nonce three parameters in dictionary order
string[] parms = new string[] {token, timestamp, nonce};//to place strings that need a dictionary order into several Group
Arrays.sort (parms); in the dictionary order according to the API requirements "Baidu: What is the dictionary order"




//Step two: Concatenation of three parameter strings into a string for SHA1 encryption "Baidu: Java SHA1 Encryption"
concatenation string
parmsstring = ""; Note that you cannot =null here. for
(int i = 0; i < parms.length i++) {
  parmsstring + = Parms[i];
}
SHA1 encryption
String mparms = null;//result after encryption ...

//The place is SHA1 encryption implementation, no longer stick code    

mparms = hexstring.tostring ();//Encryption result
 * * API requirements: If you confirm that the GET request from the micro-trust server, please return the ECHOSTR parameter content, then access to effective, become successful developers, otherwise access failed.
 *
//Step Three: The encrypted string can be compared with signature by the developer to identify the request from the success of the micro-mail access.
System.out.println (TAG + ":" + mparms + "---->" + signature);
if (mparms.equals (signature)) {
  //System.out.println (TAG + ":" + mparms + "---->" + signature);
  Printwriter.write (ECHOSTR);
} else {
  //access failed without writeback
  //System.out.println (TAG + "Access failed");
}  

4, fill in the server configuration

1), including content
The server configuration is primarily the server and the micro-mail access interface that is configured when we write our own code to access the micro-credit development platform.
2), server operation
Open the server Tomcat and put the written code under the WebApps file.
3), micro-trust public platform operation
* Application for micro-letter test account (directly with micro-mail sweep can be logged in):Http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
* Open the Micro-trust public platform test number, configure the interface configuration information. Configured as follows
Url:http://ip/weixinapidemo/coreservlet
TOKEN:WGYSCSF
* Submit, configuration success and failure will be a reminder.

This part all operation source code, may use directly

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 lofty </n> Mailbox:wgyscsf@163.com</n> Blog http://blog.csdn.net/wgyscsf</n> * Writing period 2016-4-3 afternoon

  4:34:05 */@WebServlet ("/coreservlet") public class Coreservlet extends HttpServlet {String TAG = "Coreservlet"; * * Second step: Verify the validity of the server address after the developer submits the information, the micro-server sends the GET request to the completed server address URL, * The request carries four parameters: signature, timestamp, nonce, ECHOSTR * developer through Verify that the request is verified by the signature (there is a check method below).
   If you confirm this get request from the micro-trust server, please return the ECHOSTR parameter content, * The access is effective, the developer succeeds, otherwise the access failed. * * The encryption/verification process is as follows: 1.
   Sort the token, timestamp, nonce three parameters in dictionary order 2. * Concatenation of three parameter strings into a string for SHA1 encryption 3.
  The developer obtains the encrypted string to compare with the signature, identifies the request from the micro-letter * * * Dictionary sort (lexicographical * order) is a sort of sequence for random variable formation.
   The method is to form a sequence of small to large, in alphabetical order, or in small numbers. * * @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOE
    Xception {//Set encoding req.setcharacterencoding ("Utf-8");
    Resp.setcontenttype ("Html/text;charset=utf-8");
    Resp.setcharacterencoding ("Utf-8");

    Gets the output stream printwriter PrintWriter = Resp.getwriter (); Set up a global token, the developer sets itself.
    The API explains this: token can be filled out by the developer,////used as a generating signature (the token is compared to the token contained in the interface URL to verify security) String token = "WGYSCSF";
    According to the API description, get the above four parameters String signature = req.getparameter ("signature");
    String timestamp = req.getparameter ("timestamp");
    String nonce = Req.getparameter ("nonce");
    String echostr = Req.getparameter ("Echostr"); Temp: Temporarily print, watch return parameter condition//System.out.println (TAG + ": Signature:" + signature + ", Timestamp:"//+ timestamp + ",
    Nonce: "+ nonce +", Echostr: "+ echostr"; Access is based on the API's "encryption/validation process". TotalThree steps//First step: Sort token, timestamp, nonce three parameters in dictionary order string[] parms = new string[] {token, timestamp, nonce};//will need a dictionary order  string into the array arrays.sort (parms);//Step two: concatenate three parameter strings into a string for SHA1 encryption//stitching string parmsstring
    = ""; Note that there is no =null here.
    for (int i = 0; i < parms.length i++) {parmsstring + = Parms[i];
    }//SHA1 encryption String mparms = null;//The result of encryption 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 (); The byte array is converted to a hexadecimal number for (int i = 0; i < messagedigest.length; i++) {String Shahex = integer.tohexstring (messag
      Edigest[i] & 0xFF);
if (Shahex.length () < 2) {hexstring.append (0);      } hexstring.append (Shahex); Mparms = hexstring.tostring ()///encryption Results/* API requirements: If you confirm that the GET request from the micro-trust server, please return the ECHOSTR parameter content, then access to effective, become a developer success, or access lost
     Defeat.
    *//Step Three: The encrypted string can be compared with signature by the developer to identify the request from the success of the micro-mail access.
    System.out.println (TAG + ":" + mparms + "---->" + signature);
      if (mparms.equals (signature)) {//System.out.println (TAG + ":" + mparms + "---->" + signature);
    Printwriter.write (ECHOSTR);
    else {//access failed without writeback//System.out.println (TAG + "Access failed"); } @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception
  , IOException {doget (req, resp);

 }

}

Java micro-Trust Development API, the first content is introduced here, I hope you continue to pay attention to the updated content, thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.