The realization of _java in the first-line payment function of Java Micro-scan code payment mode

Source: Internet
Author: User
Tags cdata flush key string openid readline stub stringbuffer log4j

First, preparatory work

Countless people to cross-examine model one development, so in this posted out, only for reference. As for the difference between mode one and mode two, I have explained many times, is the mode of one of the two-dimensional code is for the goods, mode two two-dimensional code is for orders, other specific details I do not waste breath, you can go to the official view of the document, and then the choice of mode one or mode II have to look at their business.

1.1. About Configuration parameters

Or before that four, app_id and App_secret can be found in the public platform, mch_id and Api_key are found in the merchant platform, especially the Api_key to set up in the merchant platform, this dongdong related to the correctness of the parameters check, so be sure to set up correctly. Sweep code Payment mode in fact, and sweep code payment mode is similar to the actual, will only use app_id, mch_id and Api_key, the rest are not. The official document address of mode one is here: Https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_4

1.2. Relevant Concepts

Here I would like to revise a concept first, in the previous Pattern II development process I mentioned a "payment callback address" concept, the effect is that the customer after the scan completes payment, the micro-trust server to visit the address we provide, send us payment results, so that we can verify orders for delivery, This is a more common concept and term for other payment tools. But then I flipped through the website of Micro-trust, and found that in the development of the model, they called this "asynchronous notification URL" instead of "payment callback address", but essentially it meant a meaning. But why do I have to mention this stuff here? This is because in mode one, in fact, there is another so-called "payment callback" called "Sweep code Payment callback URL", this dongdong with the above "asynchronous notification URL" can be different, simple understanding can be considered as our server on the last to help complete the order of the interface. The development of pattern one requires both "Sweep code payment callback URL" and "Asynchronous notification URL" two interface to complete, so here we have to identify well.

The asynchronous notification URL is set when calling the unified down-order interface, and can be set dynamically, as long as the interface receives parameter response parameters according to the relevant rules. and "Sweep code payment callback URL" is more fixed, it in the micro-trust public platform settings, it takes about 10 minutes to enter into force, everyone login Micro-trust public platform, select micro-letter payment, in the development of the Configuration tab can be found below:

Here we want to set up a server's address (again, the public network address, is to let the micro-mail server can find you).

1.3. Development environment

I'm here with the most basic servlet 3.0 as an example environment. With reference to a third party jar package, compared to Pattern II development, in addition to the use of XML operations jdom, outside of a Google zxing two-dimensional Code pack and log4j package. The following figure:

In order to facilitate debugging, we recommend that you first in this environment down and then transplanted to the real project.

Second, the development of actual combat

Before I do, I suggest that you go to the official document to take a good look at the timeline diagram, understand the sequence diagram, writing code is not difficult, of course, if you can not understand the map, but also combined with my following code to try to understand.

2.1, two-dimensional code generation

First is the two-dimensional code, two-dimensional code in the contents of the link, in the form of:

weixin://wxpay/bizpayurl?sign=xxxxx&appid=xxxxx&mch_id=xxxxx&product_id=xxxxxx&time_stamp= Xxxxxx&nonce_str=xxxxx

You can refer to the official document model for a lifetime into a two-dimensional code rule. Next we need to deliver the chain into a two-dimensional code, where I use Google zxing to generate a two-dimensional code.

Package com.wqy; 
Import java.io.IOException; 
Import Java.io.OutputStream; 
Import Java.util.HashMap; 
Import Java.util.Iterator; 
Import Java.util.Map; 
Import Java.util.Set; 
Import Java.util.SortedMap; 
 
Import Java.util.TreeMap; 
Import javax.servlet.ServletException; 
Import Javax.servlet.annotation.WebServlet; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
 
Import Javax.servlet.http.HttpServletResponse; 
 
