iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

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

用 Google App Script 實現發送認證碼的 API

昨天用 Vite 快速打造了輸入信箱獲取認證碼的頁面,但必須搭配發送認證碼的 API 才能繼續完成這個 LIFF APP。因為會用到發信功能,所以還是選擇 Google App Script 作為開發 API 的工具吧!

新建 GAS 專案 Send Mail

將 Read Mail 做為資料庫載入

因為要用到 Read Mail 連接 google sheet 的功能,所以需要將 Read Mail 做為資料庫載入。忘記怎麼操作的話可以參考 將先前的 GAS 專案部署為資料庫

API 規劃

method: POST
postdata: {
    name: string
    mail: string
    token: string(line user id)
}

文件

Gmail App - Send Mail

sendMail.gs

要完成的事情有三件:

  1. 接收 POST Request
  2. 找到未使用的認證碼,押上 user id, 發送日期, 有效時戳
  3. 將步驟2的認證碼寄送到指定的 email

doPost

因為這是要作為 API 使用,所以需要 doPost function 處理 post request

function doPost(e) {
  var message = "fail";
  var input = JSON.parse(e.postData.contents);
  // postdata這幾項必須不為空
  // 也可以多用正則檢驗 mail 是否為有效信箱地址,這邊先略過
  if (input.name && input.mail && input.token) {
    // 取得未使用的認證碼
    var verificationCode = getVerificationCode(input.token, input.name, input.mail);
    if (verificationCode.length > 0) {
      // 組合信件內容文字
      var content = `${input.name} 您好,您的身份認證碼為: ${verificationCode},時效為10分鐘。`;
      // 信件標題採用此種格式,讓使用者一眼就能從標題快速找到認證碼
      sendMail(input.mail, `[${verificationCode}] 驗證碼小幫手的身份認證碼`, content);
      // 回應訊息標為成功
      message = "success";
    }
  }
  // 回應給 client 端的訊息
  return ContentService.createTextOutput(JSON.stringify({message})).setMimeType(ContentService.MimeType.JSON);
}

修改 verification_code sheet

因為我們需要回寫 user id, 發送日期, 有效時戳等資料,所以要修改 verification_code 這張 sheet 格式如下圖:
modify_verification_code_sheet

getVerificationCode

接著實作 取得未使用的認證碼 功能,這邊會用到前面載入的 ReadMail 資料庫去連接 Google Sheet,並且新載入 ReplyMessage 做為資料庫使用 (如果忘記怎麼設定載入,請參考 部署 Google App Script 專案(1))

function getVerificationCode(userId, name, email) {
  var sheet = ReadMail.connectToSheet('verification_code');
  // 取出所有驗證碼的前兩行
  var codes = sheet.getSheetValues(2, 1, (sheet.getLastRow()-1), 2);
  var verificationCode = "";
  codes.some((value, index) => {
    // 逐列搜尋,直到找到 user_id 為空,表示此未被使用過的認證碼
    if(value[1].length === 0) {
      // 取得認證碼的值
      verificationCode = value[0];
      const now = new Date();
      const expireAt = Math.floor(now.getTime() / 1000)+600;
      var rowRange = sheet.getRange((index+2), 2, 1, 4);
      // 在 verification_code sheet 中押上 user id, 發送日期, 有效時戳
      rowRange.setValues([[userId,, now, expireAt]]);
      // 在 users sheet 中押上 user id, name, email
      ReplyMessage.upsertUserInfo(userId, {name, email})
      return true;
    }
  });
  return verificationCode;
}

sendMail

最後就是要實作寄送認證碼信件的功能,使用 GmailApp 即可輕鬆達成

function sendMail(to, title, content) {
  GmailApp.sendEmail(to, title, content, {name: '驗證碼小幫手'});
}

將 Send Mail 部署為 Web App

忘記操作方法的話可以參考 部署 Google App Script 專案(2) & Line Bot 簡單回應訊息

部署好後取得網頁應用程式的網址後,就可以用 PostMan 搭配以下範例 json 試打看看這個 API 是否能正常運作。

{
    "name": "user name",
    "mail": "user email",
    "token": "test token"
}

以上~今天完成了發送認證碼的 API,明天就可以繼續在 LIFF APP 完成串接 API 的步驟!


上一篇
用 Line LIFF APP 實現信箱驗證綁定功能(2) - 使用 Vite 快速打造輸入頁面
下一篇
LIFF APP 串接發送認證碼 API
系列文
從無到有打造驗證碼共享的 Line 機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言