Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Overview

Excerpt
hiddentrue

Set up User Creation API to allow a user to be created from the Salesforce contact screen.


This User Creation API is called with a payload (transmitted data) of the user information including approval limits, customer associations etc, from the Salesforce contact screen. The web application will run validations and create the user after the validations are passed. An option in the payload is to specify whether a welcome email is to be sent to the user.


This is the primary data sent:

  • First Name
  • Surname
  • Email Address
  • Customer Code
  • Account Administrator

If the user already exists, you will be alerted with a message. 


This guide covers what you have to do in the process for to set up the User Creation using the Postman for Chrome tool. There are add-ons available for other browsers, but this guide will show examples using Postman. Use this guide to troubleshoot network connectivity and password / credential issues.
 API. You will be provided with the necessary information: 

  • The ClientID and ClientSecret
  • The Token api endpoint: /api/token
  • The api endpoint: /api/user (in this case)

With this info, you need to create code to retrieve an authorisation token and code to the API call endpoints.

Prerequisites

  1. URL (will be provided to you)
  2. Username
  3. Password 
  4. Sample Setup Request file (see sample at the end of this articlepage)
  5. API testing app / browser add-on: 


Step-by-step guide

...

Get Authorisation Token 

Before any API call is made, an authorisation token must be created.


1. Open Postman.

2. Enter the URL in the URL request box. 

...


3. Set the request type to 'POST'. 

...


...

4. Add the clientId and clientSecret.

5. The clientId and clientSecret need to be joined and ended with a colon. NOTE- btoa() encodes the value in base 64.

// NOTE: Professional Services should provide these values
var clientId = '7BEFD2BA2C50424FA05248D42D6668BB';
var clientSecret = '114F3F65162F46D899EEEF6426768606';
 
// Join the above two values together with a colon in between and base64 encode the result.
var auth = btoa(clientId + ":" + clientSecret);


6. Do a call to get the token. 

Tthe 'Authorization' uses the above auth value to generate the token:
Image Added


$.ajax({
    url: '/api/token',
    method: 'post',
    headers: {'Authorization': 'Basic ' + auth},
    data: { 'grant_type': 'client_credentials' }
}).then(function(response) {
    // IMPORTANT: we will use these two value in the api calls.
    var type = response.token_type;
    var token = response.access_token;
});


7. The response is an object with two fields:

  • response.token_type: this is the authorisation type that is needed for the api calls (should be 'bearer' usually)
  • response.access_token: this is the actual token


Make the API call

The token_type and access_token are needed to make the API call. The API endpoint requires use of the token type and token in the authorisation header.

The API request content is the payload.

Image Addeds

token_type = response.token_type;
access_token = response.access_token;
 
$.ajax({
    url: '/api/User',
    method: 'post',
    headers: { 'Authorization': token_type + ' ' + access_token },
    contentType: 'application/json',
    data: JSON.stringify({
        "EmailAddress" : "user-does-not-exist",
        "FirstName" : "user-name",
        "Surname" : "user-surname",
        "PhoneNumber" : "0419 000 000",
        "NotifyEmailAddress" : "someone@somedomain.com",
        "CustomerCodes" : [
            "046008",
            "046018"
        ],
        "SendWelcomeEmail": false
    })
}).done(function(response) {
    console.log(response);
});


NOTE - The response object should contain a response that allows you to see whether the call succeeded and whatever response information the call will return. All responses should contain "Success" and may contain "Message" (it should have the field but might have no content depending on the service). All other fields on the response object are endpoint specific.

Image Added



Example

Below is an simple example of combining the above into a function that retrieves a token and caches it in local storage. It also retrieves the token if it is not cached or if the api endpoint call returns a 401 (not authorized) because the token is expires:


Warning

You need to replace the clientId and clientSecret values below in the getToken() function with the values provided by Professional Services.

...

Code Block
languagejs
function clearToken() {
    sessionStorage.removeItem('api_type_ebf530f9-083c-43a1-bf93-cd47a853495b');
    sessionStorage.removeItem('api_token_ebf530f9-083c-43a1-bf93-cd47a853495b');
}

function getToken() {
    // Use Cached authorization token information if available
    //

    var type = sessionStorage.getItem('api_type_ebf530f9-083c-43a1-bf93-cd47a853495b');
    var token = sessionStorage.getItem('api_token_ebf530f9-083c-43a1-bf93-cd47a853495b');

    var result = $.Deferred();

    if (type != null && token != null) {
        result.resolve({
            type: type,
            token: token
        });

        return result.promise();
    }

// TODO replace these values with your clientId and client secret values
    var clientId = '<replace>';
    var clientSecret = '<replace>';

    var auth = btoa(clientId + ":" + clientSecret);

    // Get and Cache new authorization token.
    //

    $.ajax({
        url: 'https://justinw-office.commercevision.com.au/api/token',
        method: 'post',
        headers: {'Authorization': 'Basic ' + auth},
        data: { 'grant_type': 'client_credentials' }
    }).then(function(response) {
        type = response.token_type;
        token = response.access_token;

        sessionStorage.setItem('api_type_ebf530f9-083c-43a1-bf93-cd47a853495b', type);
        sessionStorage.setItem('api_token_ebf530f9-083c-43a1-bf93-cd47a853495b', token);

        result.resolve({
            type: type,
            token: token
        });
    });

    return result.promise();
}

function createUser(user) {
    function createOptions(tokenInfo) {
        return {
            url: 'https://justinw-office.commercevision.com.au/api/User',
            method: 'post',
            headers: { 'Authorization': tokenInfo.type + ' ' + tokenInfo.token },
            contentType: 'application/json',
            data: JSON.stringify(user)
        };
    }

    var prom = $.Deferred();

    // Get token (cached or retrieve) and make call. On failure due to token having expired, retrieve
    // a new token and retry.
    //

    getToken().then(function(token) {
        $.ajax(createOptions(token))
            .done(function(response) {
                prom.resolve(response);
            })
            .fail(function(response) {
                if (response.status == 401) {
                    clearToken();

                    getToken().then(function(token) {
                        $.ajax(createOptions(token))
                            .done(function(response) {
                                prom.resolve(response);
                            })});
                    return;
                }

                console.error(response);
            });
    });

    return prom.promise();
}

createUser({
    "EmailAddress" : "user-does-not-exist",
    "FirstName" : "user-name",
    "Surname" : "user-surname",
    "PhoneNumber" : "0419 000 000",
    "NotifyEmailAddress" : "someone@somedomain.com",
    "CustomerCodes" : [
        "046008",
        "046018"
    ],
    "SendWelcomeEmail": false
}).done(function(response) {
// TODO do something with the response here
    console.log(response);
});

Related help

...