星期一, 7月 20, 2026

[GAS] 透過第三方 API 產生 QRCode

在 GAS 上使用 goQR.me 第三方服務,該服務只有兩個 API 可以使用,分別為
該筆記只會紀錄使用 create-qr-code 來產生 QRCode 而已
/**
 * 測試與執行範例:呼叫共用模組並儲存到 Google Drive
 */
function testGenerateQRCode() {
  const myData = "https://workspace.google.com/";
  const mySize = 250; // 將會產生 250x250 的 QR Code
    
  const qrBlob = getQRCodeBlob(myData, mySize);
  
  if (qrBlob) {
    const file = DriveApp.getRootFolder().createFile(qrBlob);
    Logger.log(`✅ QR Code 建立成功!檔案連結:${file.getUrl()}`);
  } else {
    Logger.log("❌ 流程中斷:無法取得 QR Code 圖片。");
  }
}

/**
 * 透過 goQR.me (api.qrserver.com) 產生 QR Code 的共用模組
 * 
 * @param {string} textToEncode - 必填:要轉換為 QR Code 的內容(網址或純文字)
 * @param {number} size - 選填:QR Code 的尺寸,預設為 300 (即 300x300 像素)
 * @returns {GoogleAppsScript.Base.Blob|null} 成功時回傳圖片 Blob,失敗則回傳 null
 */
function getQRCodeBlob(textToEncode, size = 300) {
  if (!textToEncode) {
    Logger.log("❌ 錯誤:未傳入 textToEncode 參數");
    return null;
  }

  // 組合 API 網址 (將單一 size 數值轉換為 api.qrserver.com 所需的 "寬x高" 格式)
  const apiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(textToEncode)}`;
  
  try {
    const response = UrlFetchApp.fetch(apiUrl, {
      muteHttpExceptions: true
    });
    
    // 驗證並回傳 Blob
    if (response.getResponseCode() === 200) {
      const fileName = `QRCode_${new Date().getTime()}.png`;
      return response.getBlob().setName(fileName);
    } else {
      Logger.log(`❌ 產生失敗,API 伺服器回應狀態碼:${response.getResponseCode()}`);
      return null;
    }
  } catch (error) {
    Logger.log(`❌ 執行階段發生例外狀況:${error.message}`);
    return null;
  }
}


沒有留言:

張貼留言