Home  >  Article  >  Java  >  Detailed explanation of the case of Java calling Alipay payment interface

Detailed explanation of the case of Java calling Alipay payment interface

php是最好的语言
php是最好的语言Original
2018-08-09 13:59:354541browse

1. Scenario: The company needs to make Alipay payment on the website.
2. API: Use the payment capability of Alipay’s open platform-instant payment interface. Alipay Open Platform Link
3. Analysis:

#1. Alipay’s documents are relatively easy to read, mainly because there are corresponding DEMOs. The DEMO I am looking at here It is the JAVA-UTF-8 version.

Detailed explanation of the case of Java calling Alipay payment interface

2. Import DEMO and fill in the corresponding partner and key in com.alipay.config (obtained from the corresponding merchant backend). Run it directly to understand the payment process.

Detailed explanation of the case of Java calling Alipay payment interface

3. Rewrite: I am using springmvc mybatis here. The product initiates purchase (payment via Alipay), jumps to Alipay, and Alipay calls back the payment status.

4. Implementation:

1. Initiate a purchase request for the product (use the page in the DEMO directly).

[javascript] view plain copy


  1. #

  2. # #=

    "header">

  3.         

    class

    ="container black">  

  4.             

    class

    ="qrcode">  

  5.                 

    class

    ="littlecode">  

  6.                     Detailed explanation of the case of Java calling Alipay payment interface"16px" src="img/little_qrcode.jpg" id="licode">  

  7.                     

    class

    ="showqrs" id="showqrs">  

  8.                         

    class

    ="shtoparrow">

      
  9.                         

    class

    ="guanzhuqr">  

  10.                             Detailed explanation of the case of Java calling Alipay payment interface"img/guanzhu_qrcode.png" width="80">  

  11.                                                                                                                                                                                                            margin-top:5px;"> ##                                                 ##                                                                                                                                                                                                        because of #"shmsg" style=

    "margin-bottom:5px;"
  12. >

  13. Receive important information

  14. # This/P & GT; ;/p>

  15.             

      
  16.         

      
  17.         

    class

    ="container">  

  18.             

    class

    ="nav">  

  19.                 "https://www.alipay.com/" class="logo">Detailed explanation of the case of Java calling Alipay payment interface"img/alipay_logo.png" height="30px">  

  20. ##                                                                       class=

  21. "open"
  22. target="_blank">Open platform ##                                                           ##> ##                                                                   .com/doc2/detail?treeId=62&articleId=103566&docType=1"

    target=
  23. "_blank"

    >Online Document li>

  24.                                                                                                                                                                                                                                                                                           Since ="_blank">Technical Support

  25. # #                                                                                                                p>
  26. ##                                    >

  27. #                                                       ##>Alipay instant payment (create_direct_pay_by_user)

  28. #              

    ##                                                                               "content">

  29. ##                           "${ctx}/aliPay/open" class="alipayform" method="POST" target="_blank"> --%>

  30. #                                               ##"element"

    style="margin-top:60px;">                                                                                                                                                                                                    

  31. #                                                

  32.             

    class

    ="element">  

  33.                 

    class

    ="etitle">商户订单号:

      
  34.                 

    class

    ="einput">"text" name="WIDout_trade_no" id="out_trade_no">

      
  35.                 
      

  36.                                                                                                                                                             through ).Required (recommended to be English letters and numbers, no special characters)

    #                              
  37.                                                                                                                                                                                                                                
  38. #"element"

    >

  39. #                                                     

    "etitle"
  40. >Product name:

  41.                                                                                                                                      #"text" name="WIDsubject" id="WIDsubject" value="test product 123">

    ##                                                                                                                                                                        Name (subject), required (Chinese, English, numbers are recommended, no special characters allowed)
  42. #                               ;

  43. ##                                                                                      

  44.                                                                                                                                                                                               through ; ##                                                        #>"text"

    name=
  45. "WIDtotal_fee"

    id="WIDtotal_fee " value="0.01">

                                                                                                                             >Note: Payment amount (total_fee), required (format such as: 1.00, please be accurate to the minute) ##                                                                           
  46.                                                                                                            #                                                                                                                                                  /p>

    #                                       
  47. >

    "text" name="WIDbody" id= "WIDbody" value=

    "Instant transfer test"
  48. >

    ##                                                                                             
  49.                                                                                                                                                               , optional (recommend Chinese, English, numbers, no special characters)

    #                                                                                                      
  50. #                                                    "button"

  51. class="alisubmit" id="sbumitBtn"

    value =
  52. "Confirm payment"

    > ##                                                                                 #

    "returnAli">

  53.     

    class

    ="footer">  

  54.         

    class

    ="footer-sub">  

  55.             "http://ab.alipay.com/i/index.htm" target="_blank">关于支付宝|  

  56.             "https://e.alipay.com/index.htm" target="_blank">商家中心|  

  57.             "https://job.alibaba.com/zhaopin/index.htm" target="_blank">诚征英才|  

  58.             "http://ab.alipay.com/i/lianxi.htm" target="_blank">联系我们|  

  59.             "#" id="international" target="_blank">International Business|  

  60.             "http://ab.alipay.com/i/jieshao.htm#en" target="_blank">About Alipay  

  61.             
      

  62.              支付宝版权所有  

  63.             class="footer-date">2004-2016  

  64.             "http://fun.alipay.com/certificate/jyxkz.htm" target="_blank">ICP证:沪B2-20150087  

  65. ##          

  66. ##                                                                                             

  67. ##2. After clicking to confirm the payment, request the background through ajax and put the returned html code directly into the above

    , this form will be automatically submitted.
  68. [javascript] view plain copy


