Node.js SDK GitHub 頁面
https://github.com/ECPay/ECPayAIO_Node.js
以上範例僅展示 Node.js SDK 最簡易的作業方式,實務上仍請再依您的 其他設定、專案作業流程……等等自行調整。
一、安裝 SDK
npm install ecpay_aio_nodejs
於專案資料夾安裝 SDK,裝成功後,於 node_modules 資料夾應有 ecpay_aio_nodejs 資料夾
二、專案根目錄新增 app.js
const express = require(“express”);
const ECPayPayment = require(“ecpay_aio_nodejs”);
const options = require(‘./config/ecpay_options.js’);
require(“dotenv”).config();
const options = {
OperationMode: “Test”,
MercProfile: {
MerchantID: `${process.env.MerchantID}`,
HashKey: `${process.env.HASH_KEY}`,
HashIV: `${process.env.HASH_IV}`,
},
IgnorePayment: [],
IsProjectContractor: false,
};
const ecpayInstance = new ECPayPayment(options);
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get(“/”, (req, res) => {
res.send(“ECPay OK”);
});
app.post(“/create-order”, (req, res) => {
const MerchantTradeDate = new Date().toLocaleString(“zh-TW”, {
year: “numeric”,
month: “2-digit”,
day: “2-digit”,
hour: “2-digit”,
minute: “2-digit”,
second: “2-digit”,
hour12: false,
timeZone: “Asia/Taipei”,
});
const base_param = {
MerchantTradeNo: “ecpay” + Date.now(),
MerchantTradeDate: MerchantTradeDate,
TotalAmount: “100”,
TradeDesc: “測試交易”,
ItemName: “測試商品”,
ReturnURL: `https://www.ecpay.com.tw`,
};
const create = ecpayInstance.payment_client.aio_check_out_all(base_param);
res.send(create);
});
app.listen(PORT, () => {
console.log(`伺服器運行於 port ${PORT}`);
});
三、檔案與路徑結構
myProject/
├── app.js
├── node_modules/
│ ├── ecpay_aio_nodejs/
│ ├── express/
│ ├── dotenv/
│ └── … (其他套件)
├── .env
├── package-lock.json
└── package.json
四、環境變數(以測試帳號 3002607 為例)
MerchantID=3002607
HASH_KEY=pwFHCqoQZGmho4w6
HASH_IV=EkRm7iFT261dpevs
五、於本地端執行或部署至網路上
- 本地端執行:node app.js
- 或部署至網路上:以 Render 為例,專案推至 GitHub Repo,Render 開新服務 (Web Service)、匯入 GitHub Repo 並部署。假設 URL 為:https://ecpay-aio-nodejssdk-example.onrender.com
六、呼叫建立訂單
const url=”https://ecpay-aio-nodejssdk-example.onrender.com/create-order“
fetch(url, {
method: “POST”,
headers: {
“Content-Type”: “application/x-www-form-urlencoded”,
Accept: “text/html”,
},
body:””,
})
.then((response) => response.text())
.then((text) => {
console.log(“Response:”, text);
})
.catch((error) => console.error(error));
或是以其他方式呼叫 url
七、回傳
Console 會回傳 HTML 的 <form> 標籤,於前端執行 <form> 將跳轉至全方位金流付款頁面。