SSH Framework Online Mall Project 21st War Details CHEIPAO payment process _java

Source: Internet
Author: User
Tags hmac md5 ssh stringbuffer

This section we first write a simple point of the demo to test Yeepay payment process, familiar with this process, and then do the actual development, because it is a demo, so I did not consider some design patterns of things, is directly to achieve the payment function. The implementation of the payment function requires the API provided by the easy treasure. So the problem is, the main thing to use a Third-party payment platform is to get the API for the platform, we first have to get their APIs and develop documents before we can do further development.

1. Get the easy to treasure API

Get the first step of the API, to register an account on the easy treasure, this account is the account of the merchant, after the buyer payment, will be deposited into the account, and then the merchant himself extracted to the bank card, yeepay in the extraction process charge a certain fee. This is the profit model of Yi Bao. But registration success requires a prerequisite, that is, you have to have a website, or a company, it is a bar, and so on, anyway, you have to qualify for the application, this is easy to audit, satisfied will allow you to register, will give you their interface, not everyone can register. I use other people to register well, I have nothing ... Can not register ... Dick Silk One, we understand ~ but generally in the development of the company, there will be no such problem, the account must be certain, the most important thing is to master the development process and related technology ~

2. Test payment Process

With the official API and technical documents, you can start to develop, where the main writing a simple demo to test the Yeepay payment process, demo's structure is very simple, a servlet, a filter, two JSP pages and a cryptographic tool class. Servlet and easy to deal with the server side, we do some with the Yeepay interface-related processing, filter is used to deal with possible Chinese garbled problem, two JSP in one is the front page.
Let's first analyze the process of payment requests, as follows:

OK, here's a detailed analysis of the relevant code in the demo:

2.1 Front Desk test page

First look at the front page index.jsp specific code

<%@ page language= "java" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

From the above JSP page can be seen, these input tags in the Name property values are very strange, pi_ function (i=0,1,2,..., 9), of course I have other values, this has to refer to the official documents of the PO, these name represents the corresponding attributes, will be passed to Sevlet processing, For these property values, I truncated a graph, as follows:


  

Some of these parameter names are in the foreground in the actual project, for example, the above written order number, how much to pay, these in order to confirm the time will bring the past, then other parameters, must be filled out, need to specify in the servlet, not required fields, it can be empty, where the empty is not NULL, but "", Mentioned in the following servlet.
The value of the corresponding value in the two banks is also fixed, and the value of all the banks that it supports is fixed and cannot be modified. Here, write two banks to test the effect.
The last hidden field is used to make judgments in the servlet, whether to pay or to return after successful payment, as explained in Sevlet below.

2.2 Servlet processing Requests

servlet main processing and Yeepay related requests, there are two parts of the content, part of the Yeepay to send clear text and ciphertext, the other part is to judge Yeepay sent over the plaintext and ciphertext, we look at the demo of the specific implementation code:

public class Payservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse respons
    E) throws Servletexception, IOException {String status = Request.getparameter ("status"); if (Status.equals ("pay")) {The hidden field in//index.jsp is pay, so processing the payment of this part//encryption key, used in cryptographic algorithms, provided by the payment intermediary, each merchant's unique String keyval
      UE = "w0p75wmz203fr46r5i70v556whfa94j14yw5j6vuh4yo3nrl5jsqf3c41677";
      1: Assign values to the parameters, these parameters (that is, clear text) are the official documents available in the definition, the name we can not change the String p0_cmd = formatstring ("buy");
      String P1_merid = formatstring ("10000940764");
      String P2_order = formatstring (Request.getparameter ("P2_order"));
      String P3_amt = formatstring (Request.getparameter ("P3_amt"));
      String p4_cur = formatstring ("CNY");
      String p5_pid = "";
      String p6_pcat = "";
      String P7_pdesc = "";
      String P8_url = "http://www.tongji.edu.cn";//This is paid after the successful jump to the page, you can set for the mall home page, this demo on the home page with Tongji University ...
      String P9_saf = "0";
      String pa_mp = ""; String pd_frpid = foRmatstring (Request.getparameter ("Pd_frpid"));
      Pd_frpid = Pd_frpid.touppercase ();

      String Pr_needresponse = "0"; String HMAC = formatstring ("");//hmac is used to store redaction/* All of the plaintext on the above is wrapped with the FormatString method, which, in the following, mainly converts null to "" * because NULL is None Cheng Mi-wen//Resolution of the data security problem: The plaintext encryption---> ciphertext and then the clear text and ciphertext to Yeepay//Yeepay to get the data, the passing of the plaintext encryption, and pass over the ciphertext comparison,//If the equality of data has not been tampered with (
      The merchant and the easy treasure encrypt when all uses the same key)//The clear text data appends to the StringBuffer, note that the append order can not be changed, otherwise the generated ciphertext will be different,//to be strictly in accordance with the official documents of Yeepay to write the line, because the Yi Bao that is in accordance with the order of the document appended
      StringBuffer InfoBuffer = new StringBuffer ();
      Infobuffer.append (P0_cmd);
      Infobuffer.append (P1_merid);
      Infobuffer.append (P2_order);
      Infobuffer.append (P3_amt);
      Infobuffer.append (p4_cur);
      Infobuffer.append (P5_PID);
      Infobuffer.append (P6_PCAT);
      Infobuffer.append (P7_PDESC);
      Infobuffer.append (P8_url);
      Infobuffer.append (P9_SAF);
      Infobuffer.append (PA_MP);
      Infobuffer.append (PD_FRPID);
      Infobuffer.append (Pr_needresponse); //encrypted ciphertext is stored in HMAC, encryption algorithm is easy to provide, because he also has to use the same algorithm HMAC = Digestutil.hmacsign (infobuffer.tostring (), keyvalue);
      The plaintext and ciphertext are stored in the Request.setattribute request.setattribute ("P0_cmd", p0_cmd);
      Request.setattribute ("P1_merid", P1_merid);
      Request.setattribute ("P2_order", P2_order);
      Request.setattribute ("P3_amt", P3_amt);
      Request.setattribute ("P4_cur", p4_cur);
      Request.setattribute ("P5_pid", p5_pid);
      Request.setattribute ("P6_pcat", P6_pcat);
      Request.setattribute ("P7_pdesc", P7_pdesc);
      Request.setattribute ("P8_url", P8_url);
      Request.setattribute ("P9_saf", P9_SAF);
      Request.setattribute ("Pa_mp", PA_MP);
      Request.setattribute ("Pd_frpid", pd_frpid);
      Request.setattribute ("Pr_needresponse", pr_needresponse);
      Request.setattribute ("HMAC", HMAC);
      System.out.println ("hmac-->" + HMAC);
    Jump to reqpay.jsp and submit the information to the Request.getrequestdispatcher ("/reqpay.jsp"). Forward (request, response); }else if (status.equals ("Success")) {//Yeepay over there is success, processing returns the validation part printwriter out = Response.getwriter ();
      String keyvalue = "w0p75wmz203fr46r5i70v556whfa94j14yw5j6vuh4yo3nrl5jsqf3c41677"; 
      Gets all plaintext String r0_cmd = formatstring (Request.getparameter ("R0_cmd"));
      String P1_merid = Request.getparameter ("P1_merid");
      String R1_code = formatstring (Request.getparameter ("R1_code"));
      String R2_trxid = formatstring (Request.getparameter ("R2_trxid"));
      String R3_amt = formatstring (Request.getparameter ("R3_amt"));
      String r4_cur = formatstring (Request.getparameter ("R4_cur")); String r5_pid = new String (formatstring (Request.getparameter ("R5_pid")). GetBytes ("Iso-8859-1"), "utf-
      8 ");
      String R6_order = formatstring (Request.getparameter ("R6_order"));
      String R7_uid = formatstring (Request.getparameter ("R7_uid")); String r8_mp = new String (formatstring (Request.getparameter ("R8_MP")). GetBytes ("Iso-8859-1"), "UTF-8");
      String R9_btype = formatstring (Request.getparameter ("R9_btype"));
      Append data to clear text String HMAC = formatstring (Request.getparameter ("HMAC"));
      StringBuffer InfoBuffer = new StringBuffer ();
      Infobuffer.append (P1_merid);
      Infobuffer.append (R0_cmd);
      Infobuffer.append (R1_code);
      Infobuffer.append (R2_TRXID);
      Infobuffer.append (R3_amt);
      Infobuffer.append (r4_cur);
      Infobuffer.append (R5_PID);
      Infobuffer.append (R6_order);
      Infobuffer.append (R7_UID);
      Infobuffer.append (R8_MP);
      Infobuffer.append (R9_btype);
      Encrypt the returned plaintext String MD5 = digestutil.hmacsign (infobuffer.tostring (), keyvalue);
      Determine whether encrypted ciphertext is equal to the transmitted data signature Boolean IsOK = Md5.equals (HMAC); if (IsOK && r1_code.equals ("1")) {//r1_code for 1 indicates success//the payment of the successful order status has been paid, and to show the user to pay the success of the message/Call Mail Service interface, SMS send clothing

      Business and/or here on the print a Word bai ~ out.println ("Order number is:" + r6_order + "Payment amount is:" + R3_amt);
       } else { OUT.PRINTLN ("fail!!!!");  }} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception,
  IOException {doget (request, response);
    } string formatstring (string text) {if (text = null) {return ";
  } return text;
 }
}

