提前準備
使用Online API,需要提前準備以下內容。
處理 API credentials
若要呼叫Online API,需在HTTP標頭中代入credentials。 可以在註冊合作商店後,於合作商店中心左側選單[管理付款連結 > 管理連結金鑰]的頁面中取得通訊管道ID和channel secret,並使用該數值生成credentials。
如果未註冊為合作商店,可以申請sandbox帳號取得channel ID和secret進行測試。
如果已經註冊成為合作商店取得channel ID和secret,則無需另行申請,可以立即在sandbox環境中使用它們。
指定credentials的HTTP標頭如下。
X-LINE-ChannelId
X-LINE-Authorization
X-LINE-Authorization-Nonce
X-LINE-ChannelId
標頭中輸入channel ID值,並在X-LINE-Authorization-Nonce
標頭中輸入 UUID v1或v4或時間戳記等nonce值。
X-LINE-Authorization
標頭中輸入的值是HMAC 方法使用channel secret和目標訊息生成的MAC(message authentication code),該值以Base64格式編碼。根據呼叫API的HTTP方法,配置用於MAC生成訊息,如下所示。
HTTP 方法 | MAC 生成訊息 |
---|---|
GET | Channel secret + API 路徑(apiPath ) + 查詢字串(queryString ) + nonce(nonce ) |
POST | Channel secret + API 路徑(apiPath ) + request body + nonce(nonce ) |
以下程式碼範例將credentials代入HTTP標頭中來呼叫Online API。
下面的程式碼範例中,處理交易ID 值時需要
handleBigInteger()
函數。有關交易ID和handleBigInteger()
函數的詳細訊息,請參考交易ID (transaction ID)。
const crypto = require("crypto");
function signKey(clientKey, msg) {
const encoder = new TextEncoder();
return crypto
.createHmac("sha256", encoder.encode(clientKey))
.update(encoder.encode(msg))
.digest("base64");
}
async function requestOnlineAPI({
method,
baseUrl = "https://sandbox-api-pay.line.me",
apiPath,
queryString = "",
data = null,
signal = null,
}) {
const nonce = crypto.randomUUID();
let signature = "";
// 根據不同方式(method)生成MAC
if (method === "GET") {
signature = signKey(
YOUR_CHANNEL_SECRET,
YOUR_CHANNEL_SECRET + apiPath + queryString + nonce
);
} else if (method === "POST") {
signature = signKey(
YOUR_CHANNEL_SECRET,
YOUR_CHANNEL_SECRET + apiPath + JSON.stringify(data) + nonce
);
}
const headers = {
"X-LINE-ChannelId": YOUR_CHANNEL_ID,
"X-LINE-Authorization": signature,
"X-LINE-Authorization-Nonce": nonce,
};
const response = await fetch(
`${baseUrl}${apiPath}${queryString !== "" ? "&" + queryString : ""}`,
{
method: method,
headers: {
"Content-Type": "application/json",
...headers,
},
body: data ?JSON.stringify(data) : null,
signal: signal,
}
);
const processedResponse = handleBigInteger(await response.text());
return processedResponse;
}