Sandbox environment (Beta) is an auxiliary environment to assist developers to develop interface functions and coordinate major functions, simulating the main functions and main logic of some products of the development platform. It can be used to understand the environment, compose, and debug various interfaces before the product goes live.

Sandbox environment configuration

Open ‘Alipay Developer Center’ and log in, click -> enter my consoleClick on development Services under Development Services in the Developer center to enter the sandbox environment pageYou can see the basic configuration in the sandbox application

Configure the secret key

Click RSA2(SHA256) key Settings,Click the Alipay key generator to download the corresponding version of the tool. After downloading, install the tool in a directory that does not contain Spaces.Then click open and click Generate key to generate merchant application private key and merchant application public key. Then click Copy public key.Go back to the sandbox, select the public key, and paste the public key you just copied into it.Then you can get alipay public key, the code will be used.

The node API configuration

First install Alipay SDK:

Alipaysdk. exec(method, params, options);Copy the code
  • Method: string type, calling Api, such as Alipay.trade.page.pay;
  • Params: Optional parameters, object structure, Api request parameters;
  • Options: contains
  • ValidateSign: Boolean value. Whether to check the returned value depends on alipay’s public key.
  • FormData: object structure, request parameters of the file upload class interface;
  • Log: object structure. When it exists, the info and error methods are called to write logs.

Since the AlipaySdk API is the same object each time it is called, the object only needs to be instantiated once:

// Alipay. Js is stored in a separate file, which can be imported when needed
const AlipaySdk = require('alipay-sdk').default; / / into the SDK
const alipaySdk = new AlipaySdk({
    appId: 'appId'.// The appId generated when an application is created on the open platform
    signType: 'RSA2'.// Signature algorithm, default RSA2
    gateway: 'https://openapi.alipaydev.com/gateway.do'.// The gateway address of Alipay needs to be changed when used in sandbox environment
    alipayPublicKey: 'public_key'.// Alipay public key, which is required when verifying the result
    privateKey: 'private_key'.// Apply the private key string
});
module.exports = alipaySdk;
Copy the code

To complete the payment, there are several steps,

  • The server side needs to call the payment API Alipay. Trade.page.pay to obtain the address of the payment page;
  • The server side needs to call the payment API Alipay. Trade.page.pay to obtain the address of the payment page;

Let’s take a look at the implementation of the server-side interface:

var express = require('express');
var router = express.Router();
const alipaySdk = require('.. /utils/alipay');
const AlipayFormData = require('alipay-sdk/lib/form').default; // Alipay. Trade.page.pay returns the Form Form
router.post('/pcpay'.(req, res) = >{(async() = > {// Calling setMethod and passing get returns a URL that can jump to the payment page
        const formData = new AlipayFormData();
        formData.setMethod('get');
        // Add parameters with addField
        // After the user completes the payment, the Alipay server will notify the merchant system of the payment result as a parameter in the form of a POST request according to the notifY_URL passed in.
        formData.addField('notifyUrl'.'http://www.com/notify'); // Pay successfully callback address, must be directly accessible address, no arguments
        formData.addField('bizContent', {
            outTradeNo: req.body.outTradeNo, // Merchant order number. The value contains a maximum of 64 characters, including letters, digits, and underscores (_) and cannot be repeated
            productCode: 'FAST_INSTANT_TRADE_PAY'.// Sell product code, the product code name signed with Alipay, only FAST_INSTANT_TRADE_PAY is supported
            totalAmount: '0.01'.// Total order amount, in yuan, to two decimal places
            subject: 'goods'.// Order title
            body: 'Merchandise Details'.// Order description
        });        // Add property "returnUrl" if you need to jump to merchant interface after payment.
        const result = await alipaySdk.exec(
            'alipay.trade.page.pay'.// Unified receiving order and payment page interface
            {}, // API request parameters (including "public request parameters" and "business parameters")
            {formData: formData},);        // result is the URL that can jump to the payment link
        res.json({url: result}); }) (); });Copy the code

Then there is the front page, which is relatively simple, that is, click the payment button, initiate a request to the server, get the returned payment page address and jump:

$.ajax({
    method: 'POST'.url: '/alipay/pcpay'.data: {
        outTradeNo }}). Done (function(res) {function(res) {
        window.open(res.url, '_blank');
}).
fail(function (err) {
    console.log(err);
});
Copy the code

If there is no problem with the appeal, we should see a page like this:If you are using a sandbox environment, you must download the sandbox wallet to complete the payment, as shown below:After downloading, use the account provided by the sandbox to log in, free recharge, free consumption, in fact, the sandbox wallet is a number.And then there’s the added point, how does the front end determine if the user has paid. We all know that the front-end means are not trusted, so we cannot rely on the front-end to judge. The only reliable method is to use Alipay. Trade. query in alipay API to check whether the payment has been completed.

The front end can send the order number to the server for inquiry, and the server can query the payment information of the order number to the Alipay server, and determine whether the payment has been completed through the transaction status. The specific server configuration is as follows:

const axios = require('axios');
const alipaySdk = require('.. /utils/alipay');
const AlipayFormData = require('alipay-sdk/lib/form').default;
router.get('/query'.function (req, res) {(async function () {
        const {outTradeNo} = req.query;
        const formData = new AlipayFormData();
        formData.setMethod('get');
        formData.addField('bizContent', {
            outTradeNo
        });        Const result = await alipaysdK. exec(' Alipay. Trade.query ',{}, {formData: formData
        }
    ,        );
    axios({
        method: 'GET'.url: result
    }).then(data= > {
        let r = data.data.alipay_trade_query_response;
        if (r.code === '10000') { // The interface was successfully called
            switch (r.trade_status) {
                case 'WAIT_BUYER_PAY':
                    res.send('Transaction created, waiting for buyer to pay');
                    break;
                case 'TRADE_CLOSED':
                    res.send('Unpaid transactions closed over time, or full refund after payment completed');
                    break;
                case 'TRADE_SUCCESS':
                    res.send('Transaction paid successfully');
                    break;
                case 'TRADE_FINISHED':
                    res.send('Transaction closed and non-refundable');
                    break; }}else if (r.code === '40004') {
            res.send('Transaction does not exist');
        }
    }).catch(err= > {
        res.json({
            msg: 'Query failed',
            err
        });
    });
})();
})
;

Copy the code