2.3 Encryption algorithm

The encryption algorithm used in plaintext is provided by easy treasure, we only need to use it to convert plaintext to ciphertext, the algorithm is as follows:

public class Digestutil {private static String Encodingcharset = "UTF-8";
    public static string Hmacsign (String avalue, String akey) {byte k_ipad[] = new BYTE[64];
    byte k_opad[] = new BYTE[64];
    BYTE keyb[];
    BYTE value[];
      try {keyb = akey.getbytes (Encodingcharset);
    Value = Avalue.getbytes (Encodingcharset);
      catch (Unsupportedencodingexception e) {keyb = Akey.getbytes ();
    Value = Avalue.getbytes ();
    Arrays.fill (K_ipad, Keyb.length, $, (byte) 54);
    Arrays.fill (K_opad, Keyb.length,), (byte) 92);
      for (int i = 0; i < keyb.length i++) {k_ipad[i] = (byte) (Keyb[i] ^ 0x36);
    K_opad[i] = (byte) (Keyb[i] ^ 0x5c);
    } messagedigest MD = null;
    try {md = messagedigest.getinstance ("MD5");
    catch (NoSuchAlgorithmException e) {return null;
    } md.update (K_ipad);
    Md.update (value);
    byte dg[] = Md.digest ();
    Md.reset ();
    Md.update (K_opad); Md.update (DG, 0, 16);
    dg = Md.digest ();
  Return Tohex (DG);
    public static String Tohex (byte input[]) {if (input = = null) return null;
    StringBuffer output = new StringBuffer (Input.length * 2);
      for (int i = 0; i < input.length i++) {int current = Input[i] & 0xff;
      if (current <) Output.append ("0");
    Output.append (integer.tostring (current, 16));
  return output.tostring (); public static string Gethmac (string[] args, String key) {if (args = = NULL | | args.length = 0) {return (n
    ULL);
    } stringbuffer str = new StringBuffer ();
    for (int i = 0; i < args.length i++) {str.append (args[i]);
  Return (Hmacsign (str.tostring (), key));
    }/** * @param avalue * @return/public static string digest (String avalue) {avalue = Avalue.trim ();
    BYTE value[];
    try {value = avalue.getbytes (Encodingcharset); catch (Unsupportedencodingexception e) {value = AVAlue.getbytes ();
    } messagedigest MD = null;
    try {md = messagedigest.getinstance ("SHA");
      catch (NoSuchAlgorithmException e) {e.printstacktrace ();
    return null;

  Return Tohex (Md.digest (value)); //My own test for public static void main (string[] args) {//Parameter 1: PlainText (data to encrypt) Parameter 2: Key System.out.println (Digestuti
    L.hmacsign ("11111", "abc"));
  System.out.println (Digestutil.hmacsign ("11111", "Abd"));
 Troubleshoot data security issues: the plaintext encryption---> ciphertext and then the clear text and ciphertext to Yeepay//Yeepay to get the data, the transmission over the plaintext encryption, and pass over the ciphertext comparison, if the equality of data has not been tampered with (merchants and easy to encrypt when all use the same key)}

The

Encryption algorithm also does not go too much research, seems to be the MD5 second generation encryption algorithm, anyway the clear text throws in, certainly encrypts Cheng Mi-wen on the line. Next look at the reqpay.jsp page:

<% @page language= "java" contenttype= "TEXT/HTML;CHARSET=GBK"%>  

In fact, the page is very simple, is the plaintext and ciphertext together through the <form> form to Yeepay, Yeepay receive URL for https://www.yeepay.com/app-merchant-proxy/node , this is also the official offer, we write this on it. In fact, just a submit button, click submit on the button can be clear text and ciphertext submitted past. Let's take a look at the test results:

3. Test Payment Results

The humble test desk index.jsp~~~:

     

After submitting to reqpay,jsp, click submit button after the effect is as follows, we will ICBC and CCB are measured:



  

The payment process is not a problem, was going to ICBC to pay a 1 cents to see the results of payment, the results found U shield expired, because now with Alipay more convenient ... Not to update the U shield, but I open through the ICBC e payment, so the above interface can also use e payment, so I was very generous to pay 1 cents ~ ~ The results are as follows:


  

Then we will jump to the page we specified before, that is, Tongji University ... OK, the test is done, the whole payment process is over!
This section is mainly through a simple demo test, to see if the payment interface with the bank to connect, now testing is no problem, has been connected to the back as long as the usual payment can be. Simple demo is introduced to this bar, the back is really continue to our previous online shopping mall project on-line payment module development.

Original address: http://blog.csdn.net/eson_15/article/details/51447492

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.