Last active
February 13, 2022 10:02
-
-
Save ckhung/2ea5a26235c90ba90b6aacfb59eb854c to your computer and use it in GitHub Desktop.
PTX (公共運輸整合資訊流通服務平臺) 的 bash 查詢範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# PTX (公共運輸整合資訊流通服務平臺) 的 bash 查詢範例 | |
# 詳見: https://newtoypia.blogspot.tw/2018/01/ptx-bash-php.html | |
# 需要安裝 httpie 及 openssl 等套件 | |
# 使用方式: | |
# ./ptx-example.bash 'https://ptx.transportdata.tw/MOTC/v2/Bus/DisplayStopOfRoute/City/Taichung/151?%24format=JSON' | |
# 或 | |
# ./ptx-example.bash 'https://ptx.transportdata.tw/MOTC/v2/Bus/DisplayStopOfRoute/City/Taichung/151?%24format=JSON' 'Thu, 10 Feb 2022 09:07:10 GMT' | |
# 會印出 (1) http 指令 (2) 查詢結果 | |
# (3) 查詢用的時間戳記及簽章 (在五分鐘內可供再次使用) | |
# 對應到時間戳記 'Thu, 10 Feb 2022 09:07:10 GMT' | |
# 的簽章是 '5U7kKsN5B5cKprSzCk1/h6pwzrY=' | |
export PTX_ID=FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF | |
export PTX_KEY=FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF | |
# 當然不要把你真正的 PTX_KEY 寫在原始碼裡。 請在程式外設定這兩個環境變數。 | |
ARG_REQUEST=$1 | |
ARG_TIME=$2 | |
if [ -z "$ARG_TIME" ] ; then | |
ARG_TIME=$(php -r "print gmdate('D, d M Y H:i:s') . ' GMT';") | |
fi | |
# https://stackoverflow.com/questions/7285059/hmac-sha1-in-bash | |
signature=$(echo -n "x-date: $ARG_TIME" | openssl sha1 -binary -hmac $PTX_KEY | base64) | |
# also see: | |
# https://caligatio.github.io/jsSHA/ | |
set -x | |
http GET $ARG_REQUEST 'Authorization:hmac username="'"$PTX_ID"'", algorithm="hmac-sha1", headers="x-date", signature="'"$signature"'"' "X-Date:$ARG_TIME" 'Accept-Encoding:gzip, deflate' | |
set +x | |
echo | |
# echo "$ARG_TIME signature:$signature" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment