This article is about the first step of micro-credit development, public access and Access_token management.
I. Access to micro-credit public number
In the micro-credit Development manual, the section on public number access is more detailed, the document says that access to the public number requires 3 steps, respectively:
- 1, fill in the server configuration
- 2, verify the validity of the server address
- 3. Implement business logic according to interface document
In fact, the 3rd step has not been counted as the public number access steps, but after the access, developers can be based on the micro-public number of the interface provided by the development of some.
In step 1th, the server configuration contains the server address (URL), token, and Encodingaeskey.
The server address is the public number background to provide the business logic of the entry address, currently only support 80 ports, and then include access verification and any other operation of the request (such as message delivery, menu management, material management, etc.) from this address to enter. The difference between access verification and other requests is that access authentication is a GET request, and other times is a POST request;
Token can be filled out arbitrarily by the developer and used as a generating signature (the token is compared to the token contained in the interface URL to verify security);
The encodingaeskey is either manually filled out or randomly generated by the developer and will be used as the message body encryption key. In this example, all are in an unencrypted plaintext message and do not involve this configuration item.
2nd step, verify the validity of the server address, when the "submit" button is clicked, the micro-server will send an HTTP GET request to the server address just filled in and carry four parameters:
After receiving the request, we need to do the following three steps, if you confirm that the GET request from the micro-trust server, return the ECHOSTR parameter content, the access is effective, otherwise access failed.
- 1. Sort 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
The code speaks, and the following is a portal servlevt I define, in which the checksum method is defined in the Doget method:
Token private final String token = "Fengzheng"; protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {Sy
Stem.out.println ("Start signature checksum");
String signature = request.getparameter ("signature");
String timestamp = request.getparameter ("timestamp");
String nonce = Request.getparameter ("nonce");
String echostr = Request.getparameter ("Echostr");
arraylist<string> array = new arraylist<string> ();
Array.add (signature);
Array.add (timestamp);
Array.add (nonce);
Sort String sortstring = sort (token, timestamp, nonce);
Encrypted String MyToken = DECRIPT.SHA1 (sortstring); Checksum signature if (MyToken!= null && mytoken!= "" && mytoken.equals (signature)) {System.out.println ("signature checksum pass.")
"); Response.getwriter (). println (ECHOSTR);
If the test output ECHOSTR successfully, the micro-trust server receives this output before confirming the test completion. else {System.out.println ("signature checksum failed.")
"); /** * Sorting Method * @param token * @param timestamp * @param nonce * @return/public sTatic string Sort (string token, string timestamp, string nonce) {string[] Strarray = {token, timestamp, nonce};
Arrays.sort (Strarray);
StringBuilder Sbuilder = new StringBuilder ();
for (String Str:strarray) {sbuilder.append (str);
return sbuilder.tostring ();
}
The following code is the method of encryption:
public class Decript {public
static string SHA1 (String decript) {
try {
MessageDigest digest = messagedigest< C4/>.getinstance ("SHA-1");
Digest.update (Decript.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);
}
return hexstring.tostring ();
} catch (NoSuchAlgorithmException e) {
e.printstacktrace ();
}
Return "";
}
}
The XML for the servlet map is as follows:
<servlet>
<servlet-name>Start</servlet-name>
<servlet-class> org.fengzheng.wechat.start</servlet-class>
</servlet>
<servlet-mapping>
< servlet-name>start</servlet-name>
<url-pattern>/wechat</url-pattern>
</ Servlet-mapping>
I'm using IntelliJ idea+tomcat7.0 development, start the project directly, and then use Ngrok to map the local 8080 ports to the extranet. Enter the micro-credit test public number management interface, and fill in the interface configuration information to map the external network address and Token
Click the Submit button and the page prompts for a successful configuration.
Will go to the IDE and see the information in the console output
Second, Access_token management
Before the Access_token, there are two important parameters to know, the two parameters are AppID and Appsecret, which are automatically assigned to the public number when applying for public numbers, the equivalent of the public number of identification, in many interfaces need these two parameters, These two parameters are then required when requesting access_token.
After the public number has been successfully accessed, the logic will be implemented accordingly. In the use of the micro-letter public number interface, it is found that many requests require access_token. Access_token is the public number's globally unique voucher, the public number calls each interface to use the Access_token. Developers need to be properly saved. Access_token storage should be reserved for at least 512 character spaces. The validity period of the Access_token is currently 2 hours and needs to be refreshed periodically, and repeated acquisition will cause the last acquired access_token to fail. and the upper limit for getting the Access_token interface is called 2000 times per day.
Summing up the above instructions, Access_token need to do the following two points:
- 1. Because the Access_token has a 2-hour timeliness, there is a mechanism to ensure that the maximum of 2 hours can be retrieved once;
- 2. Because the interface calls the upper limit 2000 times a day, so cannot call too frequently;
In this context, the solution here is to define a default-initiated servlet that starts a thread in the Init method, which defines an infinite loop method for obtaining Access_token, which, when successful, sleeps for 7,000 seconds, Otherwise hibernate for 3 seconds to continue getting. The flowchart is as follows:
The following is the formal beginning of the project to achieve the above ideas, because the returned data are in JSON format, here will be used in the Ali Fastjson Library, for the construction of the request and processing the request after the data serialization and deserialization to provide support. Subsequent other interfaces will also be used.
1. Define a Accesstoken entity
public class Accesstoken {public
String Getaccesstoken () {return
accesstoken;
}
public void Setaccesstoken (String accesstoken) {
this.accesstoken = Accesstoken;
}
public int Getexpiresin () {return
expiresin;
}
public void Setexpiresin (int expiresin) {
this.expiresin = expiresin;
}
Private String Accesstoken;
private int expiresin;
}
2. Define a default boot servlet, start a thread in the Init method, and set this servlet to the default web.xml in the boot.
import javax.servlet.ServletException; import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import java.io.IOException; @WebServlet (name = "Accesstokenservlet") public class Accesstokenservlet extends HttpServlet {public void init () throw s servletexception {tokenthread.appid = Getinitparameter ("appId");//get servlet initial parameters appId and Appsecret tokenthread.appsec
ret = Getinitparameter ("Appsecret");
System.out.println ("AppID:" +tokenthread.appid);
System.out.println ("Appsecret:" +tokenthread.appsecret); New Thread (New Tokenthread ()). Start (); Start process} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex ception {} protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {}}
Set up the servlet self-boot in Web.xml and set initialization parameters AppID and Appsecret
<servlet>
<servlet-name>initAccessTokenServlet</servlet-name>
<servlet-class>
org.fengzheng.wechat.accesstoken.AccessTokenServlet
</servlet-class>
<init-param>
<param-name>appid</param-name>
<param-value>your appid</param-value>
</ init-param>
<init-param>
<param-name>appsecret</param-name>
<param-value >your appsecret</param-value>
</init-param>
<load-on-startup>0</ Load-on-startup>
</servlet>
3. Define the thread class, in which you invoke Access_token to get the interface and abstract the resulting data to static entities for use elsewhere. Interface address is Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET , wherein the grant_type is fixed and written as client_credential. This request is a GET request for HTTPS, and the data format returned is {"Access_token": "Access_token", "expires_in": 7200}.
The
Process class implementation is as follows:
Import Com.alibaba.fastjson.JSON;
Import Com.alibaba.fastjson.JSONObject;
Import Org.fengzheng.wechat.common.NetWorkHelper;
public class Tokenthread implements Runnable {public static String appId = "";
public static String appsecret= "";
<br>//Note is static public static accesstoken Accesstoken = null;
public void Run () {while (true) {try{Accesstoken = This.getaccesstoken ();
if (Null!=accesstoken) {System.out.println (Accesstoken.getaccesstoken ()); Thread.Sleep (7000 * 1000);
Get to Access_token hibernate 7,000 seconds}else{Thread.Sleep (1000*3);//Get Access_token for empty hibernate 3 seconds}}catch (Exception e) {
System.out.println ("An exception occurred:" +e.getmessage ());
E.printstacktrace (); try{Thread.Sleep (1000*10); abnormal hibernation 1 seconds}catch (Exception E1) {}}}/** * Get Access_token *
@return * * Private Accesstoken Getaccesstoken () {Networkhelper nethelper = new Networkhelper (); String URL = String.Format ("Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s ", This.appid,this.appsecret);
String result = Nethelper.gethttpsresponse (Url, "");
SYSTEM.OUT.PRINTLN (result);
Response.getwriter (). println (result);
Jsonobject JSON = json.parseobject (result);
Accesstoken token = new Accesstoken ();
Token.setaccesstoken (json.getstring ("Access_token"));
Token.setexpiresin (Json.getinteger ("expires_in"));
return token;
}
}
Where the Gethttpsresponse method in Networkhelper is to request an HTTPS address, the parameter requestmethod is either a string "get" or "POST", or null or "" Default to Get method.
Implemented as follows:
public string Gethttpsresponse (string hsurl,string requestmethod) {URL url;
InputStream is = null;
String resultdata = "";
try {url = new URL (hsurl);
Httpsurlconnection con = (httpsurlconnection) url.openconnection ();
Trustmanager[] tm = {XTM};
Sslcontext CTX = sslcontext.getinstance ("TLS");
Ctx.init (NULL, TM, NULL);
Con.setsslsocketfactory (Ctx.getsocketfactory ());
Con.sethostnameverifier (New Hostnameverifier () {@Override public boolean verify (String arg0, sslsession arg1) {
return true;
}
}); Con.setdoinput (TRUE); Allow input stream, that is, allow downloads//In Android must set this to False Con.setdooutput (false); Allow output stream, that is, allow upload con.setusecaches (false); Do not use buffer if (Null!=requestmethod &&!requestmethod.equals ("")) {Con.setrequestmethod (Requestmethod); else{Con.setrequestmethod ("get") by using the specified method;////using GET request} is = Con.getinputstream ();
Gets the input stream, the link is actually established inputstreamreader ISR = new InputStreamReader (IS); BufferedreAder Bufferreader = new BufferedReader (ISR);
String inputline = "";
while ((Inputline = Bufferreader.readline ())!= null) {Resultdata + = inputline + "\ n";
} System.out.println (Resultdata);
certificate[] certs = Con.getservercertificates ();
int certnum = 1;
for (certificate cert:certs) {x509certificate Xcert = (x509certificate) cert;
} catch (Exception e) {e.printstacktrace ();
return resultdata; X509trustmanager XTM = new X509trustmanager () {@Override public x509certificate[] Getacceptedissuers () {/To
Do auto-generated method stub return null;
@Override public void checkservertrusted (x509certificate[] arg0, String arg1) throws Certificateexception { TODO auto-generated Method stub} @Override public void checkclienttrusted (x509certificate[] arg0, String ar
G1) throws Certificateexception {//TODO auto-generated Method stub}};
Now that the code is complete, deploy the project and see the console output as follows:
To look at the effect, you can set the hibernation time a little bit, such as 30 seconds to get one, and then the Access_token output. The following is a test JSP page, and the hibernation time set to 30 seconds, so that after 30 seconds to refresh the page, you can see the changes, by the way to show how to get access_token in other places
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
<%@ page import= " Org.fengzheng.wechat.accesstoken.TokenThread "%>
This page is browsed in the browser, showing the following effect:
Refresh after 30 seconds, this value has changed:
This article has been organized into the "Android micro-credit Development tutorial Summary," Welcome to learn to read.
The above is the entire content of this article, I hope that the development of Java micro-credit to help the public number.