Last active
February 10, 2022 09:31
-
-
Save ckhung/4558dec03460d34b431e78ce541f36ba to your computer and use it in GitHub Desktop.
PTX (公共運輸整合資訊流通服務平臺) 的 php 查詢範例
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
<?php | |
# PTX (公共運輸整合資訊流通服務平臺) 的 php 查詢範例 | |
# 詳見: https://newtoypia.blogspot.tw/2018/01/ptx-bash-php.html | |
# 使用方式: | |
# php ptx-example.php 'https://ptx.transportdata.tw/MOTC/v2/Bus/DisplayStopOfRoute/City/Taichung/151?%24format=JSON' | |
# 或 | |
# php ptx-example.php 'https://ptx.transportdata.tw/MOTC/v2/Bus/DisplayStopOfRoute/City/Taichung/151?%24format=JSON' 'Thu, 10 Feb 2022 09:07:10 GMT' | |
# 本程式不需要任何外加套件; 但關於 「如何保護私密資訊」, 請見 | |
# http://phpsec.org/projects/guide/3.html | |
# 的 "PHP Cookbook" 那一段 | |
# 以下只供測試用; 當然不要把你自己真實的 id 跟 key 公開貼在程式碼裡面! | |
$_SERVER['PTX_ID'] = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'; | |
$_SERVER['PTX_KEY'] = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'; | |
$ARG_REQUEST = $argv[1]; | |
if ($argc >= 3) { | |
$ARG_TIME = $argv[2]; | |
} else { | |
$ARG_TIME = gmdate('D, d M Y H:i:s') . ' GMT'; | |
} | |
$signature = base64_encode(hash_hmac("sha1", "x-date: $ARG_TIME", $_SERVER['PTX_KEY'], true)); | |
$opts = [ | |
"http" => [ | |
"method" => "GET", | |
"header" => | |
'Authorization:hmac username="' . $_SERVER['PTX_ID'] . '", algorithm="hmac-sha1", headers="x-date", signature="' . "$signature\"\n" . | |
"x-date:$ARG_TIME\n", | |
"Accept-Encoding: gzip, deflate\n", | |
] | |
]; | |
$ret = file_get_contents( $ARG_REQUEST, false, stream_context_create($opts) ); | |
echo $ret; | |
?> | |
哦, 謝謝! 原來 x-date header 後面不能有空格、 日期要用兩位數 (例如今天是 04 Feb)
我也是弄了很久最後找他們客服
他們自己查很久,其實官網也隻字未提哈哈
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我創建了一個Fork修正code會有例外異常的部分