Spring uses paid treasure sweep code to pay _java

Source: Internet
Author: User
Tags unsupported

The previous paragraph has been studying Alipay's sweep code to pay, I have to say, Alipay's documentation is really a rotten (at least at the beginning of the first time is MENGBI). The example above in the document is quite different from the example in the demo. Often the document above the example is very simple, and the demo code is very complex, so at the beginning did not know which code to use, and then took a closer look at the demo of those packets inside the code, found also called the document example of those interfaces, this just understand that they are a thing, Only demo to the interface of the document to do some packaging.

First to apply for an enterprise's Alipay account, this account has a PID, you need to add the application to this account, each application has a appid, and a public key and private key. Public and private keys can be generated from the tools provided by Alipay, and Java developers need to use the private key in PKCS6 format. If the application needs to use the Sweep code function, you need to add in the application in person to pay the option, this need to sign. Signed a face-to-face pay function, can not be used directly, because the application needs to be on-line to use, so the development can use the sandbox version of the application, Alipay provided with a sandbox version of the gateway, Alipay Public key, PID and AppID, in the configuration needs to be modified.

Code can directly use the code inside the demo, first in the project to import Alipay provided by the API (note is not the demo code), and then import the demo code, as shown in the figure:


This com.alipay.demo.trade.Main file can be run directly, but you need to configure a resource file:

# Alipay Gateway name, Partnerid and AppID #此为沙箱环境的网关 open_api_domain = https://openapi.alipaydev.com/gateway.do Mcloud_api_domain =

http://mcloudmonitor.com/gateway.do #此为沙箱环境的商户UID pid = 2088102172329883 #此处请填写你沙箱环境当面付的APPID AppID = 2016082000300485 # RSA private key, public key and Alipay public key #此处请填写你的商户私钥且转PKCS8格式 Private_key = miiceqibadanbgkqhkig9w0baqefaascammwggjfageaaogbamkxzrfr+ rnvygbs9qz2ce1mcsibreaqan+5pf5+02hyj4hzcnttwqhfm91ih3wypyhpm7xlbgj5ywjtgc4g1lz75r8a+ucyuxp8by1lv/44gi/ tiflsgatfq73ocm9imxocrdyz2zcwqi1gv+b3udoy/ da5w07grwizfzs6vq1ragmbaaecgyeaqhhc4grbsrckeinytk1vhqcj0yg11lvy85z3si0fny26dvs8r5gfydzc/mx5f8rnpuuyuhqn+ 4cqor3d/ C291x1itov2nevlhejroudknp4oqriqt2w9pz8rzwzp2jcwvrvuf4ztpeimppmorp6sprfx6dlzg29sfi6gzwu6tkcqqdp3mim1bhus3yonezgqc69zn0 /dgofkeix0s18qau1x4i1fejvtky4hpdwihpgyajm0ufg1lk8mtiunhpzrcnakea1qf6u1akjm6zsvdenrxedtcc75uvjgsyfjwhhx9pjyd9vx8nszv0z0u4v 0zg0n0yvhj5lro6u5fcqfrw1wixnqjbalmckz8svf/h9n6liwmspy6w5q82knrlrc7wscenspqt0wql5+ Sacg98m0xxy5j1hmiolhxgctvyrixowobivqccqqctnanb4uz3q/86r/kukbvd3dirwlfryaho6yxp8oy+je/bv/359+vr3cxzyyldhzor9/tvspwr/y9q4jlemq1takealbu7+4edzfap7e/fmgykd5dml8h2iaeumrrcpl84ghffk/7psq/ 40ngkxptgy44nlelhxcrpw5czu6gqdinjoa== #此处请填写你的商户公钥 Public_key = migfma0gcsqgsibdqebaquaa4gnadcbiqkbgqdcl2axufq572iabpas9nbnzgkiauxmqmp/ut3+ftnh8o+ b83du01qhxzvdsb98gd8oato15w4ceclibyauinzc++a/gvlasrst/g8ts1f+ Obov0yhy0oae30o9zndpypl6hexwm9mqskotyffm91a6mvw2ucno4evosxc0ulatawidaqab #此为沙箱环境的公钥 Alipay_public_key = Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdighnon7llillketd6bfrj0gqgs2y3mn1wmqmyh9zeywlz5p1zrahrahbxafcfsqshsnfqomaqzshrvjcqj Saw1jyqrxapdkbmr90dipixmiykxv4ggakpyj/6ftfy99uhpiq0qadd/uszqsefwo0atvp/65zi3eof7tcz32owpwidaqab # To pay the maximum number of queries and the query interval (milliseconds) Max_query_retry = 5 Query_duration = 5000 # Face-to-face pay maximum undo times and undo interval (milliseconds) Max_cancel_retry = 3 Cancel_duration =

 2000 # Transaction security thread first scheduling delay and scheduling interval (sec) Heartbeat_delay = 5 Heartbeat_duration = 900

The