Import Org.apache.log4j.Logger; 
Import Com.google.zxing.BarcodeFormat; 
Import Com.google.zxing.EncodeHintType; 
Import Com.google.zxing.MultiFormatWriter; 
Import com.google.zxing.WriterException; 
Import Com.google.zxing.client.j2se.MatrixToImageWriter; 
Import Com.google.zxing.common.BitMatrix; 
Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 
Import Com.wqy.util.PayCommonUtil; 
 
Import Com.wqy.util.PayConfigUtil; /** * Servlet Implementation class Pay1/@WebServlet ("/pay1") public class Pay1 extends HttpServlet {private static final long serialversionuid = 1L; 
   
  private static Logger Logger = Logger.getlogger (Pay1.class); 
   
  public static int defaultwidthandheight=200; 
    /** * @see httpservlet#httpservlet () * * * Public Pay1 () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HttpServlet 
      Response * Response) */protected void doget (HttpServletRequest request, HttpServletResponse Response) Throws Servletexception, IOException {//TODO auto-generated method stub String nonce_str = Paycommonuti 
    L.getnonce_str (); 
    Long time_stamp = System.currenttimemillis ()/1000; 
    String product_id = "Hd_goodsssss_10"; String key = Payconfigutil.api_key; 
    Key Sortedmap<object, object> packageparams = new Treemap<object, object> (); 
    Packageparams.put ("AppID", payconfigutil.app_id); Packageparams.put ("mch_id", PayconfigutIl. 
    MCH_ID); 
    Packageparams.put ("Time_stamp", String.valueof (Time_stamp)); 
    Packageparams.put ("Nonce_str", nonce_str); 
    Packageparams.put ("product_id", product_id);  
     
    String sign = paycommonutil.createsign ("UTF-8", packageparams,key);//MD5 Hash packageparams.put ("sign", sign); 
    Generate parameter String str = tourlparams (packageparams); 
    String Payurl = "Weixin://wxpay/bizpayurl?" + str; 
     
     
    Logger.info ("Payurl:" +payurl); 
    Generate two-dimensional code map<encodehinttype, object> hints=new Hashmap<encodehinttype, object> ();  
    Specifies the error correction level Hints.put (encodehinttype.error_correction, ERRORCORRECTIONLEVEL.L);  
    Specifies the encoding format hints.put (encodehinttype.character_set, "UTF-8"); 
    Hints.put (Encodehinttype.margin, 1); try {Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (Payurl,barcodeformat.qr_code, Defaultwidthandheight, Def 
      Aultwidthandheight, hints); 
      OutputStream out = Response.getoutputstream (); MatrixtoimagewRiter.writetostream (Bitmatrix, "PNG", out);//output two-dimensional code out.flush (); 
       
    Out.close (); 
    catch (Writerexception e) {//TODO auto-generated catch block E.printstacktrace (); } public String Tourlparams (Sortedmap<object, object> packageparams) {//actual can not sort StringBuffer s  
    b = new StringBuffer ();  
    Set es = Packageparams.entryset ();  
    Iterator it = Es.iterator ();  
      while (It.hasnext ()) {Map.entry Entry = (map.entry) it.next ();  
      String k = (string) entry.getkey ();  
      String v = (string) entry.getvalue (); if (null!= v &&! "".  
      Equals (v)) {sb.append (k + "=" + V + "&"); 
  } Sb.deletecharat (Sb.length ()-1);//Erase Last & return sb.tostring (); /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) * * Prote 
     CTED void DoPost (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {//TODO auto-generated Method stub doget (request, response); 
 } 
 
}

2.2. Scan Payment Callback URL interface

When the customer scanned the above two-bit code, the micro-trust server will access this interface, where we have to complete the unified order to obtain the trade Fair statement logo, the main process of processing the following:

1, receive the micro-letter server sent over the parameters, the parameters of signature verification;

2, remove the parameter product_id, this is the only two dimensional code can pass through the parameters, other parameters can refer to the Official Document mode 3.1 input parameters;

3, according to PRODUCT_ID to deal with their own business, such as the calculation of payment amount, generate order number, etc.;

4), call the unified next single interface to obtain trade fair words logo prepay_id;

4.1, prepare the relevant parameters (such as AppID, mch_id, payment amount, order number, description of goods, etc.), invoke micro-letter unified Next single interface (with mode two call unified next single interface similar), note here to add the above mentioned "asynchronous notification URL", That is to say, the asynchronous notification URL interface, the specific parameters refer to the Official document unified single request parameters;

4.2, receive the unified next single interface returns the parameter, carries on the examination sign to the parameter;

4.3, take out the parameter prepay_id, this is the trade fair word marking, extremely important, other parameters may refer to the official document unification to return the result;

5, prepare the relevant parameters (such as AppID, mch_id, Return_code, prepay_id, etc.), in response to the start of the payment callback (if the above steps if the error, such as verification failure can return the wrong parameters to the Micro-trust server), the specific parameters can refer to the Official Document Mode 3.2 Output parameters.

Package com.wqy; 
Import Java.io.BufferedOutputStream; 
Import Java.io.BufferedReader; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import Java.io.InputStreamReader; 
Import Java.util.SortedMap; 
 
Import Java.util.TreeMap; 
Import javax.servlet.ServletException; 
Import Javax.servlet.annotation.WebServlet; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
 
Import Javax.servlet.http.HttpServletResponse; 
 
Import Org.apache.log4j.Logger; 
Import Com.wqy.util.HttpUtil; 
Import Com.wqy.util.PayCommonUtil; 
 
Import Com.wqy.util.PayConfigUtil; 
  /** * Servlet Implementation class NOTIFY1/@WebServlet ("/notify1") public class Notify1 extends HttpServlet { 
  Private static final long serialversionuid = 1L; 
 
  private static Logger Logger = Logger.getlogger (Notify1.class); 
    /** * @see httpservlet#httpservlet () * * * Public Notify1 () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse * response) * * protected void doget (Httpse Rvletrequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO Auto-genera 
    Ted method Stub//read XML InputStream InputStream; 
    StringBuffer sb = new StringBuffer (); 
    InputStream = Request.getinputstream (); 
    String s; 
    BufferedReader in = new BufferedReader (new InputStreamReader (InputStream, "UTF-8")); 
    while ((s = in.readline ())!= null) {sb.append (s); 
    } in.close (); 
     
    Inputstream.close (); 
    Sortedmap<object, object> packageparams = Paycommonutil.xmlconverttomap (sb.tostring ());  
     
    Logger.info (Packageparams); Account information String key = Payconfigutil.api_key;  Key String resxml= "";//feedback to the Micro-trust server//check if (paycommonutil.istenpaysign ("UTF-8", Packageparams, Key) {//appid OpenID mch_id is_subscribe nonce_str product_idSign//Unified under single String OpenID = (String) packageparams.get ("OpenID"); 
      String product_id = (string) packageparams.get ("product_id"); Parse product_id, calculate price, etc. String out_trade_no = string.valueof (System.currenttimemillis ()); Order number String Order_price = "1";  Price Note: The unit of price is divided into String body = product_id; Product Name here set to product_id String attach = "xxx shop"; 
       
      Additional data String nonce_str0 = Paycommonutil.getnonce_str ();   
      Gets the originating computer IP String spbill_create_ip = payconfigutil.create_ip;  
       
       
      String Trade_type = "NATIVE";  
      sortedmap<object,object> unifiedparams = new treemap<object,object> (); Unifiedparams.put ("AppID", payconfigutil.app_id); Must be Unifiedparams.put ("mch_id", payconfigutil.mch_id); Must be Unifiedparams.put ("Out_trade_no", out_trade_no); 
      Must be Unifiedparams.put ("product_id", product_id); Unifiedparams.put ("Body", the body);Must be Unifiedparams.put ("Attach", attach); Unifiedparams.put ("Total_fee", Order_price); Must be Unifiedparams.put ("Nonce_str", NONCE_STR0); Must be Unifiedparams.put ("Spbill_create_ip", spbill_create_ip); Must be Unifiedparams.put ("Trade_type", Trade_type);  
      Must be Unifiedparams.put ("OpenID", OpenID); Unifiedparams.put ("Notify_url", payconfigutil.notify_url);//asynchronous Notification URL String sign0 = paycommonutil.createsign  
      ("UTF-8", Unifiedparams,key); Unifiedparams.put ("sign", sign0);  
      Signature String RequestXML = Paycommonutil.getrequestxml (unifiedparams); 
      Logger.info (RequestXML);  
       
      Unified under Single interface String rxml = Httputil.postdata (Payconfigutil.ufdoder_url, RequestXML); 
      Unified under single response Sortedmap<object, object> reparams = Paycommonutil.xmlconverttomap (rxml);  
       
      Logger.info (Reparams); Check if (paycommonutil.istenpaysign ("UTF-8", Reparams, key)) {//unify the order returnParameter string prepay_id = (string) reparams.get ("prepay_id");/trade Fair session Identification valid String nonce_str1 = P in 2 hours 
         
        Aycommonutil.getnonce_str ();  
        sortedmap<object,object> resparams = new treemap<object,object> (); Resparams.put ("Return_code", "SUCCESS"); 
        Must be Resparams.put ("return_msg", "OK"); Resparams.put ("AppID", payconfigutil.app_id); 
        Must be Resparams.put ("mch_id", payconfigutil.mch_id); Resparams.put ("Nonce_str", NONCE_STR1); Must be Resparams.put ("prepay_id", prepay_id); Must be Resparams.put ("Result_code", "SUCCESS"); 
         
        Must be Resparams.put ("Err_code_des", "OK");  
        String sign1 = paycommonutil.createsign ("UTF-8", Resparams,key); Resparams.put ("sign", SIGN1); 
        Signature Resxml = Paycommonutil.getrequestxml (resparams); 
         
      Logger.info (Resxml); 
        }else{logger.info ("Signature validation error"); Resxml = "<xml>" + "<return_code><! [cdata[fail]]></return_code> "+" <return_msg><!  
      [cdata[Signature Verification Error]]></return_msg> "+ </xml>"; 
      }}else{Logger.info ("Signature validation error"); Resxml = "<xml>" + "<return_code><! [cdata[fail]]></return_code> "+" <return_msg><!  
    [cdata[Signature Verification Error]]></return_msg> "+ </xml>";  }//------------------------------//processing business completed//------------------------------Bufferedoutputstream  
    out = new Bufferedoutputstream (Response.getoutputstream ());  
    Out.write (Resxml.getbytes ());  
    Out.flush ();  
     
  Out.close (); /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) * * Prote 
    CTED void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { TODO auto-generated Method Stub doget (request, RESponse); 
 } 
 
}

At this point, the user's micro-letter will show the amount of money to be paid and the description of the product, and then wait for the customer to complete the payment.

2.3, asynchronous Notification URL interface

When the user completes the payment operation on the micro-letter, the micro-server will notify the interface asynchronously and send us the final payment result so that we can verify the order for delivery and so on, and note that the development of this interface and mode two is identical. The approximate process is as follows:

1, receive the micro-letter server sent over the parameters, the parameters of signature verification;

2, take out the parameter Result_code, the order number out_trade_no, the order Amount Total_fee and other business related parameter, the concrete parameter may refer to the Official document payment result general notice notification parameter;

3, processing business, such as the check order number and order amount, modify order status;

4, prepare the relevant parameters (Return_code and return_msg), answer the micro-trust server.

Note that if the micro-letter received the merchant's reply is not a success or timeout, the micro-letter believes that the notification failure, the micro-trust through a certain strategy to periodically restart the notification, as far as possible to increase the success rate of the notification, but the micro-letter does not guarantee that the notice will eventually succeed (Notification frequency is 15/15/30/180/1800/1800/1800/1800/3600, unit: seconds)

Package com.wqy; 
Import Java.io.BufferedOutputStream; 
Import Java.io.BufferedReader; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import Java.io.InputStreamReader; 
 
Import Java.util.SortedMap; 
Import javax.servlet.ServletException; 
Import Javax.servlet.annotation.WebServlet; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
 
Import Javax.servlet.http.HttpServletResponse; 
 
Import Org.apache.log4j.Logger; 
Import Com.wqy.util.PayCommonUtil; 
 
Import Com.wqy.util.PayConfigUtil;  /** * Servlet Implementation class Re_notify/@WebServlet ("/re_notify") public class Re_notify extends HttpServlet 
  {private static final long serialversionuid = 1L; 
 
  private static Logger Logger = Logger.getlogger (Re_notify.class); 
    /** * @see httpservlet#httpservlet () * * * Public re_notify () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HTtpservletresponse * Response) */protected void doget (HttpServletRequest request, HttpServletResponse Respon SE) throws Servletexception, IOException {//TODO auto-generated Method Stub//read parameter InputStream in 
    Putstream; 
    StringBuffer sb = new StringBuffer (); 
    InputStream = Request.getinputstream (); 
    String s; 
    BufferedReader in = new BufferedReader (new InputStreamReader (InputStream, "UTF-8")); 
    while ((s = in.readline ())!= null) {sb.append (s); 
    } in.close (); 
 
    Inputstream.close (); 
    Sortedmap<object, object> packageparams = Paycommonutil.xmlconverttomap (sb.tostring ()); 
 
    Logger.info (Packageparams); Account information String key = Payconfigutil.api_key; Key String resxml = ""; Feedback to the Micro-trust server//To determine whether the signature is correct if (paycommonutil.istenpaysign ("UTF-8", Packageparams, key)) {//--------------- ---------------//processing business start//------------------------------if ("succesS '. Equals ((String) packageparams.get ("Result_code")) {//Here is the payment success//////////execute own business logic//////////////// 
        String mch_id = (string) packageparams.get ("mch_id"); 
        String OpenID = (string) packageparams.get ("OpenID"); 
        String is_subscribe = (string) packageparams.get ("Is_subscribe"); 
 
        String out_trade_no = (string) packageparams.get ("Out_trade_no"); 
 
        String total_fee = (string) packageparams.get ("Total_fee"); 
        Logger.info ("mch_id:" + mch_id); 
        Logger.info ("OpenID:" + OpenID); 
        Logger.info ("Is_subscribe:" + is_subscribe); 
        Logger.info ("Out_trade_no:" + out_trade_no); 
 
        Logger.info ("Total_fee:" + total_fee); 
        Execute own business logic////////////////Logger.info ("pay success"); 
        Notify the micro-letter. Successful asynchronous acknowledgement. Otherwise it will always be notified backstage. After eight times, the deal failed. Resxml = "<xml>" + "<return_code><! [cdata[success]]></return_code> "+" <return_msg><! [Cdata[ok]]></return_msg> "+" </xml> "; 
        else {logger.info ("Payment failed, error message:" + packageparams.get ("Err_code")); Resxml = "<xml>" + "<return_code><! [cdata[fail]]></return_code> "+" <return_msg><! 
      [cdata[message is empty]]></return_msg> "+" </xml> "; 
      } else {Logger.info ("Signature validation error"); Resxml = "<xml>" + "<return_code><! [cdata[fail]]></return_code> "+" <return_msg><!  
    [cdata[Signature Verification Error]]></return_msg> "+ </xml>";  }//------------------------------//processing business completed//------------------------------Bufferedoutputstream 
    out = new Bufferedoutputstream (Response.getoutputstream ()); 
    Out.write (Resxml.getbytes ()); 
    Out.flush (); 
  Out.close (); /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) * * Prote CTED void DoPost (HttpServletRequest request, HttpSErvletresponse response) throws Servletexception, IOException {//TODO auto-generated method stub doget ( 
  request, response); 
 } 
 
}

Third, test results

3.1. Generated payment two-dimensional code link

3.2, payment callback URL interface to receive the parameters

3.3. Initiate unified request parameter of single order

3.4, unified return the parameters of the order

3.5. Payment callback URL Interface final response parameters


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.