Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Time:2021-6-12

Write down, record Alipay payment

demo   Please poke here  ¥https://download.lllomh.com/cliect/#/product/J302659722615829

Sandbox environment (beta) is an auxiliary environment to assist developers in interface function development and main function joint debugging, which simulates the main functions and main logic of some products of open platform. It can be used to understand the environment, combine and debug various interfaces before the product goes online.

Sandbox environment configuration

open  Alipay Developer Center  And log in, Click = > to enter my console (or it may be automatically entered after logging in). It doesn’t need an enterprise account, but it can also be personal

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

In the developer center, click R & D services under development services to enter the sandbox environment page,

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

You can see the basic configuration in the sandbox application.

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Key configuration

Click RSA2 (sha256) key setting,

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

click  Alipay key generator, download the corresponding version of the tool, and then install the tool in the directory without spaces,

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Then click open and click generate key to generate merchant application private key and merchant application public key. Then click Copy public key.

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Back to the sandbox interface, select the public key and paste it in;

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Then you can get the Alipay public key, which will be used in the code.

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

1. Package configuration

alipayUtil.js

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

const AlipaySdk = require('alipay-sdk').default; //  Introducing SDK
const alipaySdk =  new  AlipaySdk({
  Appid: '2021000117615613' // appid generated when creating an application on an open platform
  Signtype: 'RSA2', // signature algorithm, default RSA2
  gateway: ' https://openapi.alipaydev.com/gateway.do The address of] // Alipay gateway needs to be modified when used in sandbox environment.
  The alipayPublicKey: '// / Alipay public key needs to be filled when the result is checked.
  Privatekey: ', // apply private key string
});
module.exports = alipaySdk;

//Formal environment as long as the above is replaced by a formal one

2. Interface definition

Create the form table required by Alipay

 const formData = new AlipayFormData();
    formData.setMethod('get');

Add notice (if necessary)

formData.addField('notifyUrl', ' https://www.baidu.com '); //  The callback address for successful payment must be directly accessible, without parameters

Then there are the required order parameters

formData.addField('bizContent', {
        Outtradeno: OrderID, // the order number of the merchant, which is less than 64 characters, can contain letters, numbers and underscores, and cannot be repeated
        productCode: 'FAST_ INSTANT_ TRADE_ PAY'// sales product code, the product code name signed with Alipay, only supports FAST_ INSTANT_ TRADE_ PAY
        Totalamount: '0.01', // total order amount, in yuan, to two decimal places
        Subject: 'product', // order title
        Body: 'product details' // order description

    });

Then there is the successful callback: Here I have been trapped for a long time:

formData.addField('returnUrl', ' https://opendocs.alipay.com ');// Add it here, not in bizcontent

Finally, submit it to the official website

Const result = alipaysdk. Exec (// result is the URL that can jump to the payment link
        'Alipay. Trade. Page. Pay' // interface for unified billing, ordering and payment page
        {}, // parameters of API request (including public request parameters and business parameters)
        { formData: formData },
    );

Order query (available or not)

/**
 * add shopping cart to submit an order. After Alipay payment, whether the order status is successfully achieved * /
router.post('/api/member/queryOrderAlipay', (req, res) => {
  let orderId=req.body.orderId
  const formData = new AlipayFormData();
  formData.setMethod('get');
  formData.addField('bizContent', {
    orderId
  });
  //Through this interface, we can actively query the order status
  const result = 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 call is successful
        switch(r.trade_status) {
          case 'WAIT_BUYER_PAY':
            res.send(
              {
                "success": true,
                "message": "success",
                "code": 200,
                "timestamp": (new Date()).getTime(),
                "result": {
                  "status":0,
                  "Massage": 'transaction creation, waiting for buyer to pay'
                }
              }
            )
            break;
          case 'TRADE_CLOSED':
            res.send(
              {
                "success": true,
                "message": "success",
                "code": 200,
                "timestamp": (new Date()).getTime(),
                "result": {
                  "status":1,
                  "Massage": 'the unpaid transaction is closed over time, or full refund after payment is completed'
                }
              }
            )
            break;
          case 'TRADE_SUCCESS':
            res.send(
              {
                "success": true,
                "message": "success",
                "code": 200,
                "timestamp": (new Date()).getTime(),
                "result": {
                  "status":2,
                  "Massage": "transaction payment succeeded"
                }
              }
            )
            break;
          case 'TRADE_FINISHED':
            res.send(
              {
                "success": true,
                "message": "success",
                "code": 200,
                "timestamp": (new Date()).getTime(),
                "result": {
                  "status":3,
                  "Massage": 'transaction closed, non refundable'
                }
              }
            )
            break;
        }
      } else if(r.code === '40004') {
        Res.send ('transaction does not exist ');
      }
    })
    .catch(err => {
      res.json({
        MSG: 'query failed',
        err
      });
    });

})

It’s done here. If you successfully return to the address of payment, the front end only needs to get the address and jump to the address to pay. If you succeed, jump to the callback success page

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Interface demonstration

The front end directly requests and gets the address:

goPay() {
            let data = {
                OrderID: 't45212121' // randomly generate the only one on the line. Find this by yourself
            }
            var instance = this.$axios.create({headers: {'content-type': 'application/x-www-form-urlencoded'}});
             //Agent to http://localhost :3000/api/pcpay
            instance.post(`http://localhost:3000/api/pcpay`, this.$qs.stringify(data)).then(res =>{
                this.data=res;
                window.open(res.data.result)
            });

        }

Finally, we can see the effect by scanning the code of sandbox version app

Node.js+vue to achieve Alipay payment (sandbox) full version, pro test available

Results demo

Hope a lot of support, your comments are my motivation, you can leave a message, thank you