is then run to run the Main.java file. As for our actual application of the sweep code payment code can be directly copy Main.java file in the Test_trade_precreate () function, in the controller to establish a function:

@RequestMapping (value = "/pay/alipay", method = requestmethod.post) public map<string, string> Alipay (@RequestPar

    Am String amount, @RequestParam int userid) {map<string, string> Map = new hashmap<string, string> ();  (required) Merchant website Order system in the unique order number, 64 characters, can only contain letters, numbers, underscores,//need to ensure that the merchant system can not repeat, the proposed database sequence generation, String Outtradeno = "xxxxx" +

    System.currenttimemillis () + (Long) (Math.random () * 10000000L); (required) The order title, a rough description of the user's payment purposes.

    such as "xxx brand XXX shop face to pay sweep code consumption" String subject = "pay"; (required) The total amount of the order, Unit is yuan, can not exceed 100 million yuan///If the "Discount amount", "No discount Amount", "Total order Amount", must meet the following conditions: "Total order Amount" = "Discount Amount" + "No discount amount" String Totalamoun

    t = amount; (optional) Order can not be discounted amount of money to match the business platform to configure discount activities, if the beverage does not participate in the discount, the corresponding amount is filled in this field//if the value is not passed in, but the "total order Amount" is passed in, "Discount Amount", the value defaults to "Total order Amount"-"Discount Amount" String u

    Ndiscountableamount = "0"; Seller Alipay Account ID, used to support a signed account to support the call to a different collection account number, (to sellerid corresponding to the payment PO account)//If the field is empty, the default for the merchant signed with Alipay's PID, that is, AppID corresponding PID String sell

    Erid = "2088102172329883"; Order description, you can carry out a detailed description of the transaction or merchandise, such as filling out "Purchase 2 pieces of a total of 15.00 Yuan "String BODY =" Purchase 3 pieces of goods a total of 20.00 yuan ";

    Merchant operator number, add this parameter to do sales statistics for merchant operators String Operatorid = "test_operator_id";

    (required) Merchant store number, through the store number and business background can be configured to store the accurate discount information, detailed inquiry Alipay technical support String storeId = "2088102172329883"; Business extension parameters, currently can be added by Alipay assigned by the system business number (through the Setsysserviceproviderid method), please consult Alipay technical support extendparams extendparams = new Extendparams ()
    ;

    Extendparams.setsysserviceproviderid ("2088100200300400500");

Payment timeout, defined as 120-minute String timeoutexpress = TIMEOUT;
Product detail list, need to fill in the purchase details,//list<goodsdetail> goodsdetaillist = new arraylist<goodsdetail> (); Create a commodity information, parameter meaning is the commodity ID (use GB), name, Unit price (unit is divided), quantity, if need to add commodity category, see Goodsdetail//Goodsdetail GOODS1 = Goodsdetail.newinst
ance ("goods_id001", "xxx bun", 1000, 1);
Create a good item and add it to the product detail list//Goodsdetaillist.add (GOODS1);  //Continue to create and add the first product information, the user to buy products for "black Toothbrush", the unit price of 5.00 yuan, purchased two//Goodsdetail GOODS2 = goodsdetail.newinstance ("goods_id002",
"XXX Toothbrush", 500, 2);

    Goodsdetaillist.add (GOODS2); Create a sweep code payment request BuiLder, set request parameters Alipaytradeprecreaterequestbuilder Builder = new Alipaytradeprecreaterequestbuilder (). Setsubject ( Subject). Settotalamount (TotalAmount). Setouttradeno (Outtradeno). Setundiscountableamount (Undiscou Ntableamount). Setsellerid (Sellerid). Setbody (body). Setoperatorid (Operatorid). Setstoreid (storeId). Setextendparams (Extendparams). Settimeoutexpress (timeoutexpress). Setnotifyurl ("http:// Xxx.xx.xxx.xxx:8080/baobiao/pay/notify ");//Alipay server to notify Merchant server to specify the page HTTP path, according to the need to set up, here we set is our own write an interface, etc. will be introduced//.

    Setgoodsdetaillist (goodsdetaillist);
    Alipayf2fprecreateresult result = Tradeservice.tradeprecreate (builder);
        Switch (Result.gettradestatus ()) {case SUCCESS:log.info ("Alipay success:)");

        System.out.println ("Payment PO Pre-single success:)");
Alipaytradeprecreateresponse response = Result.getresponse ();
Dumpresponse (response); System.out.println (Response.getboDY ()); Need to be modified to run the path on the machine//String FilePath = String.Format ("/users/liuyangkly/qr-%s.png", Response.getouttradeno
());
Log.info ("FilePath:" + FilePath);
Zxingutils.getqrcodeimge (Response.getqrcode (), 256, FilePath);

        System.out.println (Response.getqrcode ());  Generate orders, insert database Baobiaoorder order = new Baobiaoorder (userid, Outtradeno, "", double.parsedouble (amount), New Date (),
        1);

        Baobiaoorderservice.insertorder (order);
        Map.put ("Status", "true"); Map.put ("QRCode", Response.getqrcode ());

        Returns to the client two-dimensional code map.put ("Outtradeno", Outtradeno);

      return map;
        Case FAILED:log.error ("Payment PO Pre-Failure!!!");
        System.out.println ("Pay treasure to advance a single failure!!!");
        System.out.println (Result.getresponse (). GetBody ());

      Break
        Case UNKNOWN:log.error ("system exception, pre-single State unknown!!!");
        SYSTEM.OUT.PRINTLN ("System exception, pre-order status unknown!!!");

      Break
 Default:log.error ("Unsupported transaction status, transaction return anomaly!!!");       SYSTEM.OUT.PRINTLN ("Unsupported transaction status, transaction return anomaly!!!");
    Break
    } map.put ("Status", "false"); Map.put ("MSG", "system abnormal, please try again later!")
    ");
  return map;

 }

Then the logic is that the user will use the mobile phone scan code to pay Alipay payment, and then Alipay received will send a payment to the success of the message to our set of Notify_url, as follows:

@RequestMapping (value = "/pay/notify", method = requestmethod.post) public String notifyresult (HttpServletRequest reque St, httpservletresponse response) {Log.info ("receive an asynchronous notice of Alipay!")
    ");

    map<string, string> params = new hashmap<string, string> ();
    All parameters are removed to verify the signature enumeration<string> parameternames = Request.getparameternames ();
      while (Parameternames.hasmoreelements ()) {String parametername = parameternames.nextelement ();
    Params.put (ParameterName, Request.getparameter (parametername));
    Boolean signverified;
    try {signverified = Alipaysignature.rsacheckv1 (params, Configs.getalipaypublickey (), "UTF-8");
      catch (Alipayapiexception e) {e.printstacktrace ();
    Return "Failed";
      } if (signverified) {String Outtradeno = params.get ("Out_trade_no"); Log.info (Outtradeno + "order callback notification.)
"); System.out.println ("Verify signature successful!")
      "); Log.info ("Verify signature successful!")

      "); If the AppID in the parameter is not the same as the AppID filled in, the exception is notified if (! Configs.getappid (). Equals (Params.get ("app_id"))) {Log.warn ("Unlike the AppID at the time of payment, this is an exception notification and should be ignored!")
        ");
      Return "Failed"; ///Find the order number in the database and compare the amount to the amount in the database, and if not, also notify baobiaoorder order = Baobiaoorderservice.findorderbyouttraden
      O (Outtradeno); if (order = = null) {Log.warn (Outtradeno + ") Check no such orders!"
        ");
      Return "Failed"; } if (Order.getamount ()!= double.parsedouble (Params.get ("Total_amount"))) {Log.warn ("unlike the amount at the time of payment, this is an exception notification, should be ignored!")
        ");
      Return "Failed"; if (order.getstatus () = = baobiaoorder.trade_success) return "SUCCESS";
      If the order has been paid successfully, simply ignore this notification String status = Params.get ("Trade_status"); if (Status.equals ("Wait_buyer_pay")) {//If status is waiting for user payment if (order.getstatus ()!= Baobiaoorder.wait_buyer_pay) Baobi
      Aoorderservice.modifytradestatus (Baobiaoorder.wait_buyer_pay, Outtradeno); else if (status.equals ("trade_closed")) {//If the status is unpaid transaction timeout closed, or payment completed after full refund if (Order.getstatus ()!= BaobiaoorDer.
      trade_closed) Baobiaoorderservice.modifytradestatus (baobiaoorder.trade_closed, Outtradeno); else if (status.equals ("trade_success") | | | status.equals ("trade_finished")) {//If the status is already paid successfully if (Order.getstatus (
      )!= baobiaoorder.trade_success) baobiaoorderservice.modifytradestatus (baobiaoorder.trade_success, Outtradeno);
      else {baobiaoorderservice.modifytradestatus (baobiaoorder.unknown_state, Outtradeno);
    Log.info (Outtradeno + "The status of the order has been modified to" + status);
    else {//If the verification signature does not pass return "failed";
  Return to "success";

 }

This is probably the case, but less to the client to send payment successful notification, there are some security issues.

Finally, summarize the problems encountered in this process:

1. Alipay returned two-dimensional code can not be opened directly in the browser, but to use two-dimensional Code conversion tool to generate two-dimensional code, or through cli.im this site to view
2. Pay treasure sandbox environment generated two-dimensional code can only use the sandbox version of the mobile phone Alipay to sweep the code, the normal version of the payment of the treasure sweep will appear this two-dimensional code expiration and so on error
3. If the payment is not received after the payment PO sent asynchronous notification, you can use postman and other tools to check the completion of the Notify_url can be used public network IP access to
4. If the problem with the ISV's lack of permissions is because there is no sign or application does not add the corresponding function, the application is not online and can not be used, the development of the time to choose the sandbox application
5. Sandbox version of the mobile phone payment treasure when the registration can not receive text messages, contact customer service to ask for an account

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.