iT邦幫忙

2021 iThome 鐵人賽

DAY 20
0
自我挑戰組

從無到有打造驗證碼共享的 Line 機器人系列 第 20

使用 Line Messaging Api 取得 User Profile

今天我們要幫驗證碼小幫手加上取得 User Profile 的功能,這樣能更進一步客製化訊息或紀錄。

流程構思

目的是取得 User Profile 中顯示名稱的部分,並且:

  1. 新增資料在 users sheet 時,將顯示名稱一併寫入
  2. 回應驗證碼的時候多加上針對使用者問好的訊息

所以可以簡單修改流程如下:

  1. 在檢查認證碼有效,綁定身份的同時取得使用者名稱,並回寫到 users sheet 中
  2. 使用者已認證且同意條款後,若輸入訊息為獲取驗證碼時,再次取得使用者名稱回寫到 users sheet 中(因顯示名稱是可以修改的)
  3. 在回應驗證碼訊息加上針對使用者問好的訊息

Line Messaging Api

以往我們要取得使用者的 profile, email, openid 等資訊,必須要經由 Line Login Api,或是 LIFF APP 才能取得。但如果只是要取得 1. 使用者名稱 2. 顯示圖片 3. 狀態訊息 4. 使用語言 這四項資訊的其中一項的話,就可以使用 Line Messaging Api 簡單取得 (還是有限制條件,使用者必須 1. 有加 Line Bot 好友 2. 不是只使用PC版的 Line)

文件

Get profile

Reponse Example:
{
"displayName":"LINE taro",
"userId":"U4af4980629...",
"language":"en",
"pictureUrl":"https://obs.line-apps.com/...",
"statusMessage":"Hello, LINE!"
}

新增 getUserLineProfile

在 replyMessage.gs 新增一個 function getUserLineProfile 如下:

function getUserLineProfile(userId) {
  var response = UrlFetchApp.fetch(`https://api.line.me/v2/bot/profile/${userId}`, {
    'headers': {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN
    },
    'method': 'get'
  });
  return JSON.parse(response);
}

修改 tagVerificationCode.gs

修改 tagVerificationCode 如下:

function tagVerificationCode(target, userId) {
  var sheet = ReadMailAndInsertToGoogleSheet.connectToSheet('verification_code');
  var searchResult = ReadMailAndInsertToGoogleSheet.searchColumnValue(sheet, 'code', target);
  if (searchResult !== -1) {
    var targetRowIndex = searchResult+2;
    var userIdValue = sheet.getRange(targetRowIndex, 2, 1, 1).getValue();
    if (userIdValue.length === 0) {
      var targetRange =  sheet.getRange((searchResult+2), 2, 1, 2);
      targetRange.setValues([[userId, new Date()]]);
      // 新增以下兩行取得 userName
      var userProfile = getUserLineProfile(userId);
      var userName = userProfile.displayName??"";
      // upsertUserInfo 多增加 'name': userName
      upsertUserInfo(userId, {'name': userName, 'is_verifed': true});
      return true;
    }
  }
  return false;
}

修改 getValidationCodeMessage

修改回應驗證碼的 Message Object,加上針對使用者問好的回應

function getValidationCodeMessage(userId) {
  var validationCode = ReadMailAndInsertToGoogleSheet.app(userId);
  var userProfile = getUserLineProfile(userId);
  var userName = userProfile.displayName??"";
  upsertUserInfo(userId, {'name': userName});
  return [
    {
      'type': 'text',
      'text': `${userName}您好,以下是驗證碼:`
    },
    {
      'type': 'text',
      'text': validationCode
    }
  ];
}

修改完了記得儲存,然後要管理部署建立新版本發佈,接著就可以在驗證碼小幫手測試結果囉!

測試結果

接著在驗證碼小幫手點擊獲取驗證碼,檢查看看有沒有正確取得顯示名稱並問好
get user profile result

以上~鐵人賽到現在也過了 2/3 了,明天開始就要進入開發 LIFF APP 的部分囉!


上一篇
使用 Template Message 替 Line Bot 加上同意條款的功能(2)
下一篇
用 Line LIFF APP 實現信箱驗證綁定功能(1) - 取得 user email
系列文
從無到有打造驗證碼共享的 Line 機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言