<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dimitris Paxinos on Medium]]></title>
        <description><![CDATA[Stories by Dimitris Paxinos on Medium]]></description>
        <link>https://medium.com/@dpaxinos_35980?source=rss-aa69abc51066------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*er82ZLiTDAl8QJU7</url>
            <title>Stories by Dimitris Paxinos on Medium</title>
            <link>https://medium.com/@dpaxinos_35980?source=rss-aa69abc51066------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:02:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dpaxinos_35980/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to write Google Apps Script logs into Google Sheets]]></title>
            <link>https://medium.com/@dpaxinos_35980/how-to-write-google-apps-script-logs-into-google-sheets-248ed8fb84ce?source=rss-aa69abc51066------2</link>
            <guid isPermaLink="false">https://medium.com/p/248ed8fb84ce</guid>
            <category><![CDATA[google-workspace]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[apps-script]]></category>
            <dc:creator><![CDATA[Dimitris Paxinos]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 18:01:31 GMT</pubDate>
            <atom:updated>2023-11-06T18:01:31.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x64atjHXDPdX7GMC.png" /></figure><h3>Introduction</h3><p>In Google Apps Script, the ability to track and record actions, errors, and performance metrics is crucial for both developers and users. However, the <a href="https://developers.google.com/apps-script/guides/logging">built-in logging mechanisms</a> often fall short regarding accessibility and ease of use. This is where Local Google Apps Script Logging comes into play, offering a streamlined and integrated approach to capturing script activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*g8T3RCQz1fvMaipT.png" /></figure><h3>Watch the Video Tutorial</h3><p>For a comprehensive visual guide, watch our video tutorial. If you prefer, you can also watch it directly on YouTube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyGQmfHAUfcM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyGQmfHAUfcM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyGQmfHAUfcM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc386f4b02667d496b3cfd081562e85f/href">https://medium.com/media/fc386f4b02667d496b3cfd081562e85f/href</a></iframe><h3>Why Local Google Apps Script Logs Matters</h3><p>Local logging ensures that logs are easily accessible within a Google Sheet, providing a persistent and organized record of script activity. This is especially beneficial for scripts that are frequently executed or shared across teams, as it allows for immediate access to logs without navigating away from the workspace.</p><h3>Introducing LocalLogger for Enhanced Logging</h3><h3>Overview of the Localogger Class</h3><p>As seen in the <a href="https://apptivasoftware.com/blog/creating-a-settings-section-in-google-sheets-apps-script-projects/">Settings class implementation</a> covered in a previous blog post, I love creating components that can be reused across different projects. This is the exact approach we followed here as well.</p><p>Localogger is a custom class that extends the basic logging functionality in Google Apps Script. It allows developers to log messages directly into a Google Sheet, categorizing them by severity levels for better clarity. It includes a notification system sending email alerts in case of errors or critical issues.</p><h3>Key Features</h3><p><strong>Optional Custom Sheet for Logging</strong></p><ul><li>Ability to provide a specific Google Sheet for logging or default to a ‘Logs’ sheet if none is provided.</li><li>Enhances flexibility and allows logs to be organized in a dedicated sheet, separate from other data.</li></ul><p><strong>Configurable Logging Levels</strong></p><ul><li>Define severity levels (INFO, WARNING, ERROR, DEBUG) to categorize log messages.</li><li>Set a notification threshold to control which logs trigger email alerts.</li></ul><p><strong>Customizable Email Notifications</strong></p><ul><li>Configure an email address to receive alerts for logs of a certain severity.</li><li>Automated email alerts for logs that meet or exceed a set severity level, such as ERROR.</li></ul><p><strong>Dynamic Log Placement</strong></p><ul><li>Choose to place new log entries at the top or bottom of the Google Sheet.</li><li>Ensures the most recent log entries are easily accessible and visible.</li></ul><p><strong>Severity-Based Color Coding</strong></p><p>Log entries are color-coded based on severity for quick visual identification:</p><ul><li>INFO: Light green</li><li>WARNING: Light yellow</li><li>ERROR: Light red</li><li>DEBUG: Light blue</li></ul><p><strong>User Information in Logs</strong></p><ul><li>Capture and include the email or session ID of the user executing the script.</li><li>Provides traceability and is useful for scripts run by multiple users.</li></ul><p><strong>Automated Log Sheet Setup</strong></p><ul><li>If no custom sheet is provided, automatically create a ‘Logs’ sheet with headers.</li><li>Format headers in bold for clear separation and organization of log entries.</li></ul><pre>const Severity = {<br>  INFO: &#39;INFO&#39;,<br>  WARNING: &#39;WARNING&#39;,<br>  ERROR: &#39;ERROR&#39;,<br>  DEBUG: &#39;DEBUG&#39;<br>};<br><br>/**<br> * Class representing a logger with functionality to log messages to a Google Spreadsheet.<br> */<br>class LocalLogger {<br>/**<br>   * Creates a logger instance.<br>   * @param {string} emailAddress - The email address to send notifications to. (Leave blank to disable notifications)<br>   * @param {boolean} logAtTop - Determines if logs should be placed at the top of the spreadsheet.<br>   * @param {GoogleAppsScript.Spreadsheet.Sheet} [logSheet] - Optional. The sheet to log messages to.<br>   */<br>constructor(emailAddress = null, logAtTop = false, notifyLevel = Severity.ERROR, logSheet = null) {<br>  this.spreadsheet = SpreadsheetApp.getActiveSpreadsheet();<br>  this.logSheet = logSheet || this.spreadsheet.getSheetByName(&#39;Logs&#39;);<br>  this.logAtTop = logAtTop;<br>  this.notifyLevel = notifyLevel; // Notify when an ERROR or more severe log is added<br>  this.emailAddress = emailAddress; // Email address for sending notifications<br>}<br><br>/**<br> * Initializes the logger by creating a Logs sheet if it does not exist.<br> */<br>init() {<br>  if (!this.logSheet) {<br>    this.logSheet = this.spreadsheet.insertSheet(&#39;Logs&#39;);<br>    this.logSheet.appendRow([&#39;Timestamp&#39;, &#39;Severity&#39;, &#39;Message&#39;, &#39;User/Session&#39;]);<br>    this.logSheet.getRange(&#39;1:1&#39;).setFontWeight(&#39;bold&#39;);<br>  }<br>}<br><br><br>  /**<br>   * Logs a message to the spreadsheet.<br>   * @param {string} message - The message to log.<br>   * @param {string} [severity=Severity.INFO] - The severity of the log message.<br>   */<br>  log(message, severity = Severity.INFO) {<br>    const userEmail = Session.getActiveUser().getEmail(); // May return empty in some contexts due to privacy<br>    const sessionID = Session.getTemporaryActiveUserKey(); // Alternative session identifier<br>    const userInfo = userEmail || sessionID;<br>    const timestamp = new Date();<br>    const formattedTimestamp = Utilities.formatDate(timestamp, Session.getScriptTimeZone(), &quot;yyyy-MM-dd HH:mm:ss&quot;);<br>    const logEntry = [formattedTimestamp, severity, message, userInfo];<br><br>    try {<br>      this.writeLogEntry(logEntry);<br><br>      // Trigger notification if severity is high<br>      if (this.shouldNotify(severity)) {<br>        this.notify(message, severity);<br>      }<br>    } catch (e) {<br>      // Handle the error, e.g., log to a different place or send an email<br>      Logger.log(&#39;Failed to log message: &#39; + e.toString());<br>    }<br>  }<br><br>/**<br> * Writes a single log entry to the spreadsheet.<br> * @param {Array} entry - The log entry to write.<br> */<br>writeLogEntry(entry) {<br>  let range;<br>  if (this.logAtTop) {<br>    // Insert a new row after the headers for the new log entry<br>    this.logSheet.insertRowAfter(1);<br>    range = this.logSheet.getRange(2, 1, 1, 4); // Now the new entry will be on the second row<br>  } else {<br>    // Append at the bottom of the log sheet<br>    const lastRow = this.logSheet.getLastRow();<br>    range = this.logSheet.getRange(lastRow + 1, 1, 1, 4);<br>  }<br>  range.setValues([entry]);<br>  range.setFontWeight(&#39;normal&#39;);<br>  this.applyLogColor(range, entry[1]); // Apply color based on severity<br>}<br><br> /**<br>   * Sends a notification for a log entry.<br>   * @param {string} message - The log message.<br>   * @param {string} severity - The severity of the log message.<br>   */<br>  notify(message, severity) {<br>    <br>    if(!this.emailAddress) {<br>      Logger.log(&#39;No email address specified for notifications&#39;);<br>      return;<br>    }<br><br>    try {<br>      const subject = `New ${severity} log entry`;<br>      const body = `A new log entry with severity ${severity} was added: \n ${message}`;<br>      MailApp.sendEmail(this.emailAddress, subject, body); // Use the stored email address<br>    } catch (e) {<br>      Logger.log(&#39;Failed to send notification: &#39; + e.toString());<br>    }<br>  }<br><br>  /**<br>   * Determines if a log entry should trigger a notification based on its severity.<br>   * @param {string} severity - The severity of the log entry.<br>   * @return {boolean} True if notification should be sent, false otherwise.<br>   */<br>  shouldNotify(severity) {<br>    const severityOrder = [Severity.DEBUG, Severity.INFO, Severity.WARNING, Severity.ERROR];<br>    return severityOrder.indexOf(severity) &gt;= severityOrder.indexOf(this.notifyLevel);<br>  }<br><br>  /**<br> * Applies background color to a log entry based on its severity.<br> * @param {GoogleAppsScript.Spreadsheet.Range} range - The range to apply the background color to.<br> * @param {string} severity - The severity of the log entry.<br> */<br>applyLogColor(range, severity) {<br>  let color = &quot;#FFFFFF&quot;; // Default white background<br>  switch (severity) {<br>    case Severity.INFO:<br>      color = &quot;#D9EAD3&quot;; // Light green<br>      break;<br>    case Severity.WARNING:<br>      color = &quot;#FFE599&quot;; // Light yellow<br>      break;<br>    case Severity.ERROR:<br>      color = &quot;#F4CCCC&quot;; // Light red<br>      break;<br>    case Severity.DEBUG:<br>      color = &quot;#CFE2F3&quot;; // Light blue<br>      break;<br>  }<br>  range.setBackground(color);<br>}<br><br>}</pre><h3>Setting Up LocalLogger</h3><p>To test <strong>LocalLogger</strong> yourself:</p><ol><li>Create a new Google Sheet</li><li>Go to the Apps Script Editor (Extensions –&gt; Google Apps Script Editor.</li><li>Create a new file (called LocalLogger for example) and paste the LocalLogger Implementation</li><li>Now in your main Code file, paste the code snippet below.</li></ol><p>As you can see below, we have LocalLogger’s instantiation and initiation.</p><p><strong>Instantiation</strong></p><p>Upon instantiation, we define:</p><ul><li>The email address the logs should be sent to. If null, no emails will be sent.</li><li>Whether the newest log message should be placed in the first or last row of the sheet</li><li>The minimum severity level that should also trigger an email notification</li><li>The spreadsheet where the logs should be stored in. Feel free to leave it blank if already working within a Google Sheet.</li></ul><p><strong>Initialization</strong></p><p>Within the onOpen() function of the Sheet, we initialize — init() function — our Logger. During initialization, the logger checks for an existing ‘Logs’ sheet and creates one if necessary, complete with headers for ‘<strong>Timestamp</strong>‘, ‘<strong>Severity</strong>‘, ‘<strong>Message</strong>‘, and ‘<strong>User/Session</strong>‘.</p><p>The rest of the snippet shows the different ways to create a log message entry with different severity levels.</p><pre>const notificationEmailAddress = &quot;apptiva.projects@gmail.com&quot;;<br>const showNewestMessageFirst = true;<br><br>const logger = new LocalLogger(notificationEmailAddress, showNewestMessageFirst);<br><br>function onOpen() {  <br>  logger.init();<br>  let ui = SpreadsheetApp.getUi();<br>  ui.createMenu(&#39;Logging&#39;)<br>  .addItem(&quot;Generate Debug Message&quot;, &#39;generateDebugMessage&#39;)<br>    .addItem(&quot;Generate Info Message&quot;, &#39;generateInfoMessage&#39;)<br>    .addItem(&quot;Generate Warning Message&quot;, &#39;generateWarningMessage&#39;)<br>    .addItem(&quot;Generate Error Message&quot;, &#39;generateErrorMessage&#39;)<br>    .addToUi();<br>}<br><br>function generateDebugMessage(){<br>  logger.log(&#39;This is a DEBUG Message&#39;, Severity.DEBUG);<br>}<br><br>function generateInfoMessage(){<br>  logger.log(&#39;This is an INFO Message&#39;, Severity.INFO);<br>}<br><br>function generateErrorMessage(){<br>  logger.log(&#39;This is an ERROR Message&#39;, Severity.ERROR);<br>}<br><br>function generateWarningMessage(){<br>  logger.log(&#39;This is a WARNING Message&#39;, Severity.WARNING);<br>}<br><br>function generateWarningMessage(){<br>  logger.log(&#39;This is a WARNING Message&#39;, Severity.WARNING);<br>}</pre><h3>Local Google Apps Script Logs — Conclusion</h3><p>The enhanced LocalLogger class allows for sophisticated Google Apps Script logs within Google Sheets, complete with severity levels and notification capabilities. By leveraging these features, developers can maintain a high level of awareness and control over their scripts, leading to more reliable and efficient automation.</p><p><strong>Need Help with Google Apps Script Projects?</strong></p><p>At <a href="https://apptivasoftware.com/">Apptiva</a>, we help companies save time and money by automating manual, time-consuming processes and integrating external APIs with a strong focus on the Google Workspace. So, if you have a project in mind, contact us at <a href="/service/mailto:contact@apptivasoftware.com">contact@apptivasoftware.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=248ed8fb84ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Customer Recurring Billing with Stripe and Google Sheets]]></title>
            <link>https://medium.com/@dpaxinos_35980/automate-customer-recurring-billing-with-stripe-and-google-sheets-9913274c932a?source=rss-aa69abc51066------2</link>
            <guid isPermaLink="false">https://medium.com/p/9913274c932a</guid>
            <category><![CDATA[stripe-integration]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[google-workspace]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <dc:creator><![CDATA[Dimitris Paxinos]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 06:35:35 GMT</pubDate>
            <atom:updated>2023-10-19T06:35:35.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qgp_glEirDeTzFis.png" /></figure><h3>Introduction</h3><p>Navigating through the maze of managing both offline and online sales can be a daunting task for businesses. The complexities of handling customer data, setting up recurring billing, and ensuring timely payment collection often pose significant challenges. What if there was a way to streamline this entire process, ensuring you can focus more on growing your business and less on administrative tasks? In this comprehensive guide, discover a seamless method to automate customer recurring billing with Stripe and Google Sheets, providing you with a simplified, automated, and efficient billing system.</p><p>Whether you’re a seasoned business owner or a budding entrepreneur, this step-by-step walkthrough will equip you with the tools to transition smoothly from manual billing to a streamlined online recurring payment system, enhancing both your business operations and customer experience.</p><h3>Watch the Video Tutorial</h3><p>For a comprehensive visual guide, watch our video tutorial. If you prefer, you can also watch it directly on YouTube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fm4r2hCpCDL4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm4r2hCpCDL4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fm4r2hCpCDL4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/76bc0b7e89b1eb7b9e7213b9cbbdc0c7/href">https://medium.com/media/76bc0b7e89b1eb7b9e7213b9cbbdc0c7/href</a></iframe><h3>Overview of the Customer Recurring Billing Solution</h3><p>Utilizing Google Sheets as a centralized database, we can input vital customer details effortlessly. An integrated Apps Script automates the creation of Stripe customer profile subscription setups and dispatches payment links via email. You can see the automated 4-step process in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k5OILAuVgO4wPn6M.png" /></figure><h3>Creating a Stripe Subscription Product</h3><p>Before diving into the automation with Google Sheets and Apps Script, setting up a subscription product in Stripe is essential.</p><p><strong>Prefer working on a product in Stripe’s “Test mode” first.</strong></p><p>In order to create a subscription product, follow these steps:</p><ol><li>Log into Your Stripe Dashboard</li><li>Navigate to the ‘Products’ Section</li><li>Create a New Product by clicking the ‘+ Add product’ button.</li><li>Input Product Details. Only the name is required.</li><li>Set up pricing to “Recurring” setting the Billing Period to “Monthly”.</li><li>Save the Product</li></ol><h3>Access the Google Sheet Template</h3><p>To follow along with this guide, you can access and copy our <a href="https://docs.google.com/spreadsheets/d/1Cw7PpZLyVmwes3MdY8idWXCwQX7bxAPlZMcEgyooYZs/copy">Google Sheet Template here</a>.</p><h3>Detailed Walkthrough of the Google Sheet Solution</h3><p>Once we are done creating the Product, let’s move on to our Google Sheet, which consists of two tabs: <a href="https://apptivasoftware.com/blog/creating-a-settings-section-in-google-sheets-apps-script-projects/">Settings</a> and Subscription Data.</p><h3>Settings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p6jGkiKOhcbq7oJ4.png" /></figure><p>In the Settings tab, we have to fill in:</p><ul><li>Our <a href="https://support.stripe.com/questions/locate-api-keys-in-the-dashboard">Stripe API Key</a> and press the “Set API Key” to store the key in the Script Properties. <strong>Please remove the Stripe API Key from the Settings tab after that.</strong></li><li>The default trial period duration of our subscription, if any, in days</li><li>The ID of the Subscription Product we would like to use. This ID can be found in the URL of the product details page in our Stripe dashboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*SfUwmI51S3QH3uPU" /></figure><h3>Customer Data to automate Customer Recurring Billing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4qgfiftrQMaQPK9-.png" /></figure><p>The Subscription Data tab will be used for entering the customer information:</p><ul><li><strong>Full Name</strong></li><li><strong>Email</strong></li><li><strong>Address</strong></li><li><strong>Country</strong></li><li><strong>City</strong></li><li><strong>Postal Code</strong></li><li><strong>Subscription Duration (Months)</strong></li><li><strong>Trial Period (Days) [Optional Field]:</strong> This can be set if we want to override the default value set in the Settings tab.</li><li><strong>Monthly Amount:</strong> This is the monthly amount the user will be charged. Please note that this amount should already be defined in the pricing section of the product.</li><li><strong>Subscription ID (auto-filled later):</strong> The script will automatically add the subscription ID here once it is created</li><li><strong>Subscription Status (auto-filled later):</strong> This will be set to “CREATED” after the script has processed the respective row.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mFdTtvY2zqinoXKm.png" /></figure><h3>Triggering the Script</h3><p>The script is triggered by the “Create Subscription” menu item on the top right corner of the Google Sheet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3EnUgDCUh5uvysLP.png" /></figure><p>When the script runs, it selects all rows with an empty subscription status.</p><p>For every such row, the script:</p><ul><li>Creates a new customer and subscription in Stripe. The picture below shows a sample subscription with a 4-day trial period and a 4-month duration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0NBnP4p0DRomH_Pv.png" /></figure><ul><li>Sends an email with the checkout link to the new subscriber with a link to the checkout page:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*RZ1xPe4Rlmh1y_K8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BxRtm47YfkrO6xUe.png" /></figure><p>Once the subscriber has paid for the subscription, it appears as active in Stripe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cfvj2iZEMvW9id4D.png" /></figure><h3>Access the Complete Code on GitHub</h3><p>For a hands-on look at the entire codebase and to experiment with it yourself, access our <a href="https://github.com/dimitrispaxinos/stripe-subscriptions-with-sheets">GitHub Repository here</a>. It contains all the necessary scripts and detailed documentation to help you set up and customize the solution to your needs.</p><h3>Google Apps Script Implementation Details</h3><p>I always like to split the Google Apps Script code into separate modules according to the specific responsibility of each module.</p><p>Splitting code into modules offers several advantages. It promotes a clear separation of concerns, allowing each module to focus on specific tasks, enhancing readability and maintainability.</p><p>Modules can be reused across different parts of an application or even in separate projects, providing consistency and reducing redundancy.</p><p>Therefore, we have the following two modules in this case:</p><h3>Settings Class</h3><p>This class manages settings stored in a Google Sheet named ‘Settings’ or in the Script Properties. If you want to see in detail how the Settings class is implemented, feel free to read the respective blog post <a href="https://apptivasoftware.com/blog/creating-a-settings-section-in-google-sheets-apps-script-projects/">here</a>.</p><h3>StripeApiClient Class</h3><p>The StripeApiClient class serves as a client to interact with the Stripe API.</p><p>It provides methods to:</p><ul><li>Create a new customer in Stripe.</li><li>Create a subscription for a customer.</li><li>Create a checkout session for a customer.</li><li>Fetch a list of customers, products, and prices from Stripe.</li></ul><p>And more…</p><pre>/**<br> * Stripe API Client for handling various Stripe operations.<br> */<br>class StripeApiClient {<br>    constructor(apiKey) {<br>        this.apiKey = apiKey;<br>    }<br><br>    /**<br>     * Private method to make requests to the Stripe API.<br>     * @param {string} endpoint - The Stripe API endpoint.<br>     * @param {string} method - The HTTP method (e.g., &#39;post&#39;, &#39;get&#39;).<br>     * @param {object} data - The data payload for the request.<br>     * @returns {object} - The parsed JSON response from the Stripe API.<br>     */<br>    _makeRequest(endpoint, method, data) {<br>        let headers = {<br>            &quot;Authorization&quot;: &quot;Bearer &quot; + this.apiKey,<br>            &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;<br>        };<br><br>        let options = {<br>            &quot;method&quot;: method,<br>            &quot;headers&quot;: headers,<br>            &quot;payload&quot;: data<br>        };<br><br>        let response = UrlFetchApp.fetch(&#39;https://api.stripe.com/v1/&#39; + endpoint, options);<br>        return JSON.parse(response.getContentText());<br>    }<br><br>    /**<br>   * Create a new customer in Stripe.<br>   * @param {string} name - The customer&#39;s name.<br>   * @param {string} email - The customer&#39;s email address.<br>   * @param {string} address - The customer&#39;s address.<br>   * @param {string} country - The customer&#39;s country.<br>   * @param {string} city - The customer&#39;s city.<br>   * @param {string} postalCode - The customer&#39;s postal code.<br>   * @returns {object} - The created customer object.<br>   */<br>    createCustomer(name, email, address, country, city, postalCode) {<br>        let customerData = {<br>            &quot;name&quot;: name,<br>            &quot;email&quot;: email,<br>            &quot;address[line1]&quot;: address,<br>            &quot;address[city]&quot;: city,<br>            &quot;address[postal_code]&quot;: postalCode,<br>            &quot;address[country]&quot;: country<br>        };<br><br>        return this._makeRequest(&#39;customers&#39;, &#39;post&#39;, customerData);<br>    }<br><br>    /**<br>   * Create a subscription for a customer.<br>   * @param {string} customerId - The ID of the customer.<br>   * @param {string} priceId - The ID of the price.<br>   * @param {number} duration - The duration of the subscription in months.<br>   * @param {number} trialDays - The trial period in days.<br>   * @returns {object} - The created subscription object.<br>   */<br>    createSubscription(customerId, priceId, duration, trialDays) {<br>        let currentDate = new Date();<br>        currentDate.setMonth(currentDate.getMonth() + parseInt(duration));<br>        let cancelAtTimestamp = Math.floor(currentDate.getTime() / 1000);<br><br>        let subscriptionData = {<br>            &quot;customer&quot;: customerId,<br>            &quot;items[0][price]&quot;: priceId,<br>            &quot;cancel_at&quot;: cancelAtTimestamp.toString(),<br>          <br>        };<br><br>        if(trialDays &gt; 0) {<br>            let trialEndDate = new Date();<br>            trialEndDate.setDate(trialEndDate.getDate() + trialDays);<br>            let trialEndTimestamp = Math.floor(trialEndDate.getTime() / 1000);<br><br>            subscriptionData[&quot;trial_end&quot;] = trialEndTimestamp.toString();<br>        }<br><br>        return this._makeRequest(&#39;subscriptions&#39;, &#39;post&#39;, subscriptionData);<br>    }<br><br>    /**<br>     * Create a checkout session for a customer.<br>     * @param {string} priceId - The ID of the price.<br>     * @param {string} customerId - The ID of the customer.<br>     * @param {string} [success_url=&quot;https://your-success-url.com&quot;] - The URL to redirect to upon successful checkout.<br>     * @param {string} [cancel_url=&quot;https://your-cancel-url.com&quot;] - The URL to redirect to upon checkout cancellation.<br>     * @returns {object} - The created checkout session object.<br>     */<br>    createCheckoutSession(priceId, customerId, payment_method_type = &quot;card&quot;, success_url = &quot;https://your-success-url.com&quot;, cancel_url = &quot;https://your-cancel-url.com&quot;) {<br>        let sessionData = {<br>            &quot;customer&quot;: customerId,<br>            &quot;payment_method_types[]&quot;: payment_method_type,<br>            &quot;line_items[0][price]&quot;: priceId,<br>            &quot;line_items[0][quantity]&quot;: &quot;1&quot;,<br>            &quot;mode&quot;: &quot;subscription&quot;,<br>            &quot;success_url&quot;: success_url,<br>            &quot;cancel_url&quot;: cancel_url<br>        };<br><br>        return this._makeRequest(&#39;checkout/sessions&#39;, &#39;post&#39;, sessionData);<br>    }<br><br>    /**<br>     * Fetch a list of customers from Stripe.<br>     * @returns {object} - The list of customers.<br>     */<br>    fetchCustomers() {<br>        return this._makeRequest(&#39;customers&#39;, &#39;get&#39;, {});<br>    }<br><br>    /**<br>     * Fetch a list of products from Stripe.<br>     * @returns {object} - The list of products.<br>     */<br>    fetchProducts() {<br>        return this._makeRequest(&#39;products&#39;, &#39;get&#39;, {});<br>    }<br><br>    fetchProduct(productId) {<br>        return this._makeRequest(&#39;products/&#39; + productId, &#39;get&#39;, {});<br>    }<br><br>    /**<br>     * Fetch a list of prices for a specific product from Stripe.<br>     * @param {string} product - The ID of the product.<br>     * @returns {object} - The list of prices for the specified product.<br>     */<br>    fetchProductPrices(product) {<br>        return this._makeRequest(&#39;prices?product=&#39; + product, &#39;get&#39;, {});<br>    }<br><br><br>    /**<br>    * Create a new price for a product in Stripe.<br>    * @param {number} unit_amount - The amount for the price.<br>    * @param {string} product - The ID of the product.<br>    * @param {string} currency - The currency for the price.<br>    * @returns {object} - The created price object.<br>    */<br>    createProductPrice(unit_amount, product, currency) {<br>        let priceData = {<br>            &quot;product&quot;: product,<br>            &quot;unit_amount&quot;: unit_amount.toString(),<br>            &quot;currency&quot;: currency,<br>            &quot;recurring[interval]&quot;: &quot;month&quot;<br>        };<br><br>        return this._makeRequest(&#39;prices&#39;, &#39;post&#39;, priceData);<br>    }<br>}</pre><h3>Main Apps Script Logic</h3><p>The main logic is implemented in two main functions:</p><h4>SubscribeCustomers</h4><p>The <strong>subscribeCustomers</strong> function stands out as the main driver. This function begins by validating essential settings like the API key and selected product. It then fetches customer data from the Google Sheet and iterates over each customer to initiate their subscription process using the subscribeCustomer function.</p><h4>SubscribeCustomer</h4><p>The <strong>subscribeCustomer</strong> function handles individual customer subscriptions by creating a customer in Stripe, determining product pricing, and establishing a subscription.</p><p>If successful, a checkout session is created in Stripe, and a checkout link is sent to the customer’s email, allowing them to finalize their subscription.</p><p>These functions essentially automate enrolling customers into a subscription service via Stripe, all managed within a Google Sheet.</p><pre>// Constants for settings labels<br>const SETTINGS_API_KEY_LABEL = &#39;Stripe API Key&#39;;<br>const SETTINGS_SELECTED_PRODUCT_LABEL = &#39;Selected Product&#39;;<br>const SETTINGS_DEFAULT_TRIAL_PERIOD_LABEL = &#39;Default Trial Period (Days)&#39;;<br><br>const MAIN_SHEET_NAME = &#39;Subscription Data&#39;;<br>const CURRENCY = &#39;EUR&#39;;<br><br><br>// Initialize settings and Stripe client<br>let settings = new Settings();<br>let stripeApiKey = settings.getSetting(SETTINGS_API_KEY_LABEL);<br>let stripeClient = new StripeApiClient(stripeApiKey);<br><br><br>/**<br> * Sets the API key in the script properties.<br>*/<br>function setApiKeyToScriptProperties() {<br>  let apiKey = settings.getSetting(SETTINGS_API_KEY_LABEL);<br>  if (!apiKey) {<br>    //notify user that the API key is not set<br>    SpreadsheetApp.getUi().alert(&#39;API Key not set&#39;);<br>    return;<br>  }<br>  settings.setSettingInScriptProperties(SETTINGS_API_KEY_LABEL, apiKey);<br>}<br><br>function onOpen() {<br>  settings.init();<br><br>  let ui = SpreadsheetApp.getUi();<br>  ui.createMenu(&#39;Stripe&#39;)<br>    .addItem(&quot;Create Subscriptions&quot;, &#39;subscribeCustomers&#39;)<br>    .addToUi();<br>}<br><br>/**<br> * Fetches customer data from the active Google Sheet.<br> * @returns {Array} List of customer objects.<br> */<br>function fetchCustomersFromSheet() {<br>  let sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();<br>  let lastRow = sheet.getLastRow();<br><br>  // Assuming the data starts from the second row (considering the first row has headers)<br>  let dataRange = sheet.getRange(2, 1, lastRow - 1, 10);<br>  let customers = dataRange.getValues();<br><br>  let customerList = [];<br><br>  for (const element of customers) {<br>    let customer = {<br>      &quot;name&quot;: element[0],<br>      &quot;email&quot;: element[1],<br>      &quot;address&quot;: element[2],<br>      &quot;country&quot;: element[3],<br>      &quot;city&quot;: element[4],<br>      &quot;postalCode&quot;: element[5],<br>      &quot;months&quot;: element[6],<br>      &quot;trialPeriod&quot;: element[7],<br>      &quot;amount&quot;: element[8],<br>      &quot;subscriptionStatus&quot;: element[8]<br>    };<br><br>    customerList.push(customer);<br>  }<br><br>  return customerList;<br>}<br><br>/**<br> * Fetches or creates a price for a product in Stripe.<br> * @param {number} unit_amount - Amount for the product.<br> * @param {string} product - Stripe product ID.<br> * @param {string} currency - Currency code (e.g., &#39;EUR&#39;).<br> * @returns {string|null} Stripe price ID or null if not found.<br> */<br>function getPrice(unit_amount, product, currency) {<br><br>  let prices = stripeClient.fetchProductPrices(product);<br><br>  for (const element of prices.data) {<br>    if (element.unit_amount == unit_amount &amp;&amp; element.currency.toLowerCase() == currency.toLowerCase()) {<br>      // If a price with the specified unit_amount exists, return its ID<br>      return element.id;<br>    }<br>  }<br><br><br>  return null;<br>}<br><br>/**<br> * Sets a specific field in the Google Sheet based on the provided email.<br> * @param {string} email - Customer&#39;s email.<br> * @param {number} column - Column number to set the value.<br> * @param {string} value - Value to set in the specified column.<br> */<br>function setField(email, column, value) {<br>  let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(MAIN_SHEET_NAME);<br>  let lastRow = sheet.getLastRow();<br><br>  // The data starts from the second row (considering the first row has headers)<br>  let emailRange = sheet.getRange(2, 2, lastRow - 1, 1);<br>  let emails = emailRange.getValues();<br><br>  for (let i = 0; i &lt; emails.length; i++) {<br>    if (emails[i][0] === email) {<br>      sheet.getRange(i + 2, column).setValue(value);<br>      break;<br>    }<br>  }<br>}<br><br>/**<br> * Main function to initiate the subscription process for customers.<br> */<br>function subscribeCustomers() {<br>  try {<br>    // Start by checking if the required settings exist and notify the user if they don&#39;t<br>    let apiKey = settings.getSettingFromScriptProperties(SETTINGS_API_KEY_LABEL);<br>    let selectedProductId = settings.getSetting(SETTINGS_SELECTED_PRODUCT_LABEL);<br>    let defaultTrialPeriod = settings.getSetting(SETTINGS_DEFAULT_TRIAL_PERIOD_LABEL);<br><br>    if (!apiKey) {<br>      throw new Error(&#39;API Key not found in script properties.&#39;);<br>    }<br><br>    if (!selectedProductId) {<br>      throw new Error(&#39;Selected Product not found in settings.&#39;);<br>    }<br><br>    if (defaultTrialPeriod == null) {<br>      throw new Error(&#39;Default Trial Period not found in settings.&#39;);<br>    }<br><br>    // Get Customers from sheet<br>    let sheetCustomers = fetchCustomersFromSheet();<br><br>    for (const element of sheetCustomers) {<br>      let fc = element;<br>      if (fc.subscriptionStatus != &#39;Subscribed&#39;) {<br>        subscribeCustomer(fc, selectedProductId, defaultTrialPeriod);<br>      }<br>    }<br>  } catch (error) {<br>    SpreadsheetApp.getUi().alert(`Error: ${error.message}`);<br>  }<br>}<br><br><br>/**<br> * Handles the subscription process for a single customer.<br> * @param {Object} fc - Customer object.<br> * @param {string} productId - Stripe product ID.<br> * @param {number} defaultTrialPeriod - Default trial period in days.<br> */<br>function subscribeCustomer(fc, productId, defaultTrialPeriod) {<br>  try {<br>    // Create Customer<br>    let newStripeCustomer = stripeClient.createCustomer(fc.name, fc.email, fc.address, fc.country, fc.city, fc.postalCode);<br>    if (!newStripeCustomer) {<br>      throw new Error(&#39;Failed to create a new Stripe customer.&#39;);<br>    }<br><br>    let amount = fc.amount * 100;<br>    let product = stripeClient.fetchProduct(productId);<br><br>    if (product == null) {<br>      throw new Error(&#39;Product not found in Stripe.&#39;);<br>    }<br><br>    // Check if the price exists, if not create it<br>    let priceId = getPrice(amount, product.id, CURRENCY);<br>    if (priceId == null) {<br>      throw new Error(&#39;Price not found for the selected product in Stripe.&#39;);<br>    }<br><br>    let trialPeriod = (fc.trialPeriod != null &amp;&amp; fc.trialPeriod != &quot;&quot;) ? parseInt(fc.trialPeriod) : defaultTrialPeriod;<br>    let subs = stripeClient.createSubscription(newStripeCustomer.id, priceId, fc.months, trialPeriod);<br><br>    if (!subs) {<br>      throw new Error(&#39;Failed to create a subscription in Stripe.&#39;);<br>    }<br><br>    let session = stripeClient.createCheckoutSession(priceId, newStripeCustomer.id, &quot;card&quot;, &quot;https://apptivasoftware.com&quot;);<br>    if (!session) {<br>      throw new Error(&#39;Failed to create a checkout session in Stripe.&#39;);<br>    }<br><br>    sendCheckoutLink(newStripeCustomer, session);<br>    setField(fc.email, 10, &#39;CREATED&#39;);<br>    setField(fc.email, 11, subs.id);<br>  } catch (error) {<br>    SpreadsheetApp.getUi().alert(`Error for customer ${fc.email}: ${error.message}`);<br>  }<br>}<br><br><br>/**<br> * Sends a checkout link to the customer via email.<br> * @param {Object} customer - Stripe customer object.<br> * @param {Object} session - Stripe checkout session object.<br> */<br>function sendCheckoutLink(customer, session) {<br>  let checkoutUrl = session.url;<br><br>  // Send an email to the customer with the checkout URL<br>  let subject = &quot;Complete Your Subscription Setup&quot;;<br>  let body = `<br>        Dear ${customer.name},&lt;br&gt;&lt;br&gt;<br>        Please complete your subscription setup by &lt;a href=&quot;${checkoutUrl}&quot;&gt;clicking here&lt;/a&gt;.&lt;br&gt;&lt;br&gt;<br>        Regards,&lt;br&gt;<br>        Your Company Name<br>    `;<br><br>  MailApp.sendEmail({<br>    to: customer.email,<br>    subject: subject,<br>    body: &quot;&quot;,<br>    htmlBody: body<br>  });<br>}</pre><p><strong>Conclusion</strong></p><p>In the digital age, organizations that want to offer ongoing value to their customers must be able to manage subscriptions effectively.</p><p>Businesses may use a strong yet user-friendly solution that bridges the gap between offline operations and online billing by connecting Google Sheets with Stripe using Apps Script.</p><p>This strategy combines the comfort of conventional encounters with the ease of contemporary technologies, streamlining the subscription process while providing clients with a smooth transition. This solution offers a scalable and practical approach to managing and building your subscription-based business, whether you’re a local gym owner, an online educator, or a burgeoning SaaS startup.</p><p>Explore the template, dive in, and see how το automate customer recurring billing.</p><p><strong>Need Help with Google Apps Script Projects?</strong></p><p>At <a href="https://apptivasoftware.com/">Apptiva</a>, we help companies save time and money by automating manual, time-consuming processes and integrating external APIs with a strong focus on the Google Workspace. So, if you have a project in mind, contact us at <a href="/service/mailto:contact@apptivasoftware.com">contact@apptivasoftware.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9913274c932a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Settings Section in Google Sheets Apps Script Projects]]></title>
            <link>https://medium.com/@dpaxinos_35980/creating-a-settings-section-in-google-sheets-apps-script-projects-1c7e07d0435c?source=rss-aa69abc51066------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c7e07d0435c</guid>
            <category><![CDATA[google-apps-script]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[google-workspace]]></category>
            <dc:creator><![CDATA[Dimitris Paxinos]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 11:50:52 GMT</pubDate>
            <atom:updated>2023-10-01T11:50:52.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DiZ6Cj0NU0kUGnzI.png" /></figure><h3>The Problem</h3><p>In my experience with Google Sheets Apps Script projects, a common challenge has been the need to incorporate external script parameters. Think about parameters like <strong>DEFAULT_DISCOUNT_RATE</strong>, <strong>EARLY_BIRD_END_DATE</strong>, <strong>FEEDBACK_EMAIL</strong>, or <strong>NEXT_EVENT_DATE</strong>. These parameters aren’t just placeholders; they are crucial settings that can influence how a script behaves or presents data to the end user.</p><p>However, managing these parameters has often been a challenge:</p><p><strong>A barrier to Non-Technical Users:</strong> We certainly don’t want non-technical team members, like sales reps or event managers, to visit the script editor and risk breaking the code to change a parameter. It’s not user-friendly and poses a risk to the script’s integrity.</p><p><strong>Configuration Chaos:</strong> Hard-coded configurations, such as DEFAULT_DISCOUNT_RATE = “10%”, can lead to maintenance issues. Every change requires diving into the code, which isn’t ideal for non-tech-savvy people.</p><p><strong>Lack of Transparency:</strong> For teams or projects where non-developers need insight, it’s challenging to have a clear view of active configurations. Imagine a marketing manager trying to understand why the early bird discount rate is 10% or why the feedback emails are being sent to a specific address.</p><p><strong>Inflexibility:</strong> Changing a simple setting, like updating the NEXT_EVENT_DATE, can become tedious if buried deep within the code.</p><p>This need for a more intuitive parameter management system wasn’t an isolated instance but a recurring theme in many of my projects. Since I’ve always valued clean, reusable code, emphasizing not just the functionality but also the elegance, maintainability, and scalability of solutions.</p><p>The goal was clear:</p><p>Create a <strong>reusable settings page in Google Sheets</strong>, using Apps Script, <strong>where configurations are easily accessible, even to those without a coding background.</strong></p><p>Something like this:</p><figure><img alt="Google Sheets Screenshot showing script settings" src="https://cdn-images-1.medium.com/max/532/1*k45JV2lEHi8X5ETxk5D8Qw.png" /></figure><p>If you prefer watching than reading, you can watch the entire tutorial here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FliiKfPJeWGo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DliiKfPJeWGo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FliiKfPJeWGo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a265eb5eccb3f1d47b50a0a5d05adaf5/href">https://medium.com/media/a265eb5eccb3f1d47b50a0a5d05adaf5/href</a></iframe><h3>A Google Sheets Apps Script Solution for User Settings</h3><p>Within the realm of Google Sheets Apps Script, the <strong>Settings class</strong> emerges as a solution to address the challenges of managing script parameters. This class connects the Google Sheet with the Apps Script, <strong>enabling easy script parameter management without diving into the code.</strong></p><pre>/**<br> * Constants for boolean settings values.<br> */<br>const YES = &#39;Yes&#39;;<br>const NO = &#39;No&#39;;<br><br>/**<br> * The Settings class provides a way to manage script parameters/settings <br> * directly within a Google Sheet, making it accessible for non-technical users.<br> */<br>class Settings {<br>    <br>    /**<br>     * Constructor initializes the settings sheet and map.<br>     * @param {string} [sheetName=&quot;Settings&quot;] - Name of the sheet where settings are stored.<br>     */<br>    constructor(sheetName = &quot;Settings&quot;) {<br>        this.sheetName = sheetName;<br>        this.spreadsheet = SpreadsheetApp.getActiveSpreadsheet();<br>        this.settingsSheet = this.spreadsheet.getSheetByName(sheetName);<br>        this.settingsMap = this.initSettingsMap();<br>    }<br><br>    /**<br>     * Initializes the settings sheet if it doesn&#39;t exist.<br>     */<br>    init() {<br>        if (!this.settingsSheet) {<br>            this.settingsSheet = this.spreadsheet.insertSheet(this.sheetName);<br>            this.settingsSheet.appendRow([&#39;Setting&#39;, &#39;Value&#39;]);<br>            this.settingsSheet.getRange(&#39;1:1&#39;).setFontWeight(&#39;bold&#39;);<br>        }<br>    }<br><br>    /**<br>     * Initializes the settings map from the sheet data.<br>     * @returns {Map} - A map of settings.<br>     */<br>    initSettingsMap() {<br>        if (!this.settingsSheet) return new Map();<br><br>        const data = this.settingsSheet.getDataRange().getValues();<br>        const map = new Map();<br><br>        for (const [key, value] of data) {<br>            map.set(key, value);<br>        }<br><br>        return map;<br>    }<br><br>    /**<br>     * Sets or updates a setting in the sheet.<br>     * @param {string} settingName - Name of the setting.<br>     * @param {string} settingValue - Value of the setting.<br>     */<br>    setSetting(settingName, settingValue) {<br>        const rowIndex = [...this.settingsMap.keys()].indexOf(settingName) + 1;<br><br>        if (rowIndex &gt; 0) {<br>            this.settingsSheet.getRange(rowIndex, 2).setValue(settingValue);<br>        } else {<br>            this.settingsSheet.appendRow([settingName, settingValue]);<br>        }<br><br>        this.settingsMap.set(settingName, settingValue);<br>    }<br><br>    /**<br>     * Retrieves a setting&#39;s value from the map.<br>     * @param {string} settingName - Name of the setting.<br>     * @returns {string|null} - Value of the setting or null if not found.<br>     */<br>    getSetting(settingName) {<br>        return this.settingsMap.get(settingName) || null;<br>    }<br><br>    /**<br>     * Retrieves a boolean setting&#39;s value.<br>     * @param {string} settingName - Name of the setting.<br>     * @returns {boolean|null} - True if &#39;Yes&#39;, False if &#39;No&#39;, or null if neither.<br>     */<br>    getBooleanSetting(settingName) {<br>        const settingValue = this.getSetting(settingName);<br><br>        if (settingValue === YES) return true;<br>        if (settingValue === NO) return false;<br><br>        Logger.log(`Setting value is not ${YES} or ${NO}: ${settingName}`);<br>        return null;<br>    }<br><br>    /**<br>     * Sets a setting in the script properties.<br>     * @param {string} settingName - Name of the setting.<br>     * @param {string} settingValue - Value of the setting.<br>     */<br>    setSettingInScriptProperties(settingName, settingValue) {<br>        PropertiesService.getScriptProperties().setProperty(settingName, settingValue);<br>    }<br><br>    /**<br>     * Retrieves a setting from the script properties.<br>     * @param {string} settingName - Name of the setting.<br>     * @returns {string} - Value of the setting.<br>     */<br>    getSettingFromScriptProperties(settingName) {<br>        return PropertiesService.getScriptProperties().getProperty(settingName);<br>    }<br>}</pre><h3>Key Features of the Code</h3><h3>Dynamic Sheet Reference with Default:</h3><p>The constructor method initializes the class with reference to the active spreadsheet and a specified sheet name, defaulting to “<strong>Settings</strong>”. This provides flexibility in naming the settings sheet.</p><p><strong>Self-Initializing Sheet:</strong></p><p>The init() method checks if the settings sheet exists. If not, it creates one, complete with headers. This ensures that the settings sheet is always available, reducing setup steps for the user.</p><p><strong>In-Memory Settings Map:</strong></p><p>The initSettingsMap method creates a map of settings for faster lookups. This reduces the need for constant sheet reads, enhancing performance.</p><p><strong>Enhanced Setting Management:</strong></p><p>The setSetting method has been optimized to update the in-memory map and the sheet simultaneously, ensuring consistency. It also allows for finding and updating a setting by its name, making changes straightforward.</p><p><strong>Boolean Settings Handling:</strong></p><p>The getBooleanSetting method interprets ‘Yes’ or ‘No’ values as boolean true or false, providing a user-friendly way to handle boolean settings.</p><p><strong>External Storage Option:</strong></p><p>Methods <em>setSettingInScriptProperties</em> and <em>getSettingFromScriptProperties</em> offer an option to store settings in Google Apps Script’s <em>ScriptProperties</em>, providing an alternative storage mechanism if needed.</p><h3>A User Settings Google Sheets Apps Script Example</h3><p>In a typical Google Sheets Apps Script project, imagine giving the end user the ability to decide if a modal message should be displayed when they press a menu button named “Show Message”.</p><p>Additionally, they should be able to customize the message shown in the modal. Here’s how you can achieve this using the Settings class:</p><p><strong>Initialization &amp; Sheet Creation</strong></p><p>First, create an instance of the <strong>Settings</strong> class and initialize the settings sheet.</p><pre>const settings = new Settings();<br>settings.init();</pre><p>Once you save your script and refresh the Google Sheet, a “Settings” sheet will be created in your Google Sheet if it doesn’t already exist.</p><p><strong>Adding Parameters</strong></p><p>Add a boolean parameter to decide if the modal should be shown and a string parameter for the modal message:</p><ul><li>“ShowModal” set to “Yes”</li><li>“ModalMessage” set to “Welcome to our Google Sheet”</li></ul><figure><img alt="Google Sheets Settings Dashboard" src="https://cdn-images-1.medium.com/max/467/0*Gc-9nvPA3Jc3fx2m.png" /></figure><p><strong>Adding a Menu Item and using the Parameters in the Script</strong></p><pre>function onOpen() {<br>  const ui = SpreadsheetApp.getUi();<br>  ui.createMenu(&#39;Settings&#39;)<br>      .addItem(&#39;Show Message&#39;, &#39;showMessage&#39;)<br>      .addToUi();<br>}<br><br><br>function showMessage() {<br>  if (settings.getBooleanSetting(&quot;ShowModal&quot;)) {<br>      const message = settings.getSetting(&quot;ModalMessage&quot;);<br>      SpreadsheetApp.getUi().alert(message);<br>  }<br>}</pre><p>Now, when the “Show Message” menu button is pressed, you can check the settings and display the modal accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*YXI-qLbO-8eg-RRD.gif" /></figure><h3>Conclusion</h3><p>With the Settings class we just saw, you can easily integrate a dedicated Settings Session in your Google Sheet using only two lines of code.</p><p>At <a href="https://apptivasoftware.com/">Apptiva Software</a>, we specialize in Google Apps Script projects and workflow automation and are committed to helping companies streamline their processes and make the most out of their data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7e07d0435c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bringing JSON Data from an API into Looker Studio]]></title>
            <link>https://medium.com/@dpaxinos_35980/bringing-json-data-from-an-api-into-looker-studio-50ed2f6cbefc?source=rss-aa69abc51066------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ed2f6cbefc</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[google-workspace]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[google-data-studio]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <dc:creator><![CDATA[Dimitris Paxinos]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 18:51:06 GMT</pubDate>
            <atom:updated>2023-09-06T18:51:06.819Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the digital age, many organizations possess a wealth of data through APIs. However, the challenge often lies in effectively visualizing this data. If you’ve been grappling with this issue, you’re not alone.</p><p>You have a rich dataset available via your API, but how do you make it visually meaningful in platforms like Looker Studio?</p><p>We’ve crafted a JSON to Looker Studio integration by <strong>developing a custom Looker Studio Connector with Google Apps Script</strong>. This solution fetches, processes, and elegantly brings your API JSON data into Looker Studio.</p><p>For this demonstration, we’ll leverage the API from Hipolabs, which offers a comprehensive dataset of universities worldwide.</p><p>Let’s get to it!</p><p><a href="https://github.com/dimitrispaxinos/looker-studio-rest-api-connector/tree/main"><strong>The code can be found on GitHub</strong></a>.</p><p>If you prefer watching than reading, you can watch the entire tutorial here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhTU2Pf670NY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhTU2Pf670NY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhTU2Pf670NY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a165f4e58ccd34d69b1c6a92c16b65aa/href">https://medium.com/media/a165f4e58ccd34d69b1c6a92c16b65aa/href</a></iframe><h3>Overview of the JSON Data</h3><p>We’ve chosen the <a href="https://github.com/Hipo/university-domains-list">Hipolabs API</a> for this tutorial, which provides details on universities from around the globe. This includes information like the university’s name, country, and alpha two code. Creating a connector for this data allows us to visualize and analyze university data in Looker Studio effortlessly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*n1lLp9cTIYcXKV9sparMlA.png" /></figure><h3>Creating a New Google Apps Script Project</h3><p>We’ll need to create a new Google Apps Script project. This will serve as the foundation for our custom connector, allowing us to bring JSON data into Looker Studio.</p><ol><li>Navigate to the <a href="https://script.google.com/home">Google Apps Script dashboard</a>.</li><li>Click on the “+ New Project” button.</li><li>Name your project appropriately, perhaps something like “LookerStudioConnector”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*H9z_zMz3wL-R6zzJ.png" /></figure><h3>Editing the Manifest File</h3><p>Every Google Apps Script project contains a hidden file known as the manifest file (appsscript.json). This file holds crucial metadata about the script, including which APIs it uses and how it interacts with other Google services. Before we dive into editing it, let’s first make it visible.</p><p>Please go to <strong>Project Settings</strong> (The Gear Icon on the left side of your screen) and click on “Show “appsscript.json” manifest file in editor”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s33TFds7yip5SWUFzNsOgg.png" /></figure><p>Now that the manifest file is visible let’s delve into its significance for our custom connector.</p><p>For our connector, the manifest file will define its properties and how it will appear in Looker Studio. Here’s a snippet of what the manifest file might look like:</p><pre>{<br>  &quot;timeZone&quot;: &quot;Europe/Athens&quot;,<br>  &quot;dependencies&quot;: {},<br>  &quot;exceptionLogging&quot;: &quot;STACKDRIVER&quot;,<br>  &quot;runtimeVersion&quot;: &quot;V8&quot;,<br>  &quot;dataStudio&quot;: {<br>    &quot;name&quot;: &quot;Looker Universities List Connector&quot;,<br>    &quot;company&quot;: &quot;Apptiva&quot;,<br>    &quot;logoUrl&quot;: &quot;https://media.licdn.com/dms/image/C4D0BAQFef_MA6VQpeQ/company-logo_100_100/0/1621108560492?e=1698278400&amp;v=beta&amp;t=vXBwKHavpEkU5GFY3Lb-IAS5FwBpI5f0ueTqwIwh8-E&quot;,<br>    &quot;addonUrl&quot;: &quot;https://www.apptivasoftware.com&quot;,<br>    &quot;supportUrl&quot;: &quot;https://www.apptivasoftware.com&quot;,<br>    &quot;description&quot;: &quot;Looker Universities List Connector Descripion&quot;<br>  }<br>}</pre><h3>A Closer Look at the Code</h3><p>Let’s delve deeper into the intricacies of our Google Apps Script code.</p><h4>Initialization and Setting the Base URL</h4><p>Here, we’re setting up our script by initializing the Community Connector, a crucial component for our integration. The BASE_URL is the endpoint from which we’ll be fetching our university data.</p><pre>// Initialize the Community Connector using the DataStudioApp service<br>let communityConnector = DataStudioApp.createCommunityConnector();<br><br>// Base API endpoint for fetching university data<br>let BASE_URL = &#39;http://universities.hipolabs.com/search&#39;;</pre><h3>Defining the Data Schema</h3><p>Our schema acts as a blueprint for the data we fetch. It ensures that the data aligns perfectly with Looker Studio’s requirements. Here’s a glimpse of how we’ve structured it:</p><pre>let schema = [    <br>    {name: &#39;alpha_two_code&#39;, label: &#39;Alpha Two Code&#39;, dataType: &#39;STRING&#39;, semantics: {conceptType: &#39;DIMENSION&#39;}},<br>    {name: &#39;country&#39;, label: &#39;Country&#39;, dataType: &#39;STRING&#39;, semantics: {conceptType: &#39;DIMENSION&#39;}},    <br>    {name: &#39;name&#39;, label: &#39;Name&#39;, dataType: &#39;STRING&#39;, semantics: {conceptType: &#39;DIMENSION&#39;}},    <br>];</pre><h3>Fetching the Data</h3><p>The <strong>getData</strong> function is where the real magic happens. We fetch the JSON data, process it, and map it to our schema. Here’s a snippet that showcases how we construct the API URL based on user input and fetch the data:</p><pre>function getData(request) {<br>    let dataSchema = [];<br>    request.fields.forEach(function (field) {<br>        for (const element of schema) {<br>            if (element.name == field.name) {<br>                dataSchema.push(element);<br>                break;<br>            }<br>        }<br>    });<br>    let countryParam = request.configParams.country;<br>    let url = BASE_URL + (countryParam ? `?country=${encodeURIComponent(countryParam)}` : &#39;&#39;);<br>    let response = UrlFetchApp.fetch(url);<br>    let parsedResponse = JSON.parse(response);<br>    let rows = [];<br>    parsedResponse.forEach(function(university) {<br>        let row = [];<br>        request.fields.forEach(function(field) {<br>            switch (field.name) {<br>                case &#39;name&#39;:<br>                    row.push(university.name);<br>                    break;<br>                case &#39;country&#39;:<br>                    row.push(university.country);<br>                    break;<br>                case &#39;alpha_two_code&#39;:<br>                    row.push(university.alpha_two_code);<br>                    break;<br>                default:<br>                    row.push(&#39;&#39;);<br>            }<br>        });<br>        rows.push({ values: row });<br>    });<br>    return {<br>        schema: dataSchema,<br>        rows: rows<br>    };<br>}</pre><h3>Configuring User Input with getConfig()</h3><p>One of the powerful features of building a custom connector is the ability to allow users to customize the data they fetch. The <strong>getConfig() </strong>function defines the configuration settings for the connector, including user input fields. It allows users to customize the data they fetch, making integrating JSON data into Looker Studio more flexible.</p><pre>function getConfig(request) {<br>    const config = communityConnector.getConfig();<br><br>    config.newInfo()<br>        .setId(&#39;instructions&#39;)<br>        .setText(&#39;Enter Country Name to fetch university data.&#39;);<br><br>    config.newTextInput()<br>        .setId(&#39;country&#39;)<br>        .setName(&#39;Country&#39;)<br>        .setHelpText(&#39;Enter the country for which you want to fetch university data.&#39;)<br>        .setPlaceholder(&#39;USA&#39;)<br>        .setAllowOverride(true);<br><br>    return config.build();<br>}</pre><p>Here, we’re initializing a configuration object using the <strong>getConfig()</strong> method of our <strong>communityConnector</strong> instance.</p><p>The newInfo() method creates an informational text field. This is particularly useful for providing instructions or context to the user. In our case, we’re guiding the user to enter a country name.</p><p>With newTextInput(), we’re defining a new text input field where users can specify the country they’re interested in. Several chained methods help configure this input:</p><ul><li>setId(): Sets a unique identifier for the input field.</li><li>setName(): Provides a display name for the input.</li><li>setHelpText(): Offers additional guidance or information about the input.</li><li>setPlaceholder(): Sets a placeholder text to indicate expected input.</li><li>setAllowOverride(): Allows users to override the default or previously set value.</li></ul><p>Finally, we build and return the configuration using the build() method. This ensures that when users interact with our connector in Looker Studio, they’ll be presented with our defined inputs, allowing for a tailored data-fetching experience.</p><h3>Deploying our Connector</h3><p>Once our script is ready, the next step is to deploy it as a connector. But before doing so, we must first assign a Google Cloud Project to our Apps Script, which can be done in <strong>Project Settings</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkaPqVDL7h365vC8lursuQ.png" /></figure><p>Now, let’s deploy our connector!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouKEI82imAcRlg5lvpDBIA.png" /></figure><h3>Our Connector is ready</h3><p>Our Connector is now ready to be used within Looker Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGqzk8mNgZBI2Mbp10sTUg.png" /></figure><h3><strong>Conclusion</strong></h3><p>Building a custom connector using Google Apps Script offers a flexible solution to bring JSON data into Looker Studio. With this guide and the accompanying <a href="https://www.youtube.com/watch?v=hTU2Pf670NY">video tutorial</a>, you can seamlessly integrate any API data into your Looker reports.</p><p>At <a href="https://apptivasoftware.com/">Apptiva Software</a>, we specialize in Google Apps Script projects and workflow automation and are committed to helping companies streamline their processes and make the most out of their data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ed2f6cbefc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>