1 of 14

每天五分鐘

LINE API 輕鬆上手 #27

LINE也可以做金流

2019@RenZhou

LINE Pay 將訂單推到線上 (API v3)

2 of 14

本篇以v3版本API來做教學

如果發現跟其他網路文章內容不同

純屬正常現象

3 of 14

先來搞定API的Header

3

4 of 14

先從產生 UUID (Universally Unique Identifier) 開始做起

一樣用 node.js 來操作 ,先安裝 uuid4 的插件

4

npm i -s uuid4

const uuid = require('uuid4')

// 直接印出來

console.log(uuid())

// 輸出長這樣

504ac11a-1888-4410-89b2-75382fef61b3

5 of 14

再來看看這個 HMAC Base64 簽章的文件說明

呃...對初學者來說這個加密簽章是有點太難了,這也是v3跟v2差異的主要地方

5

6 of 14

怎麼做 POST 的 HMAC Base64 簽章

根據官方文件的簽章公式:

Signature = Base64(HMAC-SHA256(Your ChannelSecret, (Your ChannelSecret + URI + RequestBody + nonce)))

簽章 = 轉成base64 ( HMAC-SHA256加密(金鑰, 內文))

Your ChannelSecret: 你的頻道密鑰

URI:這邊是指所呼叫的API網址,像是建立訂單的就是 ”/v3/payments/request”

RequestBody:訂單的內容

nonce: 剛剛的UUID

6

7 of 14

安裝 crypto-js

一樣也是透過npm來安裝

7

npm i -s crypto-js

const crypto = require('crypto-js')

// 裝好記得要引入

8 of 14

準備簽章所需資料

把簽章合成公式的資料準備好

8

let key = 'bf3f9cbd014aa87a*49f1b49**99fca0d'

let nonce = uuid()

let requestUri = '/v3/payments/request'

let order = { 放上前面我們產的訂單JSON }

9 of 14

製作簽章

準備好就來合成!

這樣我們就拿到加密後的 HMAC Base64的簽章了

9

let encrypt = crypto.HmacSHA256(key + requestUri + JSON.stringify(order) + nonce, key)

// 然後再轉成Base64

let hmacBase64 = crypto.enc.Base64.stringify(encrypt)

10 of 14

那怎麼上傳?

11 of 14

安裝Axios

安裝 axios 插件

11

npm i -s axios

const axios = require('axios')

// 裝好記得要引入

12 of 14

設置Headers

將文件所要求的參數填上

12

let configs = {

headers: {

'Content-Type': 'application/json',

'X-LINE-ChannelId': 161361****,

'X-LINE-Authorization-Nonce': nonce,

'X-LINE-Authorization': hmacBase64

}

}

13 of 14

將訂單送出

然後直接打post出去吧 !!

13

axios.post('https://sandbox-api-pay.line.me/v3/payments/request', order, configs).then(res => {

console.log(res.data)

})

14 of 14

伺服器回傳資料

成功會收到這樣的訊息

14