Taking users through a Zendesk OAuth flow is usually the first step in using the integration. This tutorial describes the steps to build a Zendesk app with OAuth capability based on ZIS.

By the end of this tutorial, you should have a simple Zendesk app working locally that guides users through the OAuth flow and stores a Zendesk OAuth 2.0 token in ZIS.

Prerequisites

  • You completed the ZIS basic tutorial series.
  • You registered a new integration with the name {subdomain}_zis_tutorial. Replace {subdomain} with your Zendesk subdomain.

Create a Zendesk app

You’ll create a Zendesk app that provides users with a UI to go through the OAuth flow. Users will launch the app from the nav bar on the left side of the Zendesk agent interface.

Using an app for this purpose is a good choice because it’s simple to create, hosted by Zendesk, and allows you to leverage the browser session for authentication.

Start by installing the Zendesk Command Line (ZCLI) package from npm. ZCLI provides a set of tools for building apps. Follow the instructions in Using Zendesk Command Line (ZCLI) to install the package and authenticate your Zendesk account for testing your app.

To create and test the app

  1. In your command line tool, run zcli apps:new and enter your details to create your app starter files.

  2. Navigate to the manifest.json file in the app directory, modify the manifest values as follows, and save the file.

    {  "name": "ZIS Tutorial - Slack Notifier",  "author": {    "name": "My name",    "email": "[email protected]",    "url": "https://www.example.com"  },  "version": "1.0",  "frameworkVersion": "2.0",  "defaultLocale": "en",  "private": true,  "location": {    "support": {      "nav_bar": "assets/index.html"    }  }}
  3. In the assets directory, create an index.html file and paste the following content:

    <html>  <head>    <meta name="viewport" content="width=device-width, initial-scale=1" />    <!-- jQuery is chosen for its simplicity to setup and go -->    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>    <!-- The following jsDelivr combine endpoint is used to load all of the Garden npm package    CSS required by the demo. Additional components may be added by updating the link URL.    See https://www.jsdelivr.com/features#combine for details. -->    <link      href="https://cdn.jsdelivr.net/combine/npm/@zendeskgarden/css-bedrock,npm/@zendeskgarden/css-grid,npm/@zendeskgarden/css-buttons,npm/@zendeskgarden/css-forms,npm/@zendeskgarden/css-utilities"      rel="stylesheet"    />
        <!-- https://github.com/zendesk/zendesk_app_framework_sdk -->    <script      type="text/javascript"      src="https://static.zdassets.com/zendesk_app_framework_sdk/2.0/zaf_sdk.min.js"    ></script>
        <!-- bootstrap the app -->    <script type="text/javascript" src="bootstrap.js"></script>  </head>  <body>    <div class="u-m u-fg-grey-800">      <div class="u-mb">        <div class="row">          <div class="col-6">            <div class="c-txt u-mb">              <button id="btnConnect" class="c-btn c-btn--primary">                Zendesk Authorization              </button>            </div>          </div>        </div>      </div>    </div>  </body></html>
  4. In the same directory, create a bootstrap.js file and paste the following code:

    // Bootstrap the app when DOM is ready$(function () {  // Initialize the Zendesk JavaScript API client  // https://developer.zendesk.com/apps/docs/developer-guide/getting_started  window.client = ZAFClient.init()
      // Subdomain is required to kickoff the OAuth flow  let subdomain = undefined
      // Integration key is the unique identifier for your integration app  let integrationKey = undefined
      client.context().then(function (context) {    // Derive subdomain and integration key    subdomain = context['account']['subdomain']    integrationKey = subdomain + '_zis_tutorial'    console.log('Integration key: ' + integrationKey)  })})
  5. In your command line tool, navigate to the app directory that contains manifest.json, and run zcli apps:server to start a local HTTP server.

  6. Load the app with your changes by navigating to your Zendesk instance and appending ?zcli_apps=true to the URL. See Testing your app locally in a browser.

An app icon should be displayed in the nav bar on the left side and the integration key is printed in the console. Click the icon to launch the app.

Add Zendesk authorization

ZIS requires authorization to read or write Zendesk data. In this section, you'll add the functionality that lets the user complete an OAuth flow and acquire a Zendesk access token when the Zendesk Authorization button is pressed.

To add Zendesk authorization

  1. Paste the following code into the connect.js file and save it in the same directory as index.html.

    // zendeskConnectionName is a human-friendly name for referencing// Zendesk OAuth connection stored in ZISconst zendeskConnectionName = 'zendesk'
    // zendeskOAuthClientName is used to reference the companion Zendesk OAuth// client that came with the ZIS integrationconst zendeskOAuthClientName = 'zendesk'
    function startOAuth(integrationKey, subdomain) {  let data = JSON.stringify({    name: zendeskConnectionName,    oauth_client_name: zendeskOAuthClientName,    oauth_url_subdomain: subdomain,    origin_oauth_redirect_url: window.location.href,    permission_scopes: 'read write'  })
      let request = {    type: 'POST',    url: '/api/services/zis/connections/oauth/start/' + integrationKey,    contentType: 'application/json',    data: data  }
      client.request(request).then(    function (response) {      console.log('OAuth started successfully')      authorize(response.redirect_url)    },    function (response) {      console.log('Failed to start OAuth: ', response)    }  )}
    function authorize(redirectURL) {  let authWindow = window.open(redirectURL, '_blank')  setTimeout(watchToken, 1500)  // poll token from the newly opened window  function watchToken() {    try {      let params = new URL(authWindow.location.href).searchParams      // Cross-origin access will cause error on the above line      // Once the oauth is completed, the authWindow's location      // will be redirected back to the same origin, which in turn      // allow us to get the verification token      let verificationToken = params.get('verification_token')      console.log('Successfully established connection')      authWindow.close()    } catch (err) {      console.log(        'DOM error is expected during cross domain authorization: ' + err      )      setTimeout(watchToken, 500)    }  }}
  2. Add the following code in index.html to load connect.js under bootstrap.js.

    ...   <!-- bootstrap the app -->   <script type="text/javascript" src="bootstrap.js"></script>
       <!-- establish connection -->   <script type="text/javascript" src="connect.js"></script></head>

    The script kicks off an OAuth flow by opening a tab and watching the URL pattern until the last redirect is complete. At this point, a Zendesk access token has been successfully obtained and stored in ZIS for future use.

  3. Append the code below to bootstrap.js to trigger the authorization flow:

    ...       console.log("Integration key: " + integrationKey);   }).then(function() {       // Bind button to start OAuth flow       $("#btnConnect").click(function() { startOAuth(integrationKey, subdomain) });   });});
  4. Save your changes.

  5. Reload the app and click the Zendesk Authorization button. A new tab should open to complete the Zendesk OAuth flow.

Verify the access token

You can verify that the token was acquired successfully and stored in ZIS by making a request to the ZIS Connections API. Make sure you set up the request in Postman by following Building your first integration - Part 2: Obtaining an OAuth token.

Postman request details:

  • Method: GET
  • URL: https://{subdomain}.zendesk.com/api/services/zis/connections/{subdomain}_zis_tutorial?name=zendesk

Replace {subdomain} with your Zendesk subdomain.

The response should return a connection named "zendesk" with the authorization details. Example:

Next: Part 2: Using ZIS to obtain a Slack OAuth token