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:35 4528browse

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 plaincopy


  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. class

    ="container">

  16. class

    ="nav">

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

  18. ##class=

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

    target=
  21. "_blank"

    >Online Document li>

  22. Since ="_blank">Technical Support

  23. # # p>
  24. ## >

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

  26. #

    ##"content">

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

  28. # ##"element"

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

  29. #

  30. class

    ="element">

  31. class

    ="etitle">商户订单号:

  32. class

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


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

    #
  34. #"element"

    >

  35. #

    "etitle"
  36. >Product name:

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

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

  39. ##

  40. through ;## #>"text"

    name=
  41. "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)##
  42. # /p>

    #
  43. >

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

    "Instant transfer test"
  44. >

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

    #
  46. #"button"

  47. class="alisubmit"id="sbumitBtn"

    value =
  48. "Confirm payment"

    >###

    "returnAli">

  49. class

    ="footer">

  50. class

    ="footer-sub">

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

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

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

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

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

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


  57. 支付宝版权所有

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

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

  60. ##

  61. ##

  62. ##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.
  63. [javascript]view plaincopy


##$(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. returnnewResponseEntity(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 plaincopy


  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(inti = 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. //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

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

  43. //Notice:

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

  45. }elseif(trade_status.equals("TRADE_SUCCESS")){

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

  47. #//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

  48. # 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
  49. ###

    //Note:
  50. # Notification of the transaction status

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

  52. flg = hysWebMeetingAliService.changeOrderAndAliStatusSuccess(out_trade_no);

  53. #

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

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

  56. "success";

  57. ## }
  58. else

    {

  59. ///////////////////////////////////////////////////// /////////////////////////////////////////

  60. ## }
  61. else

    {

    //Verification failed
  62. ##

    //out.print("fail");

  63. return"fail";

  64. ## }
  65. }

  66. 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 plaincopy


    1. # @RequestMapping("returnUrl")

    2. publicModelAndView returnUrl(HttpServletRequest request){

    3. ModelAndView mv =

      newModelAndView("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(inti = 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);

  67. ##//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) //

  68. ##

  69. # // Calculate the notification verification results

  70. #Boolean

    # Verify_result = Alipaynotify.verify (Params)

  71. if(verify_result){//Verification successful

  72. ##//////////////////////////////////// ///////////////////////////////////////////////////// //////

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

    ##
  75. (trade_status.equals(

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

  76. ##//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

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

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

  79. #// out.println("Verification successful
    ");
  80. ## Reference)--

  81. /////////////////////////////////////////////////// /////////////////////////////////////////////

  82. ##

    //This page can be used for page art editing

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

  84. }

  85. ;

  86. }

    5. Summary:

  87. 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.
  88. 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 plaincopy

##// 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 plaincopy


    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 plaincopy


    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