In this article, I will briefly introduce the use of Alipay sandbox in node.
1. Start
- First register Alipay open platform account: https://open.alipay.com/
- After successful login, click to enter the management center
- After entering successfully, select the console option, and then click R & D service to enter.
- Wait in the sandbox application interface and come back later
2. Generate key
-
It is also necessary to download an application to generate Alipay payment key. https://opendocs.alipay.com/common/02kipl , there are two versions of window s and mac, which can be downloaded and installed on your own computer (just click Next and select a folder to install)
-
After installation, go to the following page:
-
Choose the most commonly used RSA2 encryption algorithm, which is an algorithm invented by MIT and has not been broken through in decades. Then there are two choices: pkcs8 (for Java) and pkcs1 (for non Java). Because I want to demonstrate with node, I don't use Java, and I don't install the Java environment, I choose the second pkcs1 (for non Java).
-
Click generate key to generate public key and private key.
-
Then click the copy public key button to return to the sandbox environment interface and select the option of user-defined key in the development information. Then click the button behind the RSA2 key (recommended).
-
On the pop-up signature management page, select the public key option, paste the public key in the application that just generated the key into the following input box, and then click Save settings.
-
Adding the key is complete.
3. Initialize project
Here is the first official document to Alipay: https://www.yuque.com/chenqiu/alipay-node-sdk/config-sdk , you can save it and have a look when you want to study in the future.
- Create a new folder and open it with an editor
- First initialize the whole project, open the control panel under the root directory of the folder, and enter npm init -y to initialize the whole folder.
- Then download a very important module, which is Alipay's SDK, and input the command: npm install alipay-sdk -S.
- Because the node i will write later will use the express framework, I will install the express framework again: npm install express -S
4. Code writing
Here I will post the complete code, and I will explain each piece of information to be used
//Introducing alipay sdk module const AliPaySdk = require('alipay-sdk').default //Introducing Alibaba pay form module const AlipayForm = require('alipay-sdk/lib/form').default //Introducing express framework const express = require('express') // Instantiation framework const app = express() // Middleware introducing framework const router = express.Router() // mount app.use('/api', router) //Initialize alipay configuration const alipaySdk = new AliPaySdk({ appId: '', // Own id gateway:"https://openapi.alipaydev.com/gateway.do, / / this is Alipay's official website sandbox test gateway. privateKey: "", // Apply private key alipayPublicKey: "" // Alipay public key }) // Server send request router.get('/pay', async (req, res) => { // Instantiate AlipayForm const formData = new AlipayForm() // The following is the test code of the official website formData.setMethod('get') formData.addField('returnUrl', 'http://www.baidu.com '); / / successful payment callback formData.addField('bizContent', { outTradeNo: Math.random(), // order number productCode: 'FAST_INSTANT_TRADE_PAY', // Product code totalAmount: '499999', // Commodity amount subject: 'Cool knowledge', // Title of goods sold body: 'My knowledge' // Content of goods sold }); //results of enforcement const reult = await alipaySdk.exec('alipay.trade.page.pay',{},{ formData: formData }) // Returns data in json format res.json({ code: reult }) }) // Turn on the server to listen app.listen(8080, () => { console.log('success, http://localhost:8080/api/pay') })
I'll introduce it step by step
-
The first is to introduce several important modules
//Introducing alipay sdk module const AliPaySdk = require('alipay-sdk').default //Introducing Alibaba pay form module const AlipayForm = require('alipay-sdk/lib/form').default //Introducing express framework const express = require('express') // Instantiation framework const app = express() // Middleware introducing framework const router = express.Router() // mount app.use('/api', router)
The AliPaySdk and AlipayForm introduced are what we install in Alipay sdk module. Note that the property of.default should be added after each module.
② The last four lines of code are all the things of the express framework I introduced. It doesn't matter if I can't understand it. Just put it here -
The following configuration is more important. This is the initial configuration of Alipay payment. Note that the key words can not be modified by itself, and I will explain the value that I want to input later.
//Initialize alipay configuration const alipaySdk = new AliPaySdk({ appId: '', // Own id gateway:"https://openapi.alipaydev.com/gateway.do, / / this is Alipay's official website sandbox test gateway. privateKey: "", // Apply private key alipayPublicKey: "" // Alipay public key })
AppId: This is the id in the Alipay development platform, copying the id into the appId of the code.
gateway: This is Alipay official payment test network officer.
③ privateKey: This is the private key. Open the application that generated the key before, copy the private key and paste it into the privateKey of the code.
AlipayPublicKey: Alipay public key, open the public key that we set up in the Alipay open platform, then copy the public key and paste it into the alipayPublicKey of the code. -
The following is the request for Alipay payment, which is written in official documents: https://www.yuque.com/chenqiu/alipay-node-sdk/page_api
// Server send request router.get('/pay', async (req, res) => { // Instantiate AlipayForm const formData = new AlipayForm() // The following is the test code of the official website formData.setMethod('get') formData.addField('returnUrl', 'http://www.baidu.com'); // Callback of successful payment formData.addField('bizContent', { outTradeNo: Math.random(), // order number productCode: 'FAST_INSTANT_TRADE_PAY', // Product code totalAmount: '9.89', // Commodity amount subject: 'Good time goods~', // Title of goods sold body: 'Clothes sale' // Content of goods sold }); //results of enforcement const reult = await alipaySdk.exec('alipay.trade.page.pay',{},{ formData: formData }) // Returns data in json format res.json({ code: reult }) })
This is the fixed code. There is no need to change the code. Here I say two points:
① Code formdata. Addfield ('returnurl ',' http://www.baidu.com ', the second parameter is the website to jump to after the payment of goods is successful.
② Code outTradeNo: Math.random(), which is used to write the order number. The order number of each commodity is unique. When the commodity is paid, the order number can no longer be used. Therefore, I use a Math.random number to generate one at a time, which is a random number
5. Pay for goods
-
Open the server node pay.js
-
Open the open server, and then open the page as follows. Copy a string of addresses after the code, and then open it in the page
-
Note that if you open it in the current browser, the following page will appear:
-
This is because the current browser is not safe enough to open. At this time, copy the address of this page, open a new browser (I use Edge browser to open it here), and open this address again
-
Log in to Alipay's account name and password. The account name and password are in the sandbox account of the open platform, because here I use the interface of payment, that is, we are the buyer, so we can find the buyer's information and paste the account number and password into the browser's input box.
-
Then buy the goods.
-
If the account money is not enough, go to the sandbox account to recharge, with a maximum of 999999.99 at a time
-
Of course, it's all money for testing. It's impossible to take it out. You can experience the pleasure of spending money.
6. End
End scattered flowers