##$(function

(){


$(

"#sbumitBtn"

).on(

'click'
  1. ,

    function (){

    ## $.ajax({
  2. ## type : "post",

  3.             data : {  

  4.                 WIDout_trade_no : $('#out_trade_no').val(),  

  5.                 WIDsubject : $('#WIDsubject').val(),  

  6.                 WIDtotal_fee : $('#WIDtotal_fee').val(),  

  7.                 WIDbody : $('#WIDbody').val()  

  8.             },  

  9.             url : "${ctx}/aliPay/open",  

  10.             success : function(data) {  

  11.                 $('#returnAli').append(data.sHtmlText);  

  12.             },  

  13. error : function(da){

  14. # }

  15. ##                );

                                                                                                                                                                                               

  16. #3. In the background controller, the alipayapi.jsp in the demo is basically used directly. The difference is that the parameter transfer is defined by ourselves, and the return method complies with apringmvc requirements and is based on business needs. Order information with a status of unpaid is saved.
  17. [javascript]

    view plain
  18. copy
##@RequestMapping(


"open")

public

ResponseEntity open(Model model, String WIDout_trade_no, String WIDsubject, String WIDtotal_fee,

    String WIDbody) {
  1. ///////////////////////////////////// / Request parameters ////////////////////////////////////////

  2. ##// Merchant order number, in the merchant website order system Unique order number, required

  3. ## String out_trade_no = WIDout_trade_no;

  4. //Order name, required

  5. # String subject = WIDsubject;
  6. ##// Payment amount, required
  7. String total_fee = WIDtotal_fee;
  8. ##// Product description, can be empty
  9. ## String body = WIDbody;

  10. ##//Pack request parameters into an array

  11. # Map sParaTemp = new HashMap();

  12. # sParaTemp.put("service" , AlipayConfig.service);

  13.     sParaTemp.put("partner", AlipayConfig.partner);  

  14.     sParaTemp.put("seller_id", AlipayConfig.seller_id);  

  15.     sParaTemp.put("_input_charset", AlipayConfig.input_charset);  

  16.     sParaTemp.put("payment_type", AlipayConfig.payment_type);  

  17.     sParaTemp.put("notify_url", AlipayConfig.notify_url);  

  18.     sParaTemp.put("return_url", AlipayConfig.return_url);  

  19.     sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);  

  20.     sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);  

  21.     sParaTemp.put("out_trade_no", out_trade_no);  

  22.     sParaTemp.put("subject", subject);  

  23.     sParaTemp.put("total_fee", total_fee);  

  24. sParaTemp.put("body", body);

  25. // Other business parameters are added according to the online development documents. Document address: https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId= 62&articleId=103740&docType=1

  26. ##// Such as sParaTemp.put("Parameter name","Parameter value ");

  27. // Build request

  28. ## String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,
  29. "get"

    , "Confirm");

    ## model.addAttribute(
  30. " sHtmlText"
  31. , sHtmlText);

  32. // Save payment record
  33. #​ hysWebMeetingAliService.insertSelective(sParaTemp);

  34. return new ResponseEntity(model, HttpStatus.OK);

  35. }


##4. Callback: The java code in notify_url.jsp in DEMO is also directly used and slightly modified and the business code (modified status, etc.) is added;

