Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Gmail Webhooks

How it works

  • After setting up the webhook on GCP, we get notified every time an email in reports@wisk.ai is received. We get notified in wisk-api public/gmail/webhook endpoint.
  • This endpoint will then get the history_id (that basically references an email) and call two different queue jobs:
    • fetchSalesFromGmailHistory will connect to gmail to read the labels applied to this email. Based on those labels, we’ll try to find a venue using that label and if found, call the import_sales job to import sales from that email.
    • fetchInvoicesFromGmailHistory will connect to gmail to read the address to which the email was sent. That address is in the format inbox+{venue_slug}@wisk.ai. Based on that we’ll try to find a venue using that slug and if found, call the import_inbox_invoices job to import invoices from that email.

NOTE On dev and stage, the inbox address will be inboxdev+{venue_slug}@wisk.ai and inboxstage+{venue_slug}@wisk.ai

Setting up webhooks on GCP

  • Gmail Webhooks are used to get notified when an email arrives to a specific account.
  • Webhooks are managed through Google Pub/Sub.
  • Following this we create a Topic and an associated Subscription.
  • Then from here we click on our new topic and go to View Permissions and add gmail-api-push@system.gserviceaccount.com as Pub/Sub publisher.
  • In the Credentials section in GCP create a new OAuth 2.0 Client ID for a web application. The redirect URI needs to be set (needed in the next step to fetch the code) and the Client ID and Client secret should be written down somewhere.
  • Using Postman we create an url similar to this one: https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&client_id=172615538030-q127d3qg4btdmc8jihu6hgp4fr80e02t.apps.googleusercontent.com&response_type=code&scope=https://www.googleapis.com/auth/gmail.modify&redirect_uri=https://web.wisk.cool

gmail-webhook-3.png

images/gmail-webhook-1.png

  • And then using that token as an Authorization header (adding Bearer before the token), we make this call:

images/gmail-webhook-2.png

  • This watch call expires every 7 days. Google recommends to call this api daily to be sure we’ll always get the notifications. In our case, we have a daily scheduler calling wisk-api /sales/gmail-add-webhook endpoint that takes care of this.
  • If the Gmail API wasn’t already allowed on the project, there will be an error in the response with an url similar to this: https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=75161128058
  • After opening the url in the browser and enabling Gmail API, retry the request and if everything went well a historyId should be returned in the response.