Java (server side)-Integrated UnionPay payment, including code

Source: Internet
Author: User
Tags getmessage
Baidu UnionPay pay, basic in the spray UnionPay code rotten, or to take the official code posted up, are not careful to say the integration process, the use is not very much here to record my integration process, I hope to help everyone Official DemoIt is said that the UnionPay code has no specifications and the documents are rotten. But others very attentively, provided the demo, a little modification can be directly run. If you do not want to see this step, skip directly, but the demo still has to be downloaded ., we want to use the inside code demo download address: https://open.unionpay.com/ajweb/index, help center > Download > Gateway payment > Gateway Payment Leveling Technology Development PackageImport Eclipse, copy the certificate inside the src/assets/test environment certificate to E:/certs, (the latest version is 4 files, regardless of that version, the files are copied, and so will be modified on the line) modify Acp_ Sdk.properties, change the following to the address of the file just copied
Acpsdk.signcert.path=e:/certs/acp_test_sign.pfx
Acpsdk.encryptcert.path=e:/certs/acp_test_enc.cer
Acpsdk.middlecert.path=e:/certs/acp_test_middle.cer
Acpsdk.rootcert.path=e:/certs/acp_test_root.cer
Launch, publish to Tomcat, browser run LOCALHOST:8080/ACPSAMPLE_B2C initiate request, try more, be familiar with logic Start Integration Payment ProcessFront end request own server, own server request UnionPay, set the URL of a background notification, get the TN front end to take TN payment front-end payment completed, the Bank of the Federation tune you set the URL, and give you the corresponding parameters in the background according to the parameters of UnionPay, verify the signature, according to the corresponding business logic to judge add gold coins Copy the SDK package in the demo to your project

Config,unionpaycontroller,unionpayservice I wrote it myself, config is Com.unionpay.acp.demo under the Demobase get TN

The front end of the user ID, product ID passed over
Code as follows, to be modified where the TODO is written

' Public result GetOrder (Integer Pid,integer shopid) {//todo Do some of its own business logic pid,shopid according to Map<string, St
        Ring> contentdata=new hashmap<string, string> ();            Contentdata.put ("version", config.version);     Version number full channel default value contentdata.put ("encoding", config.encoding);                    Character set encoding can be used in UTF-8,GBK two ways contentdata.put ("Signmethod", "01");                       Signature method currently only supports 01:RSA Mode certificate encryption Contentdata.put ("Txntype", "01");                    Transaction type 01: Consumption Contentdata.put ("Txnsubtype", "01");                   Transaction Sub Class 01: Consumption Contentdata.put ("BizType", "000201");                   Fill in 000201 contentdata.put ("Channeltype", "08");                        Channel type 08 mobile phone Contentdata.put ("Merid", Merid);                     Merchant number, please change to the merchant number of your application or the 777 merchant number test contentdata.put ("AccessType", "0") registered on open;           Access type, the merchant access to fill 0, do not need to modify (0: Direct Lian merchant, 1: Receipt of a body 2: platform merchant) contentdata.put ("OrderId", orderId);         Merchant order number, 8-40 digit letter, cannot contain "-" or "_", can customize the rule contentdata.put ("Txntime", txntime);                       Order send time, take the system time, format for YYYYMMDDHHMMSS, must take the current time, otherwise will report txntime invalid Contentdata.put ("Acctype", "01");                      Account Type 01: Bank card 02: Passbook 03:ic Card Account type (Card medium) Contentdata.put ("Txnamt", Txnamt);                 The transaction amount unit is divided, cannot bring the decimal point contentdata.put ("CurrencyCode", "156");             Domestic merchants Fixed 156 RMB contentdata.put ("Backurl", Config.backurl);           TODO payment successful after the banking federation to tune this interface, it must be extranet interface map<string, string> reqdata = Acpservice.sign (contentdata,config.encoding);
        The value of the certid,signature in the message is obtained and automatically assigned in the SignData method, as long as the certificate is configured correctly.                      String Requestappurl = Sdkconfig.getconfig (). Getapprequesturl (); The transaction request URL reads the corresponding property file from the configuration file acp_sdk.properties acpsdk.backtransurl map<string, string> rspdata = Acpservice.post (reqdata,requestappurl,config.encoding); Send request message and accept synchronous Answer (default connection timeout time 30 seconds, read return result timeout time 30 seconds); After calling SignData, call SUbmiturl can not make any changes to the key value pairs in Submitfromdata, if the modification will cause the verification to not pass the String tn=null;//serial number if (!rspdata.isempty ()) {
                if (Acpservice.validate (Rspdata, config.encoding)) {logutil.writelog ("Verify signature succeeded");
                String Respcode = Rspdata.get ("Respcode");
                if (("a"). Equals (Respcode)) {tn = Rspdata.get ("TN"); }}else{//Does not return the correct HTTP status} if (tn==null) throw new Buzexceptio

        N (-1, "failed, please try again");
    Return to new result (200,TN);
 }
`
Front end take the TN payment, slightly the interface of the UnionPay callback

Reference Com.unionpay.acp.demo.BackRcvResponse here
here is the pit : UnionPay tune your interface, 1. Must be extranet, 2. If you return to the status code is 200, it does not continue to tune, if not 200, he will continue to tune your interface, which is where I have thrown anomalies, and some places to return directly to the reason

' @RequestMapping (value= "Backrcvresponse", method=requestmethod.post) public result Backrcvresponse ( HttpServletRequest req, httpservletresponse response) throws IOException {map<string, string> Map = Getallreque Stparam (req);//todo here are two methods, if one gets no value, please change to another if (! Acpservice.validate (Map, Map.get (sdkconstants.param_encoding)) {throw new Buzexception ( -2, "signature Verificatio
    n Failure ");
        else {String Respcode = map.get ("Respcode"); if (Respcode.equals ("00")) {//payment succeeded String ordersn = Map.get ("orderId");//OrderId string Qu you set when you request TN Eryid = Map.get ("Queryid"), or UnionPay gives you the unique identification//todo according to your business logic, the return to new result ("Success", Tokenpac 
        Kage.gettoken_count ());
        }else{throw new Buzexception ( -2, "Error-->respcode:" +respcode);
Return to new result (); Private map<string, string> Getallrequestparam (final httpservletrequest request) {map<string , String> res = new hashmap<string, string> ();
    enumeration<?> temp = Request.getparameternames ();
            if (null!= temp) {while (temp.hasmoreelements ()) {string en = (String) temp.nextelement ();
            String value = Request.getparameter (en);
            Res.put (en, value); if (Res.get (en) = = NULL | |
            '. Equals (Res.get (en))) {res.remove (en);
}} return res; Private map<string, string> Getallrequestparamstream (HttpServletRequest request) {map<string, String&gt ;
    res = new hashmap<string, string> (); try {string notifystr = new String (Ioutils.tobytearray (Request.getinputstream ()), Config.encodin
        g);
        string[] Kvs = Notifystr.split ("&");
            for (String Kv:kvs) {string[] tmp = kv.split ("=");
                if (tmp.length >= 2) {String key = tmp[0]; String value = Urldecoder.decode (TMP[1], config.encoding);
            Res.put (key, value); The catch (Unsupportedencodingexception e) {logutil.writelog ("Getallrequestparamstream.unsupportede
    Ncodingexception Error: "+ e.getclass () +": "+ e.getmessage ()); catch (IOException e) {logutil.writelog ("Getallrequestparamstream.ioexception error:" + e.getclass () + ":" + E
    . GetMessage ());
return res;
 }
`
because UnionPay is all over the map, when you want to use the output to see what parameters, here with the customer asked for a document, you can refer to see

http://download.csdn.net/download/gege87417376/10147779

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.