Alipay Login Interface Resolution

Source: Internet
Author: User
Tags auth gettext md5 stringbuffer

Yesterday looked at Alipay login interface code, feel that some things are still helpful to the development of the future. Here is a record of your feelings.

The first is to Alipaycore.java this class, which is a common function core processing file called by the request, notification return two files, and does not need to be modified. The main method is to splice the signature and request parameters:

/** * Generate Signature Results * @param sarray the array to be signed * @return Signature result string/public static string Buildmysign (Map<s
        Tring, string> sarray) {string prestr = createlinkstring (Sarray);//Put all elements of an array into strings using the "&" character in the mode "parameter = parameter value" Prestr = Prestr + Alipayconfig.key;
        The concatenation string is then connected directly with the security check code string mysign = Alipaymd5encrypt.md5 (PRESTR);
    return mysign; /** * Drop null values and signature parameters in array * @param sarray signature Parameter Group * @return new signature parameter group after null and signature parameters/public static MAP <string, string> parafilter (map<string, string> sarray) {map<string, string> result = new Hash

        Map<string, string> ();
        if (Sarray = null | | sarray.size () <= 0) {return result;
            For (String Key:sArray.keySet ()) {String value = Sarray.get (key); if (value = null | | value.equals ("") | | Key.equalsignorecase ("sign") | | Key.equalsignorecase ("Sign_type")) {COntinue;
        } result.put (key, value);
    return result;
     /** * Sort all elements of the array and concatenate them into strings with "&" characters according to the mode "parameter = parameter value" * @param params the parameter groups that need to sort and participate in character stitching * @return concatenation string */public static String createlinkstring (map<string, string> params) {list<string> keys = new
        Arraylist<string> (Params.keyset ());

        Collections.sort (keys);

        String prestr = "";
            for (int i = 0; i < keys.size (); i++) {String key = Keys.get (i);

            String value = Params.get (key);
            if (i = = Keys.size ()-1) {//stitching, excluding the last & character prestr = prestr + key + "=" + value;
            else {prestr = prestr + key + "=" + Value + "&";
    } return PRESTR; }
Alipayconfig.java This class is a basic configuration class that is used primarily to set account information and return paths:
↓↓↓↓↓↓↓↓↓↓ Please configure your basic information here ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
	//partner ID, with a string of 16-digit pure digits beginning with 2088 as public
	static string partner = "";
	
	Transaction security Inspection Code, consisting of numbers and letters of the 32-bit string public
	static string key = "";
	
	The page after the current page jump to use the full path of http://format, not allowed to add? id=123 such custom parameters
	//domain names cannot be written http://localhost/alipay.auth.authorize_jsp_utf8/ Return_url.jsp, otherwise it will cause Return_url to execute an invalid public
	static String Return_url = "http://127.0.0.1:8080/ Alipay.auth.authorize_jsp_utf8/return_url.jsp ";

	↑↑↑↑↑↑↑↑↑↑ Please configure your basic information here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
	

	//debug, create txt log path public
	static String Log_path = "D:\\alipay_log_" + System.currenttimemillis () + ". txt";

	The character encoding format currently supports GBK or utf-8 public
	static String Input_charset = "UTF-8";
	
	The signature method does not need to modify the public
	static String Sign_type = "MD5";
	
	Access mode, depending on whether your server supports SSL access, if supported please select HTTPS; Select HTTP public
	static String transport = "http" if not supported;
Alipaymd5encrypt.java This class is a tool class that encrypts signatures and does not need to be modified:
/**
     * MD5 Signature of String *
     * 
     @param text
     *            plaintext *
     * 
     @return ciphertext
     /public
    static string MD5 ( String text) {return

        Digestutils.md5hex (getcontentbytes (text, alipayconfig.input_charset));

    }

    /** *
     @param content
     * @param charset *
     @return
     * @throws signatureexception *
     @throws Unsupportedencodingexception 
     *
    /private static byte[] Getcontentbytes (string content, String charset) {
        if (charset = null | | "". Equals (CharSet)) {return
            content.getbytes ();
        }

        try {return
            content.getbytes (charset);
        } catch (Unsupportedencodingexception e) {
            throw new RuntimeException ("error occurred during MD5 signature, the specified encoding set is incorrect, the encoding set you are currently specifying is:" + charset);
        }
    
The next step is to Alipaynotify.java this class, which is mainly processing Alipay to return each interface notification:
/** * HTTPS Form message authentication address/private static final String Https_verify_url = "Https://www.alipay.com/cooperate/gate

    way.do?service=notify_verify& "; /** * HTTP Form message authentication address/private static final String Http_verify_url = "Http://notify.alipay.com/trade/notify_

    Query.do? "; /** * Verify that the message is a legitimate message from Alipay * @param params notification returns a parameter array * @return validation results/public static Boolean verify (
        Map<string, string> params) {String mysign = getmysign (params);
        String responsetxt = "true";
        if (Params.get ("notify_id")!= null) {responsetxt = Verifyresponse (Params.get ("notify_id"));
        String sign = "";

        if (Params.get ("sign")!= null) {sign = Params.get ("sign"); Write log records (to debug, please cancel the following two lines of comments)//string sword = "responsetxt=" + responsetxt + "\ n notify_url_log:sign=" + sign + "&m
        Ysign= "//+ MySign +" \ Notify back parameters: "+ alipaycore.createlinkstring (params);" Alipaycore.logresult (SWORD); Verify that the result of the//responsettxt is not true, with server Setup issues, Partner ID, notify_id one-minute failure related to//mysign and sign, and security checksum code, request parameter format (such as: with custom parameters, etc.),
        Encoding format for if (Mysign.equals (sign) && responsetxt.equals ("true") {return true;
        else {return false;  }/** * Based on feedback information, generate signature results * @param Params notification returned parameters array * @return generated signature results/private static String getmysign (map<string, string> Params) {map<string, string> sparanew = Alipaycore.parafilter (P
    Arams)//filter null value, sign and sign_type parameter String mysign = Alipaycore.buildmysign (sparanew);//Get signature result return mysign; /** * Get remote server ATN results, verify return URL * @param notify_id notification CHECKSUM ID * @return Server ATN results * Validate result set: * Invalid command Parameter does not appear this error, please detect partner and key in return processing NULL * True return correct information * False please check firewall or server block port problem and verify time is more than one minute/private stat IC string Verifyresponse (String notify_id) {//Get remote server ATN result, verify that the request was sent by the Alipay server StrinG transport = Alipayconfig.transport;
        String partner = Alipayconfig.partner;
        String Veryfy_url = "";
        if (transport.equalsignorecase ("https")) {veryfy_url = Https_verify_url;
        else {veryfy_url = Http_verify_url;

        } Veryfy_url = Veryfy_url + "partner=" + partner + "¬ify_id=" + notify_id;
    Return Checkurl (Veryfy_url); /** * Get remote server ATN result * @param urlvalue Specify URL path address * @return Server ATN results * Validate result set: * Invalid command parameter not present this  Error, please detect if partner and key are NULL * true in return processing return correct information * False check firewall or server block port issue and verify time for more than one minute * * private static String

        Checkurl (String urlvalue) {string inputline = "";
            try {URL url = new URL (urlvalue);
            HttpURLConnection URLConnection = (httpurlconnection) url.openconnection ();
            BufferedReader in = new BufferedReader (New InputStreamReader (URLConnection. getInputStream ())); Inputline = iN.readline (). toString ();
            catch (Exception e) {e.printstacktrace ();
        Inputline = "";
    return inputline; }
Here we need to make a Alipay access request, in the request process we have the request parameter array, the submitted form, with these conditions, we can simulate HTTP request to get the returned data. The code to generate the request parameter array is as follows:
/**
     * Generate an array of parameters to request to Alipay *
     @param an array of arguments before the sparatemp request
     * @return The parameter array to request/
    private static map< String, string> Buildrequestpara (map<string, string> sparatemp) {
        //drop null values and signature parameters in array
        map<string, string> Spara = Alipaycore.parafilter (sparatemp);
        Generate signature result
        String mysign = alipaycore.buildmysign (Spara);

        The signature result and signature method are included in the request submission parameter group
        spara.put ("sign", mysign);
        Spara.put ("Sign_type", alipayconfig.sign_type);

        return Spara;
    }
To construct a submit form code:
/** * Constructs submit form HTML data * @param sparatemp request parameter array * @param gateway gateway address * @param strmethod submission method. Two values optional: Post, Get * @param strbuttonname Confirm button Display text * @return Submit form HTML text */public static String Buildform (M Ap<string, string> sparatemp, String gateway, String strmethod, String strbuttonn
        AME) {//Pending request parameter array map<string, string> Spara = Buildrequestpara (sparatemp);

        list<string> keys = new arraylist<string> (Spara.keyset ());

        StringBuffer sbhtml = new StringBuffer (); Sbhtml.append ("<form id=\" alipaysubmit\ "name=\" alipaysubmit\ "action=\" "+ Gateway +" _input_cha

        Rset= "+ alipayconfig.input_charset +" \ "method=\" "+ strmethod +" \ ">");
            for (int i = 0; i < keys.size (); i++) {String name = (string) keys.get (i);

            String value = (string) spara.get (name); Sbhtml.append ("<inpUT type=\ "hidden\" "name=\" "+ name +" \ "value=\" "+ Value +" \ "/>"); //submit Button control Please do not include the Name property Sbhtml.append ("<input type=\" submit\ "value=\" "+ strbuttonname +" \ "style=
        \ "Display:none;\" ></form> ");

        Sbhtml.append ("<script>document.forms[' Alipaysubmit '].submit ();</script>");
    return sbhtml.tostring (); }
Constructs a POST request that simulates remote HTTP and gets the return XML processing result of Alipay:
public static String Sendpostinfo (map<string, string> sparatemp, String Gateway)
                                                                                    throws Exception {
        // To request an array
        of parameters map<string, string> Spara = Buildrequestpara (sparatemp);

        Httpprotocolhandler Httpprotocolhandler = Httpprotocolhandler.getinstance ();

        HttpRequest request = new HttpRequest (httpresulttype.bytes);
        Set the encoding set
        request.setcharset (alipayconfig.input_charset);

        Request.setparameters (Generatnamevaluepair (Spara));
        Request.seturl (gateway+ "_input_charset=" +alipayconfig.input_charset);

        HttpResponse response = Httpprotocolhandler.execute (request);
        if (response = = null) {return
            null;
        }
        
        String strresult = Response.getstringresult ();

        return strresult;
    }
Generatnamevaluepair Method:
/**
     * Map type array converted to Namevaluepair type
     * @param properties  Map Type array
     * @return Namevaluepair type array
    * * private static namevaluepair[] Generatnamevaluepair (map<string, string> properties) {
        namevaluepair[] Namevaluepair = new Namevaluepair[properties.size ()];
        int i = 0;
        For (map.entry<string, string> entry:properties.entrySet ()) {
            namevaluepair[i++] = new Namevaluepair ( Entry.getkey (), Entry.getvalue ());

        return namevaluepair;
    }
The next step is to look at the Httpprotocolhandler.java class, which is the core class for simulating HTTP requests, and the most important one is the Execute HTTP request method:
Public HttpResponse Execute (HttpRequest request) {httpclient httpclient = new HttpClient (ConnectionManager);
        Sets the connection timeout int connectiontimeout = defaultconnectiontimeout;
        if (request.getconnectiontimeout () > 0) {connectiontimeout = Request.getconnectiontimeout ();

        } httpclient.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (ConnectionTimeout);
        Set response Timeout int sotimeout = defaultsotimeout;
        if (request.gettimeout () > 0) {sotimeout = Request.gettimeout ();

        } httpclient.gethttpconnectionmanager (). Getparams (). Setsotimeout (SoTimeout); Sets the time to wait for ConnectionManager to release Connection Httpclient.getparams (). Setconnectionmanagertimeout (

        Defaulthttpconnectionmanagertimeout);
        String charset = Request.getcharset (); CharSet = CharSet = = null?
        Default_charset:charset;

        HttpMethod method = null; if (Request.getmethod (). Equals (HttpREquest.
            Method_get)) {method = new GetMethod (Request.geturl ());

            Method.getparams (). Setcredentialcharset (CharSet);
        Parsenotifyconfig will ensure that the Get method is used, the request must use QueryString Method.setquerystring (Request.getquerystring ());
            else {method = new Postmethod (Request.geturl ());
            ((Postmethod) method). AddParameters (Request.getparameters ()); Method.addrequestheader ("Content-type", "application/x-www-form-urlencoded; text/html;

        charset= "+ charset);
        //Set the User-agent attribute in the HTTP header method.addrequestheader ("User-agent", "mozilla/4.0");

        HttpResponse response = new HttpResponse ();
            try {Httpclient.executemethod (method); if (Request.getresulttype (). Equals (httpresulttype.string)) {Response.setstringresult (Method.getresponsebo
            Dyasstring ()); else if (Request.getresulttype (). Equals (Httpresulttype.bytes)) {Response.setbyteresult (Method.getresponsebody ());
        } response.setresponseheaders (Method.getresponseheaders ());
        catch (Unknownhostexception ex) {return null;
        catch (IOException ex) {return null;
        catch (Exception ex) {return null;
        finally {method.releaseconnection ();
    return response; }
Of course we need to create a thread-safe HTTP connection pool when new Httpprotocolhandler this class, and why thread safety is a good clue. Let's put this step into a proprietary construction method:
Private Httpprotocolhandler () {
        ConnectionManager = new Multithreadedhttpconnectionmanager ();
        Connectionmanager.getparams (). Setdefaultmaxconnectionsperhost (defaultmaxconnperhost);
        Connectionmanager.getparams (). Setmaxtotalconnections (defaultmaxtotalconn);

        Idleconnectiontimeoutthread ICT = new Idleconnectiontimeoutthread ();
        Ict.addconnectionmanager (ConnectionManager);
        Ict.setconnectiontimeout (defaultidleconntimeout);

        Ict.start ();
    }
The following methods are then used to enable other classes to obtain an instance object of the Httpprotocolhandler class using the getinstance () method and are thread-safe:
private static Httpprotocolhandler Httpprotocolhandler                 = new Httpprotocolhandler ();

    /**
     * Factory Method
     * 
     * @return
    /public static Httpprotocolhandler getinstance () {
        return Httpprotocolhandler;
    }
There are also properties in this class that set the timeout for HTTP connections, the number of connections, and so on:
private static String              default_charset                     = "GBK";

    /** connection Timeout, set by Bean Factory, defaults to 8 seconds *
    /private int                        defaultconnectiontimeout            = 8000;

    /** response Timeout, set by the Bean factory, defaults to 30 seconds *
    /private int                        defaultsotimeout                    = 30000;

    /** Idle connection timeout, set by Bean factory, defaults to 60 seconds *
    /private int                        defaultidleconntimeout              = 60000;

    private int                        Defaultmaxconnperhost               =;

    private int                        Defaultmaxtotalconn                 =;

    /** default wait Httpconnectionmanager return connection timeout (only when maximum number of connections is reached): 1 seconds/
    private static final long          Defaulthttpconnectionmanagertimeout = 3 * 1000;

    /**
     * HTTP Connection Manager, this connection manager must be thread safe. (How to set thread safety above already written)/
    private Httpconnectionmanager      ConnectionManager;
There are also two classes in this class, HttpClient and HttpResponse, which are primarily the encapsulation of HTTP requests and the corresponding messages that return HTTP. These two classes do not say here, is two Pojo class, httpclient inside encapsulates the request required attributes such as Character set, request method, timeout time, HttpResponse inside is the response header and the return structure of the package. The last one is Alipay each interface constructs class Alipayservice.java,
/** * Alipay provided to the Merchant Service Access Gateway URL (new) * * private static final String alipay_gateway_new = "Https://mapi.alipay.com/gat

    Eway.do? "; /** * Construction Quick Login Interface * @param sparatemp Request Parameters Collection * @return form submission HTML information/public static String Alipay_auth_ 
        Authorize (map<string, string> sparatemp) {//Add basic Configuration Sparatemp.put ("service", "alipay.auth.authorize");
        Sparatemp.put ("Target_service", "User.auth.quick.login");
        Sparatemp.put ("partner", Alipayconfig.partner);
        Sparatemp.put ("Return_url", Alipayconfig.return_url);

        Sparatemp.put ("_input_charset", Alipayconfig.input_charset);

        String Strbuttonname = "Confirmation";
    Return Alipaysubmit.buildform (Sparatemp, Alipay_gateway_new, "get", strbuttonname); /** * Used to prevent fishing, call interface Query_timestamp to get timestamp processing function * Note: Remote parse XML error, and server support SSL configuration related * @return Timestamp string * Throws IOException * @throws documentexception * @throws malformedurlexception/Public Static String Query_timestamp () throws Malformedurlexception, Doc Umentexception, IOException {//construct URL string string for accessing Query_timestamp interface = Alipay_gateway_new + "service=
        Query_timestamp&partner= "+ Alipayconfig.partner;

        StringBuffer result = new StringBuffer ();
        Saxreader reader = new Saxreader ();

        Document doc = Reader.read (new URL (strURL). OpenStream ());

        List<node> nodelist = doc.selectnodes ("//alipay/*"); for (Node node:nodelist) {//intercepted information that does not need to be parsed if (Node.getname (). Equals ("is_success") && No De.gettext (). Equals ("T")) {//Determine if there is a success mark list<node> nodeList1 = Doc.selectnodes ("//r
                esponse/timestamp/* ");
                for (Node node1:nodelist1) {result.append (Node1.gettext ());
    }} return result.tostring (); }
Here Alipay's login interface is basically over, not very detailed, the specific process and code here to download: http://download.csdn.net/detail/uohzoaix/4009777. Well, dinner's gone.














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.