Unicom E-interface development
Version 0.1
Copyright © 2005 M5
Some time to develop Unicom E interface, encounter a lot of problems, and finally completed the development of the interface in the help of friends and their own exploration. There are also a variety of problems in the SP Alliance Forum, so the development details will be organized, hoping to help people who are still as plagued as I originally. For the first time, I feel a bit of a little unable to start, the interface guide is a few hundred pages. I don't know when I developed the access platform for the test, but write code for the interface specification, and then simulate the interface. The rules generate data, which are completed in unit tests to access the UNI-Wise test environment, and there are many problems.
table of Contents
Overview
SSO interface
1.1. Transmission Safety
1.2. Generate a request ticket root
1.3. Analytical response ticket roots
2. Book interface
2. Issurate a scheduled request
2.2. Resolution Uni-Wise Request
2.3. Verification request
2.4. Responding to the scheduled request
3. Scheduled cancellation interface
3.1. Initiate cancellation request
3.2. Resolution Uni-Wise cancel request
3.3. Verification request
3.4. Response request
4. Web Push interface
4.1. Submit Push
Overview
This article uses Java language as an example, tells the little drip developed by the color e interface. The reference guide is "China Unicom value-added business integrated management and access platform SP interface specification v1.2", and the text code is tested and the Uni-Wise platform can operate normally. Color e and the SP interface include: SSO interface, predetermined interface, cancel interface, color e push interface, pick up the PUSH interface, query the PUSH interface, WAP PUSH interface. In addition to the WAP PUSH interface, the rest will be introduced one by one. The development of the color e interface is actually communication between SP and Unicom UNI-WISE platform, and UNI-WISE platform is working in a web mode, so most of the interaction of SP is transmitted through HTTP XML protocol. The author also used the partial interface code of C # written by C # during the development process. If there is this requirement, I will also organize the text.
Chapter 1 SSO Interface
SSO is the abbreviation of Single Sign on, that is, the functionality implemented in the E-interface, the user can access the relevant resources only in the UNI-WISE platform or SP platform to access the relevant resources. Implemented by cookies mechanism.
1.1. Transmission Safety
For safety reasons, the network's transmission often encrypts and encodes the transmission data, and a key point in the development of the color E interface is also written for encrypted code. It involves the following:
1, MD5 encryption, the encryption algorithm is unidirectional encryption, that is, the encrypted data cannot be redefined by decryption. Related classes are included in the java.security.MessageSt package.
2, 3-DES encryption, the encryption algorithm is reversible, and the decryption party can decrypt it by the redefined key. Related classes are included in the javax.crypto. * Packet.
3. Base64 encoding is the most commonly used encoding method for transmitting 8bit byte code. Related classes in Sun.Misc.Base64Decoder and Sun.Misc.Base64Encoder.
4, URLENCoder encoding, is a character encoding to ensure that the parameters transmitted are composed of text compliant. Related classes in the java.net.urlencoder package.
1.2. Generate a request ticket root
When the user initiates a login request from the SP platform, the SP platform needs to generate a legitimate ticket, transferred to the UNI-WISE platform in HTTP protocol. The rules that generate the request ticket root are: SPTICKETREQUESTVALUE = Urlencoding {Unicode (spcode "$") Base64 [Encrypt (unicode (SEED "$") Digest]}
1. Generate seed: returnURL "$" timestamp; returnurl receives UNI-WISE response ticket reel links after logging in. Timestamp is the generated timestamp.
Example 1.1. TimeStamp implementation code
Public string gettimestamp ()
{
Calendar Cal = Calendar.getInstance ();
SimpleDateFormat Formatter = New SimpleDateFormat ("YYYYMMDDHMMMS.SSS");
String timestamp = formatter.format (CAL.GETTIME ());
Return TimeStamp;
}
2, generate digest: base64 {hash [unicode (spcode " seed " spkey)]}, where the Hash algorithm uses MD5
Example 1.2. DiGest's implementation code
Public String getDigest (String strsrc)
{
// String strsrc = spcode "$" getseed () "$" spkey;
Base64encoder base64en = new base64encoder ();
String Digest = "";
Try
{
Byte [] srcmd5 = md5encrypt (strsrc);
Digest = Base64en.encode (srcmd5); (1)
}
Catch (Exception E) {
E.PrintStackTrace ();
}
Return Digest;
}
Private Byte [] MD5Encrypt (String strsrc)
{
Byte [] returnbyte = NULL;
Try
{
MessageDigest MD5 = MessageDigest.getInstance ("MD5"); (2)
ReturnByte = md5.digest (strsrc.getbytes ("GBK"));
}
Catch (Exception E)
{
E.PrintStackTrace ();
}
Return ReturnTe;
}
(1) Use base64 encoding (2) Specify the encryption method for MD5
3, generate a key, use the key provided by Unicom to make MD5 encryption.
Example 1.3. Get a 3-DES of the key
Private byte [] getenkey (String Spkey)
{
DESKEY = NULL;
Try
{
Byte [] deskey1 = md5encrypt (spkey);
Deskey = new byte [24];
INT i = 0;
While (i Deskey [i] = deskey1 [i]; i ; } IF (i <24) {(1) Deskey [i] = 0; i ; } } Catch (Exception E) { E.PrintStackTrace (); } Return deskey; } (1) According to the interface specification, the key key is 24 bytes, and the MD5 encrypted is 16 bytes, so the back of 8 bytes will be added. 4, generate SPTICKETREQUESTVALUE, URLENCoding {Unicode (spcode "$") base64 [encrypt (unicode (seed "$") Digest]}, Encrypt algorithm uses 3-DES encryption, using MD5 encrypted key . Example 1.4. 3-des encryption implementation code Public String GetSpticketRequestValue () { String SpticketRequestValue = "" Try { Byte [] SRC = (GetSeed () "$" getDigest ()) .getbytes ("UTF-16LE"); Byte [] enkey = getenkey (spKey); Byte [] encrypteddata = encrypt (src, enkey); (1) String base64encrypt = filter (base64en.encode (encryptedData)); (2) String RequestValue = SPCODE "$" Base64encrypt; SPTICKETREQUESTVALUE = Urlencoder.Encode (RequestValue); } Catch (Exception E) { E.PrintStackTrace (); } Return SpticketRequestValue; } Public Byte [] encrypt (byte [] src, byte [] enkey) { Byte [] encrypteddata = null; Try { DeSedeKeyspec DKS = New DeSedeKeyspec (Enkey); (3) SecretKeyFactory KeyFactory = SecretKeyFactory.GetInstance ("DESEDE"); (4) SecretKey Key = KeyFactory.GenerateSecret (DKS); (5) Cipher cipher = cipher.getinstance ("deside"); (6) Cipher.init (cipher.encrypt_mode, key); (7) EncryptedData = Cipher.dofinal (SRC); (8) } Catch (Exception E) { E.PrintStackTrace (); } Return EncryptedData; } Private string filter (String STR) { String Output = NULL; StringBuffer SB = new stringbuffer (); For (int i = 0; i { INT ASC = Str.Charat (i); IF (ASC! = 10 && ASC! = 13) Sb.append (Str.SubSequence (I, I 1)); } Output = new string (SB); Return Output; } (1) Call the encryption function of the 3-DES. (2) When Base64 encodes 3-DES data, the resulting string has a wrap symbol, which must be removed, otherwise the Uni-Wise platform resolution ticket will not succeed, prompt "SP verification failed". In the development process, because of this problem, I will tell me that a friend tells me Unicom to have an encrypted text, then compare the string that you generate, this is a good debugging method. I finally compared that I found a string of strings that I generated. I have written the ticket root request program with the C # language, and I didn't find this problem. (3) Create a DeSedeKeyspec object from the original key data. (4) Create a key factory and use it to convert Deskeyspec into a SecretKey object. (5) Get a key instance according to the key factory. (6) Create a Cipher object. (7) Initialize the Cipher object (with the key). (8) Perform an encryption operation. In order to facilitate debugging to give a dense string (compared to the results obtained after the same string of code encrypted and given) CONTENT = key = 1234; Result = base64 (3DES (ContentByte, Keybyte); Result: "25pxmw / / qkg2arqpldvqq ==" 1.3. Analytical response ticket roots The UNI-WISE platform receives the request ticket will make a resolution of the ticket, then the user logs in will put the login information in the response ticket root and passed back to the requested ticket. (The transmitted address is "returnurl" in the request ticket root). The transmitted protocol is also HTTP XML. 1. Urlencoding decoding (I found in the UNI-Wise test platform first required Urlencoding decoding for the resulting ticket response to the incoming ticket, which is also carried out in the UNI-Wise official platform, but the response ticket obtained under the UNI-Wise official platform It is already decoded to urlencoding). Import java.net.urdecoder; Urldecoder.Decode (strencoding); 2. Split the response to the inclusion string. The segmentation is very simple, with "$" as the split, get the string behind "$". 3. Perform Base64 decoding for the encrypted string. Import sun.misc.base64decoder; Base64decoder base64decode = new base64decoder (); Base64decode.Decodebuffer (strenbase64); 4. Perform 3-DES decryption for the base64 decoded (the key is equivalent to the encrypted key). Public String Decrypt (byte [] debase64) { String strde = NULL; Cipher cipher = null; Try { Cipher = Cipher.GetInstance ("DESEDE"); Byte [] Key = getenkey (spkey); (1) DeSedeKeyspec DKS = New DeSedeKeyspec (key); SecretKeyFactory KeyFactory = SecretKeyFactory.GetInstance ("DESEDE"); SecretKey Skey = KeyFactory.GenerateSecret (DKS); Cipher.init (Cipher.Decrypt_mode, SKEY); (2) Byte ciphertext [] = cipher.dofinal (debase64); strde = new string (ciphertext, "utf-16le"); } Catch (Exception EX) { StrDe = ""; EX.PrintStackTrace (); } Return strde; } (1) Get a key, please refer to the request ticket root section (2) encrypted, decrypt it, is actually specified Cipher.Encrypt_Mode or Cipher.Decrypt_Mode 5. Split the detailed string by "$", then obtain the corresponding information, such as MDN, UserID, etc. If the SP needs to record user information, it should be stored after parsing the ticket. The user information is then added to cookies according to actual needs. To implement SSO. Chapter 2 Book Interface 2. Issurate a scheduled request The user can initiate a predetermined request from the SP platform and the UNI-WISE platform. When the predetermined request is initiated from the SP, the SP platform needs to build the data of the predetermined request, and is transferred to UNI-Wise with HTPP protocol. There are two ways to request data. It is a service method, one is a product method. Construction request parameters according to the actual situation. HTTP: // URL? SPCode = a & servicecode = b & returnURL = C (Service mode) http: // Access platform URL? SPCode = a & productcode = b & returnURL = C (Product mode) 2.2. Resolution Uni-Wise Request All predetermined operations are linked to the UN-WISE predetermined platform, and then the user has a predetermined relationship, and UNI-WISE builds a predetermined information to notify the SP platform, determine whether the predetermined action is successful or not, according to the Response result of the SP. Uni-Wise to notify SPs for the predetermined information, so you need to know the SP receives a predetermined link, which is done when the application color e service. Example 2.1. Resolution Book Request InputStream SubscriptionRequestStream = Request.getInputStream (); (1) Prasexml (SubscriptionRequestStream); (2) (1) Uni-Wise will be predetermined to output to the SP platform with the output stream, and the SP gets the input stream with HTTPSERVLETREQUEST. (2) Parsexml is a function of parse XML. As in parsing normal XML, it is no longer described herein. 2.3. Verification request After obtaining the predetermined request information, the data should be verified, and the corresponding information is returned to the UNI-WISE platform based on the result of the verification. IF (mdn == null || mdn.trim (). Equals ("")) { ErrorCode = "16842754"; ErrorInfo = "Cannot Find MDN"; } IF (spcode == null || spcode.trim (). Equals ("")) { ErrorCode = "16973826"; Errorinfo = "Cannot Find Spcode"; } IF (ProductCode == Null || ProductCode.trim (). Equals ("")) { ErrorCode = "17104898"; ErrorInfo = "cannot find products"; IF (TransactionID == Null || TransactionId.trim (). Equals ("")) { ErrorCode = "17170434"; Errorinfo = "cannot find transactionid; } 2.4. Responding to the scheduled request After the SP receives the UNI-WISE predetermined request information, verify the check, then responds to the request, the transfer protocol is HTTP XML. UNI-Wise results in a predetermined action after receiving a response, returning to the user to book related information. The SP processing request results have two cases of success and failure. Example 2.2. Request successful response format StringBuffer SB = new stringbuffer (); Sb.append (" XML Version = /" 1.0 / "encoding = /" UTF-8 / "?> / n"); sb.append (" Sb.append (" Sb.append (" Sb.append (" Sb.append (" Sb.append (" Sb.append (" pResubscriptionNotify> / N"); Sb.append (" u-max>"); String strresponse = new string (SB); Example 2.3. Request failed response format StringBuffer SB = new stringbuffer (); Sb.append (" XML Version = /" 1.0 / "encoding = /" UTF-8 / "?> / n"); sb.append (" Sb.append (" Sb.append (" sb.append (geterRorcode ()); Sb.append (" validerRorcode>"); Sb.append (" sb.append (getRrorInfo ()); Sb.append (" ValidErrorInfo>"); Sb.append (" validerror> / n"); Sb.append (" u-max>"); String strresponse = new string (sb); Chapter 3, scheduled cancel interface 3.1. Initiate cancellation request The user can initiate a request from the SP platform and the UN-WISE platform. When the request is canceled from the SP, the SP platform needs to be built to cancel the request, transferred to UNI-WISE in HTPP protocol. Request data has two ways It is a Service method, one is a product approach. Rule consistent with a predetermined request. 3.2. Resolution Uni-Wise cancel request All cancellations are also oriented to the UNI-WISE platform, and then the user performs the cancel action, and UNI-WISE receives the cancellation of the SP platform after receiving the user cancel action. Depending on the SP response result, decide whether the cancel action is successful or not. The unpacking link of the SP is also completed when the application color e service is applied. The implementation code is consistent with the parsing scheduled request code, which is no longer repeated. 3.3. Verification request Please refer to the corresponding content of the scheduled request chapter. 3.4. Response request Example 3.1. Requests to handle successful responses StringBuffer SB = new stringbuffer (); Sb.append (" XML Version = /" 1.0 / "encoding = /" UTF-8 / "?> / n"); sb.append (" Sb.append (" Sb.append (" Sb.append (" Sb.append (" Sb.append (" Sb.append (" subscriptioncancel> / n"); Sb.append (" u-max>"); String strresponse = new string (SB); Example 3.2. Request processing failure response StringBuffer SB = new stringbuffer (); Sb.append (" XML Version = /" 1.0 / "encoding = /" UTF-8 / "?> / n"); sb.append (" Sb.append (" Sb.append (" sb.append (geterRorcode ()); Sb.append (" validerRorcode>"); Sb.append (" sb.append (getRrorInfo ()); Sb.append (" ValidErrorInfo>"); Sb.append (" validerror> / n"); sb.append (" u-max>"); String strresponse = new string (SB); Chapter 4 Web Push Interface Send a lottery E, first submit the PUSH interface of the UNI-WISE platform, and then then by UNI-WISE PUSH to the IMAP platform, as shown: Figure 4.1. 4.1. Submit Push The SP submission information to the UNI-WISE PUSH interface data division head and the encapsulation, where the body is transmitted in MIME format. 1. Build a header: SP corporate code (not encrypted) SP key (encryption) pay code (encryption) condition category (encryption) condition code (encryption) send mode (encryption) [Send start time (Encryption) deadline (encryption)] billing mobile phone number (encryption) border field in the MIME Body Boundary (Envelope) Import java.net.httpurlConnection; Import java.net.URL; Private URL URL = NULL; HTTPURLCONNECTION CONN = NULL; // build a URL long connection first Public Void ConnectURL (String Strurl) { Try { URL = New URL (Strurl); CONN = (httpurlconnection) URL.OpenConnection (); Conn.setRequestMethod ("POST"); } Catch (Exception EX) { } } // Set the header Public void setHeader () { Conn.setRequestProperty ("spcode", spcode; Conn.setHeader ("Encryptspkey", Enkey); Conn.setheader ("feecode", enfeecode; Conn.setheader ("ConditionType", EnconditionType; Conn.setheader ("Conditioncode", EnconditionCode; Conn.setheader ("SendType", EnsendType); Conn.setheader ("StartTime", EnStartTime); Conn.setHeader ("endtime", Enendtime; Conn.setHeader ("ThirdPartyPayphone", EnthirdPartyPhone; Conn.setheader ("Boundary", Enboundary; } In addition to the spcode does not need to encrypt, the balances are compliant with the Base64 (3DES (ContentBytePlus, Keybyte) encryption. Encrypting implementation code and consistency of the previous chapter description. 2, build the body MIME (Multipurpose Internet Mail Extensions, multi-purpose Internet mail extensions) is a specification that creates file format for email exchange, network document, and other applications on the enterprise network and the Internet. Example 4.1. Building a MIME format Private mimeMessage mime; / / Construct the Body of the MIME format Private void setmimeMimeMessage () { Try { Mime.SetFrom (New InternetDress (Strfrom)); (1) Mime.addrecipient (javax.mail.Message.RecipientType.to, New InternetDress (STRTO)); (2) Mime.setsubject (strsubject, "utf-8"); (3) Mime.setSentDate (New Date ()); Mime.setContent (GetmimeMultipart ()); } Catch (Exception EX) { } } Private mimemultipart getmimemimemultipart () { Mimemultipart mimemultipart = new mimemultipart (); MIMEBODYPART MIMEBODYPART = new mimebodypart (); Try { MIMEBODYPART.SETTEXT ((String) MIMEBODYTEXT.GET (i), "UTF-8"); (4) MimeMultipart.addbodypart (MIMEBODYPAR); Vector filepathes = getFilePaths (); For (int i = 0; i { String filepath = (string) Filepathes.get (i); Javax.Activation.DataSource DataSource = New FileDataSource (FilePath); MIMEBODYPART MIMEFILE = New MimeBodypart (); Mimefile.SetDataHandler (DataHandler (DataSource); MimeFile.setFileName ((New File (FilePath)). getName ()); MimeMultipart.addbodypart (mimefile); } } Catch (Exception E) { } Return MimeMultipart; } (1) Set the send address, display the sender on the phone to set the title value displayed on the mobile phone number (3) mobile phone number (3) to send to the phone, and pass the author test if the encoded is UTF-8, on the phone Show as garbled (test mobile phone icy), do not know if other mobile phones have this situation. (4) The text displayed on the phone, after the author test is not specified as UTF-8, the phone is displayed as garbled (test mobile phone Kyocera). 3, submit content to the PUSH interface Public void write (string body) { Java.io.outputStream outstream = conn.getOutputStream (); (1) DataoutputStream DataStream = New DataOutputStream (Outstream); DataOutstream.writebytes (body); DataOutstream.flush (); DataOutstream.close (); } (1) The CONN object here is a URLConnection object that references the example in the first step, which is already in the OPEN state. 4, read the PUSH response information Submission information and return information are real-time, so read operations should be implemented after commit. Public String Responsepush () { StringBuffer SB = NULL; Try { SB = New StringBuffer (""); BufferedReader Rd = New BufferedReader (CONN.GETInputStream ()); FOR (String line = null; (line = rd.readline ())! = null;) Sb.append (line); rd.close (); } Catch (Exception EX) { } Return New String (SB); } Responsepush () is a standard XML string. Please refer to the Interface Guide for format. The value of the Code node is 0 represents PUSH success.