Line Pay 自動記帳 n8n workflow

用 Home Assistant 跟 n8n 做了一個 Line Pay 自動記帳小工具——收到 Line Pay 付款通之後,會自動記帳到 Firefly 記帳系統。

整體流程

透過 Home Assistant 的 Android app 的 last notification sensor 收到 notification 後打 n8n,再用 n8n parse 訊息內容、打 Firefly api 來紀錄支出。(iOS 不行,因為 iOS 幾乎沒有工具能偵測到「收到 notification」的 event)

Android 收到通知到打 n8n:

flow

n8n workflow:

n8n workflow

webhook 收到 request 後做 decode 跟 parse Line Pay 通知的訊息內容,把 parse 出來的資料拿去打 Firefly API 建立支出的 transaction,最後傳送通知到 telegram。之所以不用 HA 直接打 Firefly API,是因為打 API 不好處理跟顯示 response,單從 HA 介面難以知道有沒有成功。

Android Home Assistant app 開啟 last notification sensor

開啟後可以在 HA 的「設定」=> 「裝置與服務」=> 「實體」找到 entity:Last notification

HA 的 configuration & automation

configuration.yaml 中的 rest_command action 會打 n8n api:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rest_command:
send_expense_api:
url: "[N8N_WEBHOOK_URL]"
method: POST
headers:
Content-Type: "application/json; charset=utf-8"
Authorization: !secret n8n_token
content_type: "application/json"
payload: >
{
"app": "{{ app_name }}",
"sender": "{{ title }}",
"message": "{{ message | base64_encode }}",
"timestamp": "{{ timestamp }}"
}

HA 會以 UTF-8 編碼後的字串傳送 notification 的內容(例如 LINE\xe9\x8c\xa2\xe5\x8c\x85),這裡有個稍微 tricky 的地方是訊息內容要先經過 base64 encode 再傳送。否則 Line Pay 的通知訊息含有 \n,n8n webhook 接收時似乎會無法正常將訊息內容 parse 為 json,導致 response 422。而且這只能從 HA log 看到 warning log,n8n execution 是連 request 都沒收到,推測是進到 webhook node 前就被回應了。

automations.yaml 的自動化部份:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- id: linepay_auto_record_expense
alias: "LinePay 自動記帳"
trigger:
- platform: state
# last notification 的 entity id
entity_id: sensor.DEVICE_last_notification
condition:
# 只傳送 line 的通知
- condition: template
value_template: >
{{ 'line' in trigger.to_state.attributes['android.appInfo'] }}
action:
- service: rest_command.send_expense_to_n8n_webhook
data:
app_name: "{{ trigger.to_state.attributes['android.appInfo'] }}"
title: "{{ trigger.to_state.attributes['android.title'] }}"
message: "{{ trigger.to_state.attributes['android.text'] }}"
timestamp: "{{ trigger.to_state.attributes.post_time }}"

小結

之所以用 HA app 接通知,沒有別的原因——純粹是本來就有在用 HA,所以要用其他例如 IFTTT 的自動化程式接通知也是可以的~