- <php?
- date_default_timezone_set('Asia/Taipei');
- $sRootDir = $_SERVER['DOCUMENT_ROOT'];
- $channelAccessToken = '您的 channel Access Token';
- $bodyMsg = file_get_contents('php://input');
- // LINE 不會幫我們記錄, 所以要自己寫 log
- // 這段不是必要, 只是方便自己除錯
- $sLogfile = 'log_'.date('Ymd').'.log'; // 指定 log 檔名, 一天一個檔, 檔名格式為: log_yyyymmdd.log
- $fp = fopen($sLogfile, "a+");
- fwrite($fp , print_r(date('Y-m-d H:i:s').', Recive: '.$bodyMsg."\n", true));
- fclose($fp);
- $obj = json_decode($bodyMsg, true);
- $payload = null;
- $event = null;
- foreach ($obj['events'] as &$event)
- {
- switch($event['type'])
- {
- // 如果您有在 LINE 官方帳號後台設定 歡迎詞,
- // user 加入好友後也會收到
- case 'follow':
- // user 加入好友後, 程式自己要做的事
- $userId = $event['source']['userId'];
- $sUsername = getUsername($sUser);
- break;
- ...
- ...
- }
- }
- function getUsername($user_id) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, "https://api.line.me/v2/bot/profile/$user_id");
- curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json',
- 'Authorization: Bearer ' . $GLOBALS['channelAccessToken']
- ]);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- $result = curl_exec($ch);
- curl_close($ch);
- if ($result===false) {
- // 查詢失敗,
- return 'NG';
- }
- $data = json_decode($result, true);
- return $data["displayName"];
- }
- ?>
2023-12-07
【LINE Messaging API】以 user id 查詢 user name
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言