Java Implementation Online Payment

Source: Internet
Author: User
Tags md5 stringbuffer
The basic flow of the domestic e-commerce system is as follows:
Customer orders-> system within the system according to the order generated Alipay interface URL-> customer through the URL to use Alipay (Online banking) payment-> Alipay will customer payment completion information sent to the e-commerce system-> System received Alipay information to determine customer orders have been paid- > Follow up the shipping process.

Before you start the following, you have to have a Alipay account, if you want to integrate Alipay interface, you must also apply for open service (on how to open, you can directly to the Alipay website application). After the service is opened, Alipay will give you 2 string number: 1 Partnerid (partner ID), There are also 1 Securitycode (security codes). When you get these 2 yards, you can start with the following.
(1) How to invoke the Alipay interface. (The customer's order information in accordance with established rules to generate a URL to jump to the Alipay site)

Get the Alipay URL by invoking the following method [Makeorderalipayurl (HttpServletRequest httprequest,order Order)], and then jump (Response.sendredirect ( URL);).

/** * Generate Alipay interface URL based on order. * @param HttpRequest * @param Order instance * @return * @throws Exception/Pub Lic static String Makeorderalipayurl (HttpServletRequest httprequest,order order) throws Exception {HashMap      
        HM = new HashMap (); Hm.put ("_input_charset", httprequest.getcharacterencoding ());//Use the same encoding method Hm.put ("Body", "your order on the www.xxx.com"); /Fill out the payment information displayed on the Hm.put page ("Discount", "5"), and/or fill in the discount information-5 for the deduction of 5 Yuan Hm.put ("Logistics_fee", "10"); /Logistics Cost Hm.put ("Logistics_payment", "Buyer_pay");/logistics cost payer buyer_pay= buyer pays logistics fee hm.put ("logistics_t      
        Ype "," EXPRESS ");//Logistics Way Hm.put (" Notify_url "," http://www.xxx.com/notifyurl.jsp ");//customer payment, Alipay call page      
        Hm.put ("Out_trade_no", Order.getid ());//external transaction number, preferably unique, used when obtaining payment information from Alipay. Hm.put ("partner", Partnerid);//partnerid (partner ID) hm.put ("Agent", Partnerid);//partnerid (partner ID)      
        Hm.put ("Payment_type", "1");/Payment Type 1 = commodity purchase, 2 = Service purchase,... hm.put ("Price", "105.30");//Order Amount Information Hm.put ("Quantity", "1");//Order merchandise quantity, is generally written 1, it is according to the entire order package to calculate Hm.put ("Return_url", "Http://www.xxx.com/ReturnUrl . JSP ")//customer after successful payment, display to the Customer page hm.put (" Seller_email "," alipay@xxx.com ");//Your Alipay account email hm.put (" Servi Ce "," create_direct_pay_by_user ");//create_direct_pay_by_user= direct payment, Trade_create_by_buyer guaranteed payment hm.put (" Subjec T "," www.xxx.com Order ")//fill in the Payment header information displayed on the Skip to Alipay page String paygateway =" https://www.alipay.com/cooperate/gateway.do ?";/ /jump to Alipay URL header return Makeurl (Hm,securitycode,httprequest.getcharacterencoding (), paygateway);//securitycode (safe     
     Code)}/** * generates Alipay payment URL based on incoming parameters * @param HM parameter value * @param securitycode Security Code * @param CharSet Code * @param paygateway Payment PO Gateway * @return * * Public Stati C String Makeurl (hasHmap hm,string securitycode,string charset,string paygateway) throws exception{List keys = new ArrayList (HM      
        . Keyset ());      
        Collections.sort (keys);//Alipay request parameters must be sorted alphabetically stringbuffer content = new StringBuffer ();      
            for (int i = 0; i < keys.size (); i++) {Content.append ((String) keys.get (i));      
            Content.append ("=");      
            Content.append ((String) hm.get ((String) keys.get (i)));      
            if (I!= keys.size ()-1) {Content.append ("&");      
        } content.append (Securitycode);      
        String sign = MD5 (content.tostring (), CharSet);      
        Content.delete (0,content.length ());      
        Content.append (Paygateway);      
            for (int i = 0; i < keys.size (); i++) {Content.append (Keys.get (i));      
            Content.append ("="); Content.append (Urlencoder.encode ((String) HM.get (Keys.get (i)), CharSet));      
        Content.append ("&");      
        } content.append ("&sign_type=md5");      
        Keys.clear ();      
        keys = null;      
    return content.tostring ();    
     /** * Generates a MD5 encoded string. * @param str Source String * @param charset encoding * @return * */public static string m      
        D5 (String str,string charset) {if (str = null) return null; Char hexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F '      
        };      
        MessageDigest md5messagedigest = null;      
        byte[] md5bytes = null;      
        char md5chars[] = null;      
        byte[] strbytes = null;      
            try {strbytes = Str.getbytes (charset);      
            Md5messagedigest = Messagedigest.getinstance ("MD5"); Md5messagedigest.updaTe (strbytes);      
            Md5bytes = Md5messagedigest.digest ();      
            int j = Md5bytes.length;      
            Md5chars = new CHAR[J * 2];      
            int k = 0;      
                for (int i = 0; i < J; i++) {byte md5byte = md5bytes;      
                md5chars[k++] = hexdigits[md5byte >>> 4 & 0xf];      
            md5chars[k++] = hexdigits[md5byte & 0xf];      
        Return to New String (Md5chars);      
            catch (NoSuchAlgorithmException e) {//log.output (e.tostring (), log.std_err);      
        return null;      
            catch (Unsupportedencodingexception e) {//log.output (e.tostring (), log.std_err);      
        return null;      
            finally {md5messagedigest = null;      
            Strbytes = null;      
        Md5bytes = null;   }      
    }

After the customer has paid through the interface URL, Alipay will automatically invoke the URL in the [Notify_url] parameter provided above.

(2) Alipay will return payment information to the system
When the customer pays, Alipay automatically invokes [Notify_url] provided in the above form, and below is an example of [notifyurl.jsp]:

<%@ page contenttype= "text/html;charset=utf-8"%><%@ page import= "com.soft4j.AlipayMgr"%><%      
    String ret = Alipaymgr.insert (request);      
    if (ret==null) {      
        out.print ("Success");//successfully receive payment information from Alipay      
    }else{      
        out.print ("fail");//Error      
    }      
%>

If you confirm receipt of payment PO sent customer payment information, then return to "success", such as Alipay will know that the system has received information, otherwise return to "fail", so Alipay will be sent after a period of time. In fact, only when Alipay received "success" return information will stop sending payment information, otherwise it will automatically be called every time on the above
[Notify_url] Communication interface.

(3) System processing payment information sent by Alipay
* * Created on 2005-6-12 * Author Stephen * Email zhoujianqiang at gmail DOT com * CopyRight (C) 2005-2    
 008, All rights reserved.      
* * Package com.soft4j;      
Import java.sql.Connection;      
Import java.sql.SQLException;      
Import java.util.Enumeration;      
Import Java.util.Vector;      
Import Javax.servlet.http.HttpServletRequest;    
 /** * Alipay Payment notification interface. * @author Stephen * @version 1.0.0 * * Public final class Notifyurlmgr {public static Str ing insert (httpservletrequest httprequest) {//define variable and perform necessary initialization work enumeration Parameternames = Nu      
        ll      
        String parametername = null;      
        String parametervalue = null;      
        int count = 0;      
        vector[] params = null;      
        Vector vparametername = new vector ();      
        Vector vparametervalue = new vector (); try {String orderId = Httprequest.getparameter ("Out_tradE_no ");//order number if (orderid==null| |" ".      
            Equals (orderId)) orderid= "-1";      
            Parameternames = Httprequest.getparameternames ();      
            Boolean isprint = false; while (Parameternames.hasmoreelements ()) {//loop collects all parameter information sent by Alipay parametername = (String) parameternames      
                . Nextelement ();      
                ParameterValue = Httprequest.getparameter (parametername);      
                if (parametervalue==null) parametervalue= "";      
                Vparametername.add (parametername);      
                Vparametervalue.add (ParameterValue);      
            count++;      
            ///Add the processing of received information here: Typically, this information is stored in the database and then processed by the customer's order.      
        return null;      
        catch (Exception e) {return e.tostring ();  } finally {}}}



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.