Alipay payment mobile phone browser H5 payment

Preface

  1. Alipay payment - sandbox environment use
  2. Alipay payment - Alipay PC terminal scan code payment
  3. Alipay payment mobile phone browser H5 payment This article

Mobile phone browser payment, users install Alipay APP, mobile phone website payment interface will default call Alipay wallet payment, then run the official Demo test.

This development environment: IDEA + Tomcat8.5 + Alipay sandbox environment

Supplement: call sandbox environment interface, install Alipay APP in sandbox environment, do not know the buddy can refer to the above Alipay payment - sandbox environment use.

Download and run test Demo

Official Demo download link: Mobile Website Payment

The parameters to be adjusted after downloading and importing into IDEA are as follows:

AlipayConfig.java

public class AlipayConfig {
    // Merchant appid
    public static String APPID = "2016101700705301";
    // Private key in pkcs8 format
    public static String RSA_PRIVATE_KEY = "";
    // The path of the asynchronous notification page of the server requires a complete path in the format of http: / / or https: / /. You can't add such custom parameters as? id=123. You must be able to access the page from an external network
    public static String notify_url = "http://ngrok.sscai.club/alipay_trade_wap_pay_java_utf_8_war_exploded/notify_url.jsp";
    // The page Jump synchronization notification page path needs a complete path in the format of http: / / or https: / /, and can't add such user-defined parameters as? id=123. The merchant can be accessed normally through the Internet and can customize the synchronization jump address
    public static String return_url = "http://ngrok.sscai.club/alipay_trade_wap_pay_java_utf_8_war_exploded/return_url.jsp";
    // Request gateway address
    public static String URL = "https://openapi.alipaydev.com/gateway.do";
    // Code
    public static String CHARSET = "UTF-8";
    // Return to format
    public static String FORMAT = "json";
    // Alipay public key
    public static String ALIPAY_PUBLIC_KEY = "";
    // Logging directory
    public static String log_path = "/log";
    // RSA2
    public static String SIGNTYPE = "RSA2";
}

Several main parameters:

  1. appid: merchant appid
  2. RSA? Private? Key: apply private key
  3. ALIPAY_PUBLIC_KEY: Alipay public key, "attention is not applied to public key".

These parameters are not clear. Please have a look Sandbox environment use , or take a look Parameter description of official documents.

After the project is started, it is shown as follows:

Use in Maven project

Use in Maven actually follows Alipay payment - Alipay PC terminal scan code payment The code is very similar. Change the soup without changing the medicine. Change several parameters as follows:

Introduction of Alipay SDK dependency in pom.xml

<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>3.1.0</version>
</dependency>

Configuration can create a class separately, static initialization parameters:

public class AlipayConfig {

    // [sandbox environment] Application ID, your APPID, account receivable account is your APPID corresponding Alipay account.
    public static String app_id = "";

    // [sandbox environment] merchant private key, your RSA2 private key in PKCS8 format
    public static String merchant_private_key = "";

    // [sandbox environment] Alipay public key, check the address: https://openhome.alipay.com/platform/keyManage.htm corresponds to the Alipay public key under APPID.
    public static String alipay_public_key = "";

    // [sandbox environment] the path of the asynchronous notification page of the server needs a complete path in the format of http: / /. You can't add such custom parameters as? id=123. You must be able to access it normally through the external network
    public static String notify_url = "http://ngrok.sscai.club/alipay/aliPayNotify_url";

    // [sandbox environment] page Jump synchronization notice page path requires a complete path in the format of http: / /. You can't add such custom parameters as? id=123. You must be able to access it normally through the Internet
    public static String return_url = "http://ngrok.sscai.club/index.html#/alipay/success";

    // [sandbox environment]
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
}

As for the interface, you can refer to the Demo running above.

Simply look at generating Alipay order interface "no open source SDK".

@Transactional
public String alipayOrder(AlipayOrderRequest alipayOrderRequest) throws AlipayApiException {

    //Get the initialized AlipayClient
    AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
            AlipayConfig.app_id,
            AlipayConfig.merchant_private_key,
            "json",
            AlipayConfig.charset,
            AlipayConfig.alipay_public_key,
            AlipayConfig.sign_type);

    //Set request parameters
    String payType = alipayOrderRequest.getPayType();

    // wap
    AlipayTradeWapPayRequest alipayWapRequest = new AlipayTradeWapPayRequest();
    alipayWapRequest.setReturnUrl(AlipayConfig.return_url);
    alipayWapRequest.setNotifyUrl(AlipayConfig.notify_url);
    
    //Merchant order number, the only order number in the order system of merchant website, required
    String out_trade_no = alipayOrderRequest.getWidOutTradeNo();
    //Payment amount, required
    String total_amount = alipayOrderRequest.getWidTotalFee();
    //Order name, required
    String subject = alipayOrderRequest.getWidSubject();
    //Product description, can be blank
    String body = alipayOrderRequest.getWIDbody();

    //Splicing parameters
    alipayWapRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        + "\"total_amount\":\""+ total_amount +"\","
        + "\"subject\":\""+ subject +"\","
        + "\"body\":\""+ body +"\","
        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

    // Initiate a request
    return alipayClient.pageExecute( alipayWapRequest).getBody();
}

After the mobile website payment interface is called, a Form is returned, that is, the result is actually an Html code, and then the result is passed to the previous call. Here is an example of the returned Form:

  <form name="punchout_form" method="post" action="https://openapi.alipaydev.com/gateway.do?charset=UTF-8&method=alipay.trade.wap.pay&sign=xx&return_url=http%3A%2F%2Fngrok.sscai.club%2Falipay_trade_wap_pay_java_utf_8_war_exploded%2Freturn_url.jsp&notify_url=http%3A%2F%2Fngrok.sscai.club%2Falipay_trade_wap_pay_java_utf_8_war_exploded%2Fnotify_url.jsp&version=1.0&app_id=2016101700705301&sign_type=RSA2&timestamp=2020-01-08+14%3A09%3A58&alipay_sdk=alipay-sdk-java-3.3.0&format=json"> 
   <input type="hidden" name="biz_content" value="{&quot;body&quot;:&quot;Purchase test item 0.01 element&quot;,&quot;out_trade_no&quot;:&quot;20201814955421&quot;,&quot;product_code&quot;:&quot;QUICK_WAP_WAY&quot;,&quot;subject&quot;:&quot;Mobile Website Payment test product&quot;,&quot;timeout_express&quot;:&quot;2m&quot;,&quot;total_amount&quot;:&quot;0.01&quot;}" /> 
   <input type="submit" value="Pay now" style="display:none" /> 
  </form>

How to call it? The following is a piece of test code I used in vue. The front section receives the Form form returned by the back end and submits it:

const div = document.createElement('div');
console.log("I am the data returned by the backend:"+res.result)
div.innerHTML = res.result;
document.body.appendChild(div);
console.log("punchout_form:"+document.forms.punchout_form)
document.forms.punchout_form.submit();

After successful payment, it will be automatically redirected to the configured jump interface, which is controlled by the return ﹣ URL parameter of the backend. Take another look at the callback interface after the payment is successful: "no open source SDK demonstration used":

