2023-12-07

【LINE Messaging API】以 user id 查詢 user name

  1.  
  2. <php?
  3. date_default_timezone_set('Asia/Taipei');
  4. $sRootDir = $_SERVER['DOCUMENT_ROOT'];
  5. $channelAccessToken = '您的 channel Access Token';
  6. $bodyMsg = file_get_contents('php://input');
  7.  
  8. // LINE 不會幫我們記錄, 所以要自己寫 log
  9. // 這段不是必要, 只是方便自己除錯
  10. $sLogfile = 'log_'.date('Ymd').'.log'; // 指定 log 檔名, 一天一個檔, 檔名格式為: log_yyyymmdd.log
  11. $fp = fopen($sLogfile, "a+");
  12. fwrite($fp , print_r(date('Y-m-d H:i:s').', Recive: '.$bodyMsg."\n", true));
  13. fclose($fp);
  14.  
  15. $obj = json_decode($bodyMsg, true);
  16. $payload = null;
  17. $event = null;
  18.  
  19. foreach ($obj['events'] as &$event)
  20. {
  21. switch($event['type'])
  22. {
  23. // 如果您有在 LINE 官方帳號後台設定 歡迎詞,
  24. // user 加入好友後也會收到
  25. case 'follow':
  26. // user 加入好友後, 程式自己要做的事
  27. $userId = $event['source']['userId'];
  28. $sUsername = getUsername($sUser);
  29. break;
  30. ...
  31. ...
  32. }
  33. }
  34.  
  35. function getUsername($user_id) {
  36. $ch = curl_init();
  37. curl_setopt($ch, CURLOPT_URL, "https://api.line.me/v2/bot/profile/$user_id");
  38. curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json',
  39. 'Authorization: Bearer ' . $GLOBALS['channelAccessToken']
  40. ]);
  41. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
  42. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  43. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  44. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  45. $result = curl_exec($ch);
  46. curl_close($ch);
  47.  
  48. if ($result===false) {
  49. // 查詢失敗,
  50. return 'NG';
  51. }
  52.  
  53. $data = json_decode($result, true);
  54. return $data["displayName"];
  55. }
  56. ?>
  57.  

沒有留言:

張貼留言