This document is intended as a detailed reference for the precise behavior of the drchrono API. If this is your first time using the API, start with our tutorial. If you are upgrading from a previous version, take a look at the changelog section. # Authorization ## Initial authorization There are three main steps in the OAuth 2.0 authentication workflow: 1. Redirect the provider to the authorization page. 2. The provider authorizes your application and is redirected back to your web application. 3. Your application exchanges the `authorization_code` that came with the redirect for an `access_token` and `refresh_token`. ### Step 1: Redirect to drchrono The first step is redirecting your user to drchrono, typically with a button labeled "Connect to drchrono" or "Login with drchrono". This is just a link that takes your user to the following URL: https://drchrono.com/o/authorize/?redirect_uri=REDIRECT_URI_ENCODED&response_type=code&client_id=CLIENT_ID_ENCODED&scope=SCOPES_ENCODED - `REDIRECT_URI_ENCODED` is the URL-encoded version of the redirect URI (as registered for your application and used in later steps). - `CLIENT_ID_ENCODED` is the URL-encoded version of your application's client ID. - `SCOPES_ENCODED` is a URL-encoded version of a space-separated list of scopes, which can be found in each endpoint or omitted to default to all scopes. The `scope` parameter consists of an optional, space-separated list of scopes your application is requesting. If omitted, all scopes will be requested. Scopes are of the form `BASE_SCOPE:[read|write]` where `BASE_SCOPE` is any of `user`, `calendar`, `patients`, `patients:summary`, `billing`, `clinical` and `labs`. You should request only the scopes you need. For instance, an application which sends "Happy Birthday!" emails to a doctor's patients on their birthdays would use the scope parameter `"patients:summary:read"`, while one that allows patients to schedule appointments online would need at least `"patients:summary:read patients:summary:write calendar:read calendar:write clinical:read clinical:write"`. ### Step 2: Provider authorization After logging in (if necessary), the provider will be presented with a screen with your application's name and the list of permissions you requested (via the `scope` parameter). When they click the "Authorize" button, they will be redirected to your redirect URI with a `code` query parameter appended, which contains an authorization code to be used in step 3. If they click the "Cancel" button, they will be redirected to your redirect URI with `error=access_denied` instead. Note: This authorization code expires extremely quickly, so you must perform step 3 immediately, ideally before rendering the resulting page for the end user. ### Step 3: Token exchange The `code` obtained from step 2 is usable exactly once to obtain an access token and refresh token. Here is an example token exchange in Python: import datetime, pytz, requests if 'error' in get_params: raise ValueError('Error authorizing application: %s' % get_params[error]) response = requests.post('https://drchrono.com/o/token/', data={ 'code': get_params['code'], 'grant_type': 'authorization_code', 'redirect_uri': 'http://mytestapp.com/redirect_uri', 'client_id': 'abcdefg12345', 'client_secret': 'abcdefg12345', }) response.raise_for_status() data = response.json() # Save these in your database associated with the user access_token = data['access_token'] refresh_token = data['refresh_token'] expires_timestamp = datetime.datetime.now(pytz.utc) + datetime.timedelta(seconds=data['expires_in']) You now have all you need to make API requests authenticated as that provider. When using this access token, you'll only be able to access the data that the user has access to and that you have been granted permissions for. ## Refreshing an access token Access tokens only last 48 hours (given in seconds in the `'expires_in'` key in the token exchange step above), so they occasionally need to be refreshed. It would be inconvenient to ask the user to re-authorize every time, so instead you can use the refresh token like the original authorization to obtain a new access token. Replace the `code` parameter with `refresh_token`, change the value `grant_type` from `authorization_code` to `refresh_token`, and omit the `redirect_uri` parameter. Example in Python: ... response = requests.post('https://drchrono.com/o/token/', data={ 'refresh_token': get_refresh_token(), 'grant_type': 'refresh_token', 'client_id': 'abcdefg12345', 'client_secret': 'abcdefg12345', }) ... # Webhooks In order to use drchrono API webhooks, you first need to have an API application on file (even if it is in Test Model). Each API webhook is associated with one API application, go to here to set up both API applications and webhooks! Once you registered an API application, you will see webhook section in each saved API applications. Create a webhook and register some events there and save all the changes, then you are good to go! ## Webhooks setup All fields under webhooks section are required. **Callback URL** Callback URl is used to receive all hooks when subscribed events are triggered. This should be an URL under your control. **Secret token** Secret token is used to verify webhooks, this is very important, please set something with high entropy. Also we will talk more about this later. **Events** Events is used to register events you want to receiver notification when they happen. Currently we support following events. Event name | Event description ---------- | ----------------- `APPOINTMENT_CREATE` | We will deliver a hook any time an appointment is created `APPOINTMENT_MODIFY` | We will deliver a hook any time an appointment is modified `PATIENT_CREATE` | We will deliver a hook any time a patient is created `PATIENT_MODIFY` | We will deliver a hook any time a patient is modified `PATIENT_PROBLEM_CREATE` | We will deliver a hook any time a patient problem is created `PATIENT_PROBLEM_MODIFY` | We will deliver a hook any time a patient problem is modified `PATIENT_ALLERGY_CREATE` | We will deliver a hook any time a patient allergy is created `PATIENT_ALLERGY_MODIFY` | We will deliver a hook any time a patient allergy is modified `PATIENT_MEDICATION_CREATE` | We will deliver a hook any time a patient medication is created `PATIENT_MEDICATION_MODIFY` | We will deliver a hook any time a patient medication is modified `CLINICAL_NOTE_LOCK` | We will deliver a hook any time a clinical note is locked `CLINICAL_NOTE_UNLOCK` | We will deliver a hook any time a clinical note is unlocked `TASK_CREATE` | We will deliver a hook any time a task is created `TASK_MODIFY` | We will deliver a hook any time a task is modified and any time creation, modification and deletion of task notes, associated task item `TASK_DELETE` | We will deliver a hook any time a task is deleted ## Webhooks verification In order to make sure the callback URL in webhook is under your control, we added a verification step before we send any hooks out to you. Verification can be done by clicking "Verify webhook" button in webhooks setup page. After you click the button, we will send a `GET` request to the callback URL, along with a parameter called `msg`. Please use your webhook's secret token as hash key and SHA-256 as digest constructor, hash the `msg` value with HMAC algorithm. And we expect a `200` JSON response, in JSON response body, there should be a key called `secret_token` existing, and its value should be equal to the hashed `msg`. Otherwise, verification will fail. Here is an example webhook verification in Python: import hashlib, hmac def webhook_verify(request): secret_token = hmac.new(WEBHOOK_SECRET_TOKEN, request.GET['msg'], hashlib.sha256).hexdigest() return json_response({ 'secret_token': secret_token })
secret_token
is needed in
request header.
Try to set the secret_token
to something with high entropy, a good example could be taking the output of
ruby -rsecurerandom -e 'puts SecureRandom.hex(20)'
.
After this, you might want to verify all request headers you received on your server with this token.
# iframe integration
Some API apps provide additional functionality for interacting with patient data
not offered by drchrono, and can benefit by being incorporated into drchrono's
patient information page via iframe. We have created a simple API to make this
possible.
To make an existing API application accessible via an iframe on the patient
page, you need to update either "Patient iframe" or "Clinical note iframe" section in API management page,
to make the iframe to appear on (either the patient page or the clinical note page),
with the URL that the iframe will use for each page, and the height it should
have. The application will be reviewed before it is approved to ensure that it
is functional and secure.
## Register a Doctor
iframe applications will appear as choices on the left-hand menu of the patient
page for doctors registered with your application. To register a doctor with
your application, make a `POST` request to the `/api/iframe_integration`
endpoint using the access token for the corresponding doctor. This endpoint does not
expect any payload.
To disable your iframe application for a doctor, make a `DELETE` request to the
same endpoint.
## Populating the iframe
There are two places where the iframe can be displayed, either within the
patient detail page or the clinical note page, shown below respectively:
When requesting approval for your iframe app, you must specify a URL for one or
both of these pages which will serve as the base URL for your IFrame
contents. When a doctor views your iframe, the source URL will have various
query parameters appended to it, for example for the patient page the `src`
parameter of the IFrame will be:
```
# Welcome Implementing a new tool can be daunting, but it doesn't have to. You can implement journy.io in a few different ways to ensure it fits with the rest of your tech stack seamlessly. We welcome your feedback, ideas and suggestions. We really want to make your life easier, so if weβre falling short or should be doing something different, we want to hear about it. Send us an email at [hi@journy.io](mailto:hi@journy.io) or reach out via the chat on our website or on our platform. There are multiple ways you can send us data about users and accounts. We have both frontend and backend APIs, which can be used together at the same time. If you already use [Segment](https://segment.com/), you can [get up and running with journy.io in seconds](https://help.journy.io/en/articles/6488307-the-segment-connector). # Concepts ## Users The most basic entity is a user, a specific individual that completed an interaction with your product. We support multiple types of users, often differentiated by it's external ID prefix. E.g. In the case you are building an ordering app, there could easily be an administrator (who updates products and checks for orders) and the end-customers who place orders. One could have a typical ADM-XXXXXXXX ID, while the other would be referenced by USR-XXXXXXXXX. ## Accounts In B2B SaaS, users can be part of multiple accounts. E.g. Imagine you're building a content scheduling app where an agency can manage the social media posts of their clients. Each client of the agency has its own account in the product. If your app doesn't have the concept of a team or group of users, you can ignore accounts. ## Events An event is a data point that represents an interaction between a user and/or an account; and your product. Events can represents any range of interactions. E.g. Every time a customer creates an invoice in an invoicing app. Actions like creating an invoice can be tracked as an event in journy.io. It's critical to track events properly. You'll need to provide either an account ID, or a user ID, or both; when tracking an event. E.g. If a user updates his personal settings, you can omit the account ID as the event would not be related to any account. In a same logic, an account could get a 'suspend account' event (with account ID) from an internal process, whereas no user would be associated. In most cases, events will be associated to both 1 user and 1 account. You can optionally pass extra details as metadata (e.g. amount of the invoice). This gets particarly powerfull when creating computed properties on those event metadata. E.g. Our above ordering app could send journy.io 'Place Order' events with metadata 'price', on which journy.io very easily would compute a total order value (for each account) for the last 30 days. π‘ Metadata does not update the properties of a user or account. # Frontend vs backend The best implementations we see employ a hybrid approach to maximize data quality while maintaining the flexibility to easily collect the data they need. We recommend using our JavaScript snippet to track screen views and our backend API to sync users, sync accounts and track events. When evaluating how to track a particular event, we suggest starting with server-side and only use frontend if it's not possible to collect purely server-side. This can be the case if you need to track interactions with your product that don't result in any natural server requests (such as a button click that opens a modal). # Frontend ## Setup π‘ You can find the JavaScript snippet in the website settings in the connections view. Copy the JavaScript snippet and place it in the head or body of your application. The snippet automatically calls `journy("init", { ... })` and `journy("pageview")`. ## Identify user π‘ A user ID should be a robust, static, unique identifier that you recognize a user by in your own systems. Because these IDs are consistent across a customerβs lifetime, you should include a user ID in identify calls as often as you can. Ideally, the user ID should be a database ID. π‘ journy.io does not recommend using simple email addresses or usernames as user ID, as these can change over time. journy.io recommends that you use static IDs instead, so the IDs never change. When you use a static ID, you can still recognize the user in your analytics tools, even if the user changes their email address. π‘ The properties `full_name`, `first_name`, `last_name`, `phone` and `registered_at` will be used for creating contacts in destinations like Intercom, HubSpot, Salesforce, ... `journy("identify")` allows you to identify the user that is currently using your product. ```ts journy("identify", { // Email or user ID is required email: "john.doe@acme.com", // Unique identifier for the user in your database userId: "20", // Optional // Hash of the user ID using a backend secret // You can find the secret in the website settings // Recommended to prevent spoofing verification: "hash", // Optional properties: { full_name: "John Doe", // or first_name: "John", last_name: "Doe", phone: "123", registered_at: new Date(/* ... */), is_admin: true, key_with_empty_value: "", this_property_will_be_deleted: null, }, }); ``` ## Identify account π‘ An account ID should be a robust, static, unique identifier that you recognize an account by in your own systems. Ideally, the account ID should be a database ID. π‘ The properties `name`, `mrr`, `plan` and `registered_at` will be used to create companies in destinations like Intercom, HubSpot, Salesforce, ... `journy("account")` allows you to identify the business account (i.e. organization) using your product. ```ts journy("account", { // Required // Unique identifier for the account in your database accountId: "30", // Optional // Hash of the account ID using a backend secret // You can find the secret in the website settings // Recommended to prevent spoofing verification: "hash", // Optional properties: { name: "ACME, Inc", mrr: 399, plan: "Pro", registered_at: new Date(/* ... */), is_paying: true, key_with_empty_value: "", this_property_will_be_deleted: null, }, }); ``` ## Send page view π‘ In applications, we advise you to use screen views instead of page views. The JavaScript snippet in the site settings includes a `pageview` by default. ```ts journy("pageview"); ``` If you have a B2B application, we recommend to set account ID for every page view that happens within the context of an account. π‘ An account ID should be a robust, static, unique identifier that you recognize an account by in your own systems. Ideally, the account ID should be a database ID. ```ts journy("pageview", { accountId: "30", // Optional // Hash of the account ID using a backend secret // You can find the secret in the website settings // Recommended to prevent spoofing verification: "hash", }); ``` ## Send screen view In applications, we strongly advise you to use screen views instead of page views. Page URLs in applications often include the account ID (e.g. https://app.acme.com/accountId/settings). This makes it difficult to create signals, segments, ... based on those URLs. That's what screen views solve. It allows you to set a name for the screen being viewed (e.g. Account settings). ```ts journy("screen", { name: "Personal settings" }); ``` If you have a B2B application, we recommend to set account ID for every screen view that happens within the context of an account. Example: "Personal settings" would be without account ID, "Team settings" would be with account ID. π‘ An account ID should be a robust, static, unique identifier that you recognize an account by in your own systems. Ideally, the account ID should be a database ID. ```ts journy("screen", { name: "Account settings", accountId: "30", // Optional // Hash of the account ID using a backend secret // You can find the secret in the website settings // Recommended to prevent spoofing verification: "hash", }); ``` ## Trigger an event π‘ Use past tense for event names. User events: ```js journy("event", { // required name: "signed_in", // optional metadata: { key: "value", }, }); ``` Account events: π‘ An account ID should be a robust, static, unique identifier that you recognize an account by in your own systems. Ideally, the account ID should be a database ID. ```js journy("event", { // required name: "created_invoice", accountId: "30", // Optional // Hash of the account ID using a backend secret // You can find the secret in the website settings // Recommended to prevent spoofing verification: "hash", // optional metadata: { key: "value", amount: 100, allow_wire_transfer: true, }, }); ``` ## Identity verification Identity verification ensures that one person can't impersonate another. Identity verification requires you to add an hash (HMAC) (that you generate on your server using SHA256) to your installation snippet alongside your user ID and account ID. journy.io won't accept requests for a logged-in user without a valid hash. The hash is calculated using a secret key, which you should never share. Without this secret key, no third party can send journy.io a valid hash for one of your users, so they can't impersonate your users. This is optional but highly recommended. You can enable identify verification in the website settings in the connections view. ```js journy("identify", { userId: "userId", verification: "USER_ID_HMAC_VALUE_HERE" }) journy("account", { accountId: "accountId", verification: "ACCOUNT_ID_HMAC_VALUE_HERE" }) journy("event", { accountId: "accountId", verification: "ACCOUNT_ID_HMAC_VALUE_HERE" }) ``` ### PHP ```php { journy("screen", { name: "name" }); // or journy("pageview"); }, [location]); return ( // ... ); } ``` ### Vue Router You can use [`router.afterEach`](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-after-hooks) to listen for route changes: ```js const router = new VueRouter({ ... }); router.afterEach((to, from) => { journy("screen", { name: "name" }); // or journy("pageview"); }); ``` Note: We don't accept a page URL argument for `journy("pageview")`. The current page URL will always be resolved using `window.location.href`. ## TypeScript We published an [npm package](https://www.npmjs.com/package/@journyio/web-types) with type definitions to enable type-safe usage of our JavaScript snippet. The code and documentation is available on [GitHub](https://github.com/journy-io/web-types). ## Localhost By default a site doesn't allow page views from other domains than the registered domain. This makes it difficult to test your tracking implementation locally. You can enable "Allow any domain" in the site settings to disable the domain check. This will allow you to test the JavaScript snippet with localhost as hostname. # Backend The journy.io API is organized around REST. Our API has predictable resource-oriented URLs, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs. The API is hosted on api.journy.io. ## Official SDKs Our SDKs are designed to help you interact with our APIs with less friction. They are written in several different languages and help bridge the gap between your application and journy.io APIs. They take away the need to know the exact URL and HTTP method to use for each API call among other things leaving you more time to focus on making your application. | Language | Package | Source code | |------------|--------------------------------------------------------------------------------|----------------------------------------------------------------------------| | π Node.js | [npm install @journyio/sdk ](https://www.npmjs.com/package/@journyio/sdk) | [github.com/journy-io/js-sdk](https://github.com/journy-io/js-sdk) | | π PHP | [composer require journy-io/sdk](https://packagist.org/packages/journy-io/sdk) | [github.com/journy-io/php-sdk](https://github.com/journy-io/php-sdk) | | π Python | [pip install journyio-sdk](https://pypi.org/project/journyio-sdk/) | [github.com/journy-io/python-sdk](https://github.com/journy-io/python-sdk) | | π Ruby | Coming soon | Coming soon | Your favourite programming language not included? [Let us know!](mailto:hi@journy.io) In the meanwhile, you can use [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) to generate a client for your programming language. ## Authentication The journy.io API uses API keys to authenticate requests. You can view and manage your API keys in the [connections screen](https://system.journy.io). Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret API keys in publicly accessible areas such as GitHub, client-side code, and so forth. All API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail. For every request send to the API we expect a header `X-Api-Key` to be set with the API Key. ## Permissions When creating an API Key in [the application](https://system.journy.io) you will have the choice to give permissions to an API Key (which you can change later on). These permissions restrict the API Key from different actions. When an API Key tries to perform a certain action it doesn't have the permissions for, you will receive a `401: Unauthorized` response. ## Rate limiting To prevent abuse of the API there is a maximum throughput of 1800 requests per minute. If you need a higher throughput, please contact us. To keep our platform healthy and stable, we'll block API keys that consistently hit our rate limits. Therefore, please consider taking this throughput into account. In every response the headers `X-RateLimit-Limit` and `X-RateLimit-Remaining` will be set. The `X-RateLimit-Limit`-header will always contain the current limit of requests per minute. The `X-RateLimit-Remaining`-header will always contain the amount of requests you have left in the current sliding window. π‘ The client-side tracking uses different rate limits. ## Errors journy.io uses conventional HTTP response codes to indicate the success or failure of an API request. In general: Codes in the 2xx range indicate success. Codes in the 4xx range indicate an error that failed given the information provided (e.g. a required parameter was omitted). Codes in the 5xx range indicate an error with journy.io's servers (these are rare). When performing a `POST`- or `PUT`-request with a requestBody, or when including parameters, these parameters and fields will automatically be checked and validated against the API Spec. When any error occurs, you will get a response with an `errors`-field, structured as follows: ```json { "errors": { "parameters": { "header": { "headerParameterName": "Describe what's wrong with the header parameter.", ... }, "query": { "queryParameterName": "Describe what's wrong with the query parameter.", ... }, "path": { "pathParameterName": "Describe what's wrong with the path parameter.", ... }, }, "fields": { "fieldName": "Describe what's wrong with the fieldName.", "object.fieldName": "Describe what's wrong with the fieldName of the included object.", ... } } } ``` ## Best practices ### Track accounts & users immediately on creation When you create an account in your database, immediately sending data about that account to journy.io helps your team stay in sync. The same goes for users. Call [Upsert account](#operation/upsertAccount) as soon as possible, right after the account is first created in your database. ### Update account data daily Not every account is active every day. But, you may have properties on the account that change through background processing. That's why we recommend updating every one of your accounts' data in a recurring daily process. This way, you know that your accounts are updated every day in journy.io. ## Changelog ### December 2021 [POST /events](#operation/trackJourneyEvent) will be moved to [POST /track](#operation/trackEvent). [POST /events](#operation/trackJourneyEvent) is deprecated and will be removed in the future.