public String alipaynotify(Model model, HttpServletRequest request) {

    log.info("Alipay asynchronous callback ------------beg-----------");
    String result = "fail";
    //Get feedback from Alipay POST
    /* *
     * Function: asynchronous notification page of Alipay server
     * explain:
     * The following code is only a sample code provided for the convenience of merchant testing. The merchant can write it according to the needs of its website and technical documents, not necessarily use it.
     * This code is for studying and studying Alipay interface only, providing a reference.
     */
    Map<String, String> params=this.getAlipayRequest(request);
    if(params == null || params.size()==0){
        BufferedReader bufferReader = null;
        StringBuilder sb = new StringBuilder();
        try {
            bufferReader = new BufferedReader(request.getReader());

            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(new String(line.getBytes("ISO-8859-1"), "utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String body= null;
        try {
            body = URLDecoder.decode(sb.toString(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        params=UriComponentsBuilder.newInstance().query(body).build().getQueryParams().toSingleValueMap();
    }
    boolean signVerified =false;
    try {
        signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
    } catch (AlipayApiException e1) {
        // TODO Auto-generated catch block
        log.error("Because"+e1.getErrMsg()+"Return to Alipay system results result:fail");
        model.addAttribute("result", "fail");
        return result;
    } //Call SDK to verify signature

    //——Please write your program here (the following code is for reference only)——

        /* During the actual verification process, it is recommended that the merchant must add the following verification:
        1,You need to verify that the out trade no in the notification data is the order number created in the merchant system,
        2,Determine whether the total amount is the actual amount of the order (that is, the amount when the merchant order is created),
        3,Verify that the seller ID (or seller email) in the notice is the corresponding operator of this document (sometimes, a merchant may have multiple seller ID / seller email)
        4,Verify whether the app ﹣ ID is the merchant itself.
        */
    log.error("Alipay verifies the signature:---------------------------------"+signVerified);
    if(signVerified) {//Verification successful
        //Merchant order number
        //Transaction status
        log.info("Alipay asynchronous callback check successful!");
        String trade_status = params.get("trade_status");

        if("TRADE_FINISHED".equals(trade_status)){
            //Judge whether the order has been processed in the merchant website
            //If it has not been processed, find out 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
            //If it has been processed, the business procedure of the merchant will not be executed

            //be careful:
            //When the refund date exceeds the refundable period (such as three months' refundable), Alipay sends the status notification.
            try {
                // Here you can process the operations after the payment is successful, such as modifying the order status, etc
                coding...
                result = "success";
            } catch (Exception e) {
                log.error(e.getMessage());
                result = "fail";
            }
        }else if ("TRADE_SUCCESS".equals(trade_status)){
            //Judge whether the order has been processed in the merchant website
            //If it has not been processed, find out 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
            //If it has been processed, the business procedure of the merchant will not be executed

            //be careful:
            //After payment is completed, the Alipay system sends the transaction status notification.
            try {
                // Here you can process the operations after the payment is successful, such as modifying the order status, etc
                coding...
                result = "success";
            } catch (Exception e) {
                log.error(e.getMessage());
                result = "fail";
            }
        }else{
            result = "fail";
        }
    }else {//Validation failed
        result = "fail";
        //Call trial, write text function to record whether the program is running normally
        //String sWord = AlipaySignature.getSignCheckContentV1(params);
        //AlipayConfig.logResult(sWord);
        log.debug("Alipay asynchronous callback failed");
    }
    log.debug("Result of asynchronous callback returned to Alipay system result:"+result);

    model.addAttribute("result", result);
    log.info("Alipay asynchronous callback  -------------end ------------");
    return result;
}

This method returns two results to Alipay's result on success and fail. From the above point of view, it is not difficult to find that Alipay payment is very simple. Although I put a lot of code on it, the use of open source SDK can reduce and beautify some of them. The following is a screenshot of successful payment.

ok, that's the end of this article. There's no detailed description of interface calls, parameter descriptions, etc. Please refer to the official documents for details: https://docs.open.alipay.com/60/104790/

Download the source code of this article

The official mobile payment website that can be run Demo: https://www.lanzous.com/i8oe2sb

At the end of the article

Blog address: https://www.cgblog.com/niceyoo

If you think this article has something, you may as well pay attention to me. Attention is my greatest encouragement~

After 18 years of graduation, I was confused for a while. Recently I created a public official account to record my growth.

Tags: Programming SDK Mobile JSP Java

Posted on Sun, 03 May 2020 17:56:22 -0400 by alexislalas