Silver Networking off Payment, refund Java implementation

Source: Internet
Author: User
Tags findone html form prepare response code
    It lasted two weeks and finally paid the refund for the UnionPay. Because no one to guide, went a lot of detours, bloggers here posted the relevant code, hoping to help like me, no one to guide the small partners.
Pay for UnionPay 1: Payment, refund process.


2: Pay the relevant preparation to the official website to download the SDK, the official website related address will be at the end of this article to provide download the official website of the test configuration file acp_sdk.properties, test related certificates Acp_test_enc.cer,acp_test_ SIGN.PFX, modify acp_sdk.properties after placed under Classpath, if you want to use production environment, the relevant certificate file has four, the configuration file also has corresponding production environment certificate. If the payment is successful after the jump page, you need to prepare the relevant page, if the Java code concatenation string, you need to prepare the relevant Java class, used to dynamically produce HTML pages. 3: Payment, refund related code

1: Code structure

2:autoloadservlet

Import Com.kemile.common.pay.chinapay.sdk.SDKConfig;

Import Javax.servlet.ServletConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;


/**
 * Function: Loads the Acp_sdk.properties property file from the applied classpath and assigns the key value pairs in the property file to the Sdkconfig class <br>
 * * * 
 public
Class Autoloadservlet extends HttpServlet {

    @Override public
    void init (ServletConfig config) throws servletexception {

        sdkconfig.getconfig (). LOADPROPERTIESFROMSRC ();

        Super.init ();
    }

3:charsetencodingfilter

Import Com.kemile.common.pay.chinapay.config.ChinapayConfig;

Import java.io.IOException;

Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;



public class Charsetencodingfilter implements Filter {

    @Override public
    Void Destroy () {
    }

    @Override Public
    void Dofilter (ServletRequest request, servletresponse response,
            Filterchain chain) throws IOException, servletexception {

        request.setcharacterencoding (Chinapayconfig.encoding_utf8);
        Response.setcontenttype ("text/html; charset= "+ Chinapayconfig.encoding_utf8);
        Chain.dofilter (request, response);

    @Override public
    void init (Filterconfig filterconfig) throws servletexception {
    }

}

4:chinapayconfig

import java.text.SimpleDateFormat; import java.util.Date;
    public class Chinapayconfig {//Merchant number//public static String Merid = "777290058137116";//fill in your own website related merchant number//foreground request address
    public static String Fronturl = "Fontrev";
    Background request address public static String Backurl = "Backrev";

    The default configuration is UTF-8 public static String Encoding_utf8 = "UTF-8";

    public static String ENCODING_GBK = "GBK";

    Full channel fixed value public static String Version = "5.0.0"; Merchant Send Transaction time format: Yyyymmddhhmmss public static String GetCurrentTime () {return new SimpleDateFormat ("YYYYMMDDHHM
    MSS "). Format (new Date ()); }//AN8 ... 40 Merchant Order number, cannot contain "-" or "_" public static String Getorderid () {return new SimpleDateFormat ("YYYYMMDDHHMMSS"). Format (n
    EW Date ()); /** Merchants Bank Debit card: 6226090000000048 mobile Phone No: 18100000000 password: 111101 SMS Authentication code: 123456 (MOBILE)/111111 (PC) (click to obtain the verification code before entering Certificate type: 01 ID Number: 510265790128303 name: John */} 

5:cychinapaycontroller

@Controller @RequestMapping (value = "/cychinapay") public class Cychinapaycontroller {Logger Logger = Logger.getlogge

    R (Alipaycontroller.class); @Autowired Private Imobilecydishorderservice mobilecydishorderservice;//inject service @Autowired private Imobilese

    Rvicestyleservice Mobileservicestyleservice;  Payment @RequestMapping ("/{ORDER_NBR}") Public String Pay (@PathVariable string order_nbr, HttpServletRequest request, HttpServletResponse response) {String basepath = request.getscheme () + "://" + request.getservername () + ":" +

        Request.getserverport ();
        Cydishorderentity order = (cydishorderentity) mobilecydishorderservice.findone ("Ordernum", ORDER_NBR);
        map<string, string> requestdata = new hashmap<string, string> ();              Requestdata.put ("version", chinapayconfig.version);              Version number, full channel default value requestdata.put ("encoding", Chinapayconfig.encoding_utf8); Character set encoding, you can use the UTF-8,GBK two ways REQUESTDAta.put ("Signmethod", "01");                          Signature method, only supports 01:RSA Mode certificate encryption Requestdata.put ("Txntype", "01");                          Transaction type, 01: Consumption Requestdata.put ("Txnsubtype", "01");                      Transaction subtype, 01: Self-Service Consumption Requestdata.put ("BizType", "000201");                      Business type, Business-to-consumer Gateway payment, Mobile WAP payment requestdata.put ("Channeltype", "08"); Channel type, this field distinguishes between the Business-to-consumer gateway payment and the mobile WAP payment; 07:PC, flat 08: Mobile/*** Merchant Access Parameters ***/Requestdata.put ("Merid", Chinapayconfig.merid)                  ;                          Merchant number, please change to your own application of the official merchant number or open on the registered 777 test merchant number Requestdata.put ("AccessType", "0");             Access type, 0: Direct even merchant requestdata.put ("OrderId", ORDER_NBR);        Merchant order number, 8-40 digit letter, cannot contain "-" or "_", can customize the rule requestdata.put ("Txntime", Chinapayconfig.getcurrenttime ());                      Order send time, take the system time, format for YYYYMMDDHHMMSS, must take the current time, otherwise will report txntime invalid Requestdata.put ("CurrencyCode", "156"); Trading currency (domestic merchant is generally 156 RMB) bigdEcimal totprice = null; ========== price calculation ========= totprice = new BigDecimal (Order.getpaymoney ());//Query Price Requestdata.put ("Txnamt", String.valueof ((totprice.multiply (new BigDecimal)). Longvalue ()); Transaction amount, per unit, do not bring decimal point try {//===============================//:todo://===== ======================== requestdata.put ("Fronturl", BasePath + "/cychinapay/" + chinapayconfig.fronturl);  Front Request Address Requestdata.put ("Backurl", BasePath + "/cychinapay/" + chinapayconfig.backurl);
            Background request address Logger.info ("callback Address" +basepath + "/cychinapay/" + chinapayconfig.fronturl);
            Logger.info ("Callback Address" +basepath + "/cychinapay/" + chinapayconfig.backurl); map<string, string> submitfromdata = Acpservice.sign (RequestData, Chinapayconfig.encoding_utf8);  Signature String Requestfronturl = Sdkconfig.getconfig (). Getfrontrequesturl (); Get the front address of the request UnionPay: Acpsdk.fro in the corresponding attribute file Acp_sdk.properties fileNttransurl String html = acpservice.createautoformhtml (Requestfronturl, Submitfromdata, Chinapayconfig.encodin   G_UTF8); Generate an HTML form for an auto jump//write the generated HTML to the browser to complete the automatic jump open the UnionPay payment page; After you call SignData, you cannot change the name and value of the table item in HTML until you have written the HTML to the browser, and if the modification will lead
        The verification signature does not pass Response.getwriter (). write (HTML);
        catch (Exception e) {e.printstacktrace ();
    return null; private static map<string, string> Validedata (httpservletrequest req, HttpServletResponse resp) throws Ioexce
        ption {String encoding = Req.getparameter (sdkconstants.param_encoding);
        Get UnionPay Notification server sent background notification parameters map<string, string> reqparam = Getallrequestparam (req);
        map<string, string> validedata = null; if (null!= reqparam &&!reqparam.isempty ()) {iterator<map.entry<string, string>> it = re
            Qparam.entryset (). iterator (); Validedata = new hashmap<string, string> (Reqparam.size ());
            while (It.hasnext ()) {map.entry<string, string> e = It.next ();
                String key = (string) e.getkey ();
                String value = (string) e.getvalue ();
                Value = new String (value.getbytes (encoding), encoding);
            Validedata.put (key, value);
    } return validedata; }//Background request address @RequestMapping (value = "/backrev") public void Backrcv (HttpServletRequest req, httpservletrespons
        E resp) throws Servletexception, IOException {//map<string,string> map=getallrequestparam (request);
        Logger.info ("[Enter UnionPay payment callback method]");
        String encoding = Req.getparameter (sdkconstants.param_encoding);
        Get UnionPay Notification server sent background notification parameters map<string, string> reqparam = Getallrequestparam (req);
        Logutil.printrequestlog (Reqparam);
        map<string, string> validedata = Validedata (req, resp);
        PrintWriter out = null; out = Resp.getwriter (); Important. Do not modify the contents of the key value pairs in the Reqparam before verifying the signature, otherwise it will be checked if (!
            Acpservice.validate (Validedata, encoding)) {logger.info ("Validate signature result [failed].");
        Out.write (cyreturnpayendhtml.failedhtml (Validedata.get ("OrderId"), "Verify signature Failed", Const.validatefaliurl));
            else {logger.info ("Validate signature result [success].");
            "Note: The success of the security verification should be written to the merchant's successful processing logic" successful transaction, update merchant order status String Respcode = Validedata.get ("Respcode"); if (the ". equals" (Respcode)) {//UnionPay returns 00 for successful//:todo: This method automatically backs up the UnionPay after the user pays success. Here you can write the business logic of the successful order payment if (after the order payment succeeds) {Resp.getwriter (). Print ("OK");
                Otherwise, the banking association does not think that the callback information is received by the merchant backstage.
    }} logutil.writelog ("Backrcvresponse Receive background notification end"); //Front Request Address @RequestMapping ("/fontrev") public void Fontrev (HttpServletRequest request, HttpServletResponse re
        Sponse) throws Servletexception, IOException {response.setcharacterencoding ("utf-8"); Response.setcontenTtype ("text/html;
        Charset=utf-8 ");/set encoding printwriter out = null;
        out = Response.getwriter ()//Get response output stream Logger.info ("Frontrcvresponse Reception message return start");
        String encoding = Request.getparameter (sdkconstants.param_encoding);
        Logger.info ("encoding=[" + Encoding + "]" in the return message); map<string, string> Respparam = Getallrequestparam (request);//Get the parameters of UnionPay callback//Print request message Logutil.printreque

        Stlog (Respparam); map<string, string> validedata = validedata (request, response);//Verify signature if (! Acpservice.validate (Validedata, encoding)) {//Verify signature failed Logger.info ("Validate signature result [failed].");//Return "Redirec
            T:/pay-failed.html ";
        Out.write (cyreturnpayendhtml.failedhtml (Validedata.get ("OrderId"), "Verify signature Failed", Const.validatefaliurl)); else {String Respcode = validedata.get ("Respcode"),//If the validation succeeds, get the UnionPay response code if (". equals" (Respcode)) {/
                /Response Code of 00 indicates successful payment.
     Logger.info ("Validate signature result [success]");           =====================//todo: This method after the user pays success clicks returns the Merchant, the UnionPay callback, here writes the callback success after some business logic. else {out.write cyreturnpayendhtml.failedhtml (validedata.get ("OrderId"), "UnionPay payment failed", Const.validatefaliur
            L));
        } out.flush ();
    Out.close ();
     /** * Update order data (status) This method is written according to its business requirements, and finally returns the order number after the verification signature.

        * * @param validedata * @return/private String UpdateOrder (map<string, string> validedata) { Return Validedata.get ("orderId")//returns the order number after the successful verification of the signature}//Refund @ResponseBody @RequestMapping ("/refund/{
            ORDER_NBR} ") public string DoPost (@PathVariable string Order_nbr, HttpServletRequest req, HttpServletResponse resp)  Throws Servletexception, IOException {String basepath = req.getscheme () + "://" + req.getservername () +
        ":" + req.getserverport ();
Cydishorderentity order = (cydishorderentity) mobilecydishorderservice.findone ("Ordernum", ORDER_NBR);
        map<string, string> data = new hashmap<string, string> ();               /*** UnionPay full channel system, product parameters, in addition to encoding their own choice other than the need to modify ***/data.put ("version", chinapayconfig.version);             Version number Data.put ("Encoding", Chinapayconfig.encoding_utf8);                        Character set encoding can be used in UTF-8,GBK two ways data.put ("Signmethod", "01");                           Signature method currently only supports 01-RSA Mode certificate encryption Data.put ("Txntype", "04");                        Transaction type 04-Return Data.put ("Txnsubtype", "00");                       Transaction subtype Default Data.put ("BizType", "000201");                       The business type of the Business-to-consumer gateway payment, Mobile WAP payment data.put ("Channeltype", "07");                Channel type, 07-pc,08-mobile phone/*** merchant Access Parameters ***//*chinapayconfig.merid*/data.put ("Merid", Chinapayconfig.merid);                         Merchant number, please change to the merchant number of your application or the 777 merchant number test data.put ("AccessType", "0") registered on open; Access type, merchant access fixed fill 0, no need to modify data
Related Article

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.