Java micro-letter payment-micro-letter Red Envelope _java

Source: Internet
Author: User
Tags cdata openid pack throw exception

The use of micro-letter red envelopes has been very extensive, this article introduces the case of micro-letter red envelopes, the need to have a certified public number, and opened a micro-letter payment, merchant platform and opened the cash red envelopes the right to.

Https://pay.weixin.qq.com Merchant Landing address. Choose to view the cash bonus in the marketing center

Https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1 Cash Red Envelopes official Website Document description

Let's look at a few simple tests. The premise needs you to go to the merchant platform to recharge first. Pre-payment is not supported. This paper only sums up the call and realization of the interface of the micro-letter cash red envelopes. You should implement how to invoke the interface according to your business.

The general red envelopes in the Https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3 document have all the explanations. Calls must have a certificate for the merchant platform.

The parameters that are required are also listed. Decide according to your own needs.

1.java Package a red Envelope object

 /** 

*
 @author small 帅帅丶
 * @date 2016-8-17 morning 11:12:19
 * Open source China Http://my.oschina.net/xshuai
 * * Public
class Redpack implements serializable{
 private string sign//validation
 private string Mch_billno based on property; /order number
 private string mch_id//merchant number private string wxappid//
 Micro letter AppID
 private string send_name;//merchant name
 private string re_openid;//user OpenID
 private string total_amount;//payment amount
 private string total_num;// Red Envelope Recipients Cash red envelopes can only be 1
 private string wishing;//red Envelope Blessings
 private string client_ip;//invoke the IP
 private String act of the interface machine _name;//Activity name
 private string remark;//memo
 private string nonce_str;//random string
    //set get ellipsis
}

2. The required tool class Createbillno is to generate the merchant order number website document requirements as follows:

/** *
 @author small 帅帅丶
 * @date 2016-8-17 morning 11:12:19
 * Open source China Http://my.oschina.net/xshuai
 * * Public
class Redpackutil {
 /**
 * Generates merchant order number
 * @param mch_id merchant number *
 @param userId The user's userId
 * @ret Urn
 /public static String Createbillno () {
 //composition: mch_id+yyyymmdd+10 digits that cannot be duplicated
 in one day 10-bit digital implementations that cannot be duplicated in a single day are as follows:
 //Because each user binds the userId, their userId are different, plus a randomly generated (10-length (USERID)) to ensure that the 10-digit number is not the same as the
 Date dt=new Date ();
 SimpleDateFormat df = new SimpleDateFormat ("YYYYMMDD");
 String nowtime= df.format (DT);
 int length = ten;
 Return wxconstants.mch_id + nowtime + getrandomnum (length);
 }
 /**
 * Generate a specific number of random digits
 * @param length
 * @return
 /public static String getrandomnum (int length) {
 String val = "";
 Random Random = new Random ();
 for (int i = 0; i < length; i++) {
  val = string.valueof (random.nextint);
 }
 return val;
 }
}

3. The previous work is very simple required certificate and merchant number there. And the merchant platform has the amount to test the cash red envelope interface

Redpack pack = new Redpack (null//first time is empty, redpackutil.createbillno ()//Merchant order number,
  "your own merchant number", "Public number AppID", "name",
  " To send the user's OpenID "," send the amount of units is divided into 1 yuan for example 100, "Only 1", "9", "127.0.0.1",
  "activity name", "remark", "random string");

The test is empty except for sign. All others can be populated. Now we generate sign signatures and generate sign according to the parameters in the Pack object;

Specific Signature Algorithm Https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3 the address of the official website

https://pay.weixin.qq.com/wiki/tools/signverify/can compare this test page to see if the encryption is consistent.

String signs = signature.getsign (pack);
The generated signset into the Pack object
pack.setsign (signs);
Converting an object to an XML lattice requires XML format
String XML = Xmlutil.objtoxml (Pack,redpack.class, "xml");

4. Send Red envelopes

Redpackservice service = new Redpacservice ();
    String result = Service.redpackorder (XML);//Request returned data is successful
public class redpackservice{/** * Red Packet Interface address/private final static String redp_order_path= "https://api.mch.weixin.qq.c
 Om/mmpaymkttransfers/sendredpack "; /** * Need certificate * @param paramxml * @return * * public static String Redpackorder (String paramxml) {try {Wxbas
 
  EService service=new Wxbaseservice (Redp_order_path);
  
 Return Service.sendpost (Paramxml);
 catch (Exception e) {log.error (e.tostring ());
 return null;
   }/** * via HTTPS to API post XML data * * @param URL API address * @param xmlobj the XML data object to submit * @return API back to the actual data of the package * @throws IOException * @throws keystoreexception * @throws unrecoverablekeyexception * @throws Nosuchalgorithme Xception * @throws keymanagementexception */public string sendpost (string url, String postdataxml) throws Ioexce  Ption, Keystoreexception, Unrecoverablekeyexception, nosuchalgorithmexception, keymanagementexception {if (!hasInit)
    {init ();

    String result = null; HttpPost HttpPost = new HttpPost (URL); Resolves XStream bug//XStream Xstreamforrequestpostdata = new XStream (New Domdriver ("UTF-8", New Xmlfriendlynamecod

    ER ("-_", "_"));

    The data object to be submitted to the API is converted into XML format data post to the API//String Postdataxml = Xstreamforrequestpostdata.toxml (xmlobj);
    Util.log ("Api,post Past data is:");

    Util.log (Postdataxml);
    It is indicated that the use of UTF-8 encoding, otherwise to the API server XML in Chinese can not be successfully identified stringentity postentity = new Stringentity (postdataxml, "UTF-8");
    Httppost.addheader ("Content-type", "Text/xml");

    Httppost.setentity (postentity);

    Set the configuration of the requestor Httppost.setconfig (requestconfig);

    Util.log ("Executing request" + httppost.getrequestline ());

      try {httpresponse response = Httpclient.execute (HttpPost);

      httpentity entity = response.getentity ();

    result = entityutils.tostring (entity, "UTF-8");

    catch (Connectionpooltimeoutexception e) {log.e ("http Get throw connectionpooltimeoutexception"); catch (ConnecttimeoutexceptiOn e) {log.e ("http Get throw connecttimeoutexception");

    catch (Sockettimeoutexception e) {log.e ("http Get throw sockettimeoutexception");

    catch (Exception e) {log.e ("http Get throw Exception");
    finally {httppost.abort ();
  return result;

 }

5. Returned XML to see if success due to only recharge 1 yuan a few days ago has been tested to send so return the following information

<xml>
<return_code><![ Cdata[success]]></return_code>
<return_msg><![ cdata[account balance is insufficient, please go to the merchant platform to recharge and try again]]></return_msg>
<result_code><![ Cdata[fail]]></result_code>
<err_code><![ Cdata[notenough]]></err_code>
<err_code_des><![ cdata[account balance is insufficient, please go to the merchant platform to recharge and try again]]></err_code_des>
<mch_billno><![ Cdata[1371729102201629220149762756]]></mch_billno>
<mch_id><![ cdata[here is the merchant number in order to secure the deletion of]]></mch_id>
<wxappid><![ cdata[-appid]]></wxappid> public number
<re_openid><![ CDATA[OD5QQW8E_LBIAW9SZZUD-2XHTMVX This is the user's openid]]></re_openid>
<total_amount>100</total_ Amount>
</xml>

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.

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.