[javascript] view plain copy


  1. ##@RequestMapping("notify")

  2. @ResponseBody

  3. ##public

    String notify(HttpServletRequest request){

  4. //Get Alipay POST feedback information

  5.     Map params = new HashMap();  

  6.     Map requestParams = request.getParameterMap();  

  7.     for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {  

  8.         String name = (String) iter.next();  

  9.         String[] values = (String[]) requestParams.get(name);  

  10.         String valueStr = "";  

  11.         for (int i = 0; i 

  12.             valueStr = (i == values.length - 1) ? valueStr   values[i]  

  13.                     : valueStr   values[i]   ",";  

  14.         }  

  15.          //Garbled code solution, this code is used when garbled characters appear. If mysign and sign are not equal, you can also use this code to convert

  16. ##//valueStr = new String( valueStr.getBytes("ISO-8859-1"), "gbk");

  17. # params.put(name , valueStr);

  18. ## }
  19. #  
  20. //To obtain Alipay’s notification return parameters, please refer to the page jump synchronization notification parameter list in the technical documentation (the following is for reference only)//
  21. //Merchant order number
  22. ## String out_trade_no = request.getParameter(

    "out_trade_no"
  23. );

  24. //Alipay transaction number
  25. ## String trade_no = request.getParameter("trade_no"

  26. );
  27. //trade state

  28. ## String trade_status = request.getParameter("trade_status");

  29. ##//To obtain Alipay’s notification return parameters, please refer to the page jump synchronization notification parameter list in the technical documentation (the above is only refer to)//

  30. if(AlipayNotify.verify(params)){//Verification successful

  31.       

    //////////////////////////////////////////// //////////////////////////////////////////////////

  32. ##       
  33. //Please add the merchant’s business logic program code here

  34. ##//——Please base it on your business logic Write a program (the following code is for reference only)——
  35. ##boolean
  36. flg =

    false;

  37. ## iF ## (Trade_Status.equals (## "" Trade_finished "#)) {

  38. #            
  39. //Determine whether the order has been processed on the merchant website

  40.               
  41. //If no processing has been done, check the details of the order in the order system of the merchant website according to the order number (out_trade_no), and execute the merchant's business procedures

    ##                                                                                                                                                                       
  42. //Please make sure that the total_fee, seller_id during the request are consistent with the total_fee, seller_id obtained during the notification
  43. ##                                                                                                                                                                                                                                                      since #

  44. //Notice:

  45. #              //After the refund date exceeds the refundable period (such as refundable within three months), the Alipay system Send transaction status notification

  46. } else if (trade_status.equals("TRADE_SUCCESS" )){

  47.               //Determine whether the order has been processed on the merchant website

  48. #                           //If it has not been processed, check it in the order system of the merchant website according to the order number (out_trade_no) Go to the details of the order and execute the merchant's business procedures

  49. # The total_fee and seller_id are consistent with the total_fee and seller_id obtained during the notification.

    ## After processing, the business procedures of the merchant will not be executed
  50. ##                          #         

    //Note:
  51.    

  52. #                                                                                                                                                                                                                                  ​Notification of the transaction status

  53.               //Change the order status and the status in the Alipay record table to paid according to the order number

  54. flg = hysWebMeetingAliService.changeOrderAndAliStatusSuccess(out_trade_no);

  55. #             

  56.                                                                                  Please write the program according to your business logic (the above code is for reference only)——

  57. ##          //out.print("success"); //Please do not modify or delete

  58.                                                                                                                                     

  59. "success";

  60. ## }
  61. else

    {

  62.                                                                                                                                                                                                                   ///////////////////////////////////////////////////// /////////////////////////////////////////

  63. ## }
  64. else

    {

    //Verification failed
  65. ##          

    //out.print("fail");

  66.      

    return "fail";

  67. ## }  
  68. }  

  69. 5. return_url: The page jump synchronization notification page path is the page that Alipay will jump back to after the payment is successful. "The complete path in http:// format is required, and custom parameters such as ?id=123 cannot be added. The external network must be accessible normally." Alipay clearly stipulates that no custom parameters can be added after the page that bounces back, so some of us are It is a bit troublesome to judge the jump based on some types. I did a trick here: first move the java code in return_url.jsp directly and modify it slightly (change to springmvc method). My bounce address is IP/aliPay/returnUrl, and then new ModelAndView ("redirect:/meeting/info") to redirect to the URL we are thinking of (see point 4 of the summary below for parameter issues).

    [javascript] view plain copy


    1. # @RequestMapping("returnUrl")

    2. public ModelAndView returnUrl(HttpServletRequest request){

    3. ModelAndView mv =

      new ModelAndView("redirect:/meeting/info");

    4. ##                
    5. // Get Alipay Get to feedback information #

    6.         Map params = new HashMap();  

    7.         Map requestParams = request.getParameterMap();  

    8.         for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {  

    9.             String name = (String) iter.next();  

    10.             String[] values = (String[]) requestParams.get(name);  

    11.             String valueStr = "";  

    12.             for (int i = 0; i 

    13.                 valueStr = (i == values.length - 1) ? valueStr   values[i]  

    14.                         : valueStr   values[i]   ",";  

    15.                                                                                                                                                                                         . If mysign and sign are not equal, you can also use this code to convert

    16. # valueStr.getBytes("ISO-8859-1"), "utf-8");

    17. # params.put (name, valueStr); ## }

    18. #                                                                                                                                             

    19. ##                                                                                                  

    20. # String out_trade_no = request.getParameter("out_trade_no");

    21. //Alipay transaction number
    22. # String trade_no = request.getParameter("trade_no"

    23. );
    24. ##

    25.                                                                                                                                                                                                                                       .getParameter("trade_status");

    26. ##                              "color:#ff0000;">String meetingId = request.getParameter(

      "extra_common_param"
    27. );

    28. # mv.addObject(

      "meetingId", meetingId);

  70. ##//Get Alipay notification return parameters, Please refer to the page jump synchronization notification parameter list in the technical documentation (the above is for reference only) //

  71. ##​​​​

  72. # // Calculate the notification verification results

  73. #Boolean

    # Verify_result = Alipaynotify.verify (Params)

  74.             if(verify_result){//Verification successful

  75. ##                 //////////////////////////////////// ///////////////////////////////////////////////////// //////

  76.                                                                                         

  77. #         
  78. //— —Please write the program according to your business logic (the following code is for reference only)——

    ##                             
  79. (trade_status.equals(

    "TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) { #                        //Determine whether the order has been processed on the merchant website

  80. ##                                                                                                                                                                                                                                       //If it has not been processed, check the details of the order in the order system of the merchant website according to the order number (out_trade_no), and Execute merchant’s business procedures

  81. ## // If you have done it, do not perform the business procedure of the merchant

  82. ##                                                                                                                                                                                            through Can be used as page art editor

  83. #// out.println("Verification successful
    ");
  84. ##                                                           Reference)--

  85. /////////////////////////////////////////////////// /////////////////////////////////////////////

  86. ##                                                                                                                       

            //This page can be used for page art editing

  87. ##//                                                                                             ("verification failed");

  88. }

  89.                                                                            ;

  90. }

    5. Summary:

  91. 1. Comparison of Alipay integration Short answer, it will be easier if you take a look at the DEMO and run it to understand the process.
  92. 2. When debugging, especially callbacks, the project must be deployed to a server that can be accessed from the external network.

3. I have not encountered the above inexplicable problems. If so, you can contact me, or read the Eclipse remote debugging article to track the problem.

4. What should I do if I need to pass parameters when doing page jump synchronization notification page path? I customized a parameter at first, but I didn’t get it. Then I saw a comment in the DEMO like this Written by:

[javascript]

view plain copy

##// Other business parameters are added according to the online development document. Document address: https://doc.open.alipay.com/doc2/detail.htm? spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1


##So after I opened it and looked at it, I selected The public return parameter extra_common_param is provided, and I know what this field means to me. But you should also pay attention, others explained:
  1. [javascript] view plain copy


    1. ##The parameters body (product description), subject (product name), extra_common_param (public return parameters) cannot contain special characters (such as: #, %, &, ), sensitive words, and cannot Use foreign languages ​​(foreign languages ​​that Wangwang does not support, such as Korean, Thai, Tibetan, Mongolian, Arabic);

    ## in the open method Set value:

    [javascript]

    view plain copy


    1. ##sParaTemp.put(

      "extra_common_param", meetingId);

    2. Get the value in the returnUrl method and use it as a redirection parameter:

    [javascript]

    view plain

    copy


    1. ##String meetingId = request.getParameter("extra_common_param");

    2. mv.addObject("meetingId", meetingId);

    Related recommendations:

    Alipay payment interface single transaction query interface

    Alipay mobile website payment interface FOR ECShop

The above is the detailed content of Detailed explanation of the case of Java calling Alipay payment interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn