Salesforce Commerce Cloud OCAPI and Hooks

By Srdjan Djukić
19/06/2020

In this blog, I will give an overview of what hooks actually are, and how they can help in developing great features. Hooks help you a lot when you are in need of dynamic functionality that will execute only at certain times, and only when it's crucial for your software solution to do so. Hooks listen to certain events in the shop or in the data layer of your storefront. Which events will the hooks listen to is totally up to the development plan and customer needs.


You can use these hooks with a B2C Commerce storefront application:


OCAPI hooks: B2C Commerce provides extension points to call scripts before or after specific OCAPI calls.
Custom hooks: You can define custom extension points and call them in your storefront code using the B2C Commerce script System package HookMgr class methods. You can then access the hook in either OCAPI or your storefront code. This flexibility makes them useful for functionality in a multichannel set of applications based on the same site.

ANATOMY OF OCAPI HOOKS SETUP

 

bee-it-blog

 

Implementation of hooks to your Salesforce Commerce Cloud product

 

Use hooks to configure functionality to be called at a specific point in your application flow or at a specific event.

In this blog we will do the following:

To demonstrate user action listening we will log in a user through OCAPI, and we will edit the user's address in his account overview. Then we will listen with a specific hook on a specific Extension Path, and add a custom label to our entered data.

After that, we will log into our BM with an admin user, and modify a specific order shipping address tracking number.

 

I will start by adding a hooks definition file, which will enable our interception of certain events.

 

Let's make sure your Business Manager has the configuration for Open Commerce API (OCAPI in further text).

 

Administration > Site Development > Open Commerce API Settings

Make sure you have your json setup there with permissions for resources of interest.

 

Shop API

Your json should contain following:

        
        

{
  "_v":"19.10",
  "clients":
  [ 
    {
      "client_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "resources":
      [
        {
          "resource_id":"/customers",
          "methods":["post"],
          "read_attributes":"(**)",
          "write_attributes":"(**)"
        },
       {
          "resource_id":"/customers/auth",
          "methods":["post"],
          "read_attributes":"(**)",
          "write_attributes":"(**)"
        },
      {
          "resource_id":"/customers/{customer_id}/addresses/{address_name}",
          "methods":["get","patch"],
          "read_attributes":"(**)",
          "write_attributes":"(**)"
        }

      ]
    }
  ]
}

client_id is default client id as shown in SFCC documentation

resources represent endpoints that we expose to OCAPI calls. Currently, our resource allows us to use get, patch and put methods on the orders. This means we can modify them remotely with appropriate authentication.

 

package.json - file that is in the root of your cartridge needs to have a definition of hooks by adding hooks keyword to it.

        
        

{
   "hooks": "./cartridge/scripts/hooks.json"
}

hooks.json
{
    "hooks": [
        {
            "name": "dw.ocapi.shop.customer.address.afterPATCH",
            "script": "./cartridge/scripts/hooks/addressAfterPatch"
        }
    ]
}

To explain the properties of the hooks json, we need to understand what name actually means in this file. It is the name of the Extension Point appropriate for your request path.

You can look for these in Salesforce Cloud Commerce official documentation


bee-it-blog

 

In our case we used dw.ocapi.shop.customer.address.afterPATCH since we want to intercept the request at the moment of order editing, and hence afterPATCH method.

There are other methods as well, if those maybe suit your requirement better.
beforePATCH - hook that executes before the actual tempering with object in database

modifyPATCHResponse - hook that enables you to alter the behaviour of this endpoints response

 

In case your clients requirement expects some other resource to be edited, you can find more hooks to modify in the SFCC documentation.

 

For this example, I will be using Postman as the request showcase tool.

We need an access_token for our OCAPI client first

 

bee-it-blogbee-it-blog

How to form an Authorization for request above?

 

You can find detailed Oauth options here. For our case, we need just a part of it. Take your BM user login and password, and combine it with the client id ‘aaaa…’

Put ‘:’ to concatenate them. So when you do that, you should have something like:

username:password:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

All we need now is to Base64 encode the output and we can put it in our Authorization Header with Basic base64generatedValue.

We now get our access_token in the response, and we will use it in further requests to OCAPI.

 

Set the Content-Type of this request to application/x-www-form-urlencoded

The body of this request is x-www-form-urlencoded, and we want to set the “grant_type” to

urn:demandware:params:oauth:grant-type:client-id:dwsid:dwsecuretoken.

Next what we need to do is authorize a customer

 

bee-it-blogbee-it-blog

Basic Authorization in this request consists of the same principle as access token obtained in the request before, except now we don't include ‘aaaa….’ in the base64 generation.

 

So username:password base64 encoded and concatenated on to Basic base64 result.

The customer_id that we got in the request is needed for the following request to alter a field in his address.

 

The body in this request should contain “type”:”credentials” and we are setting the Content-Type of this request to application/json

At last we will update the address field through OCAPI call

 

bee-it-blogbee-it-blog

Customer ID from this request is a returned value of the authorization of the customer in the previous step.

Bearer type of authorization is basically Bearer + access_token from the first step.

 

Let's take a look at our request path, we want to use /customers/{customer_id} /addresses/{address_name} (which we already gave the permission for in our OCAPI settings in Business Manager) with the PATCH method.

 

Definition of a hook script

addressAfterPatch.js

        
        

'use strict';

const Status = require('dw/system/Status');
const Transaction = require('dw/system/Transaction');

exports.afterPATCH = function (customer, addressName, customerAddress) {

    Transaction.wrap(function () {
        customerAddress.title = 'HOOK modified Title';
    });

    return new Status(Status.OK);
}

You can debug it, tweak it, make it even more customised, whatever your project requirements demand. And this would cover the Shop API part. The Data API part is really similar but we need to make resource endpoints in that part of the Open Commerce API in your BM.

 

Data API

Your json should contain the following:

        
        

{
  "_v":"19.10",
  "clients":
  [ 
    {
      "client_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "resources":
      [
        {
          "resource_id":"/customer_lists/{list_id}/customers/{customer_no}",
          "methods":["patch"],
          "read_attributes":"(**)",
          "write_attributes":"(**)"
        }
      ]
    }
  ]
}

At the same place in the documentation, there is a Data API section after the Shop.

 

bee-it-blog

 

Request for OCAPI customer data manipulation

Same rules for Bearer token apply here like for the address update.

 

bee-it-blogbee-it-blog

 

WRAP UP

Hooks are basically an extension of what your functionality does. Everything that has an extension point can be manipulated. Also, OCAPI calls enable you to do shop/data calls from external systems. Always make sure to read up on the latest documentation, and you shouldn’t have any trouble implementing them.

Customizing it according to clients’ needs and optimizing it so it suits your code the best way possible makes the hooks a really nice asset to your developer skills. That's why it's good to get familiarised with them as soon as possible :)


Author

About the author

Srdjan Djukić

Salesforce Commerce Cloud developer

interesting read? Share it!

Latest blog posts

Handling Custom Shipping and Payment Methods in SFCC

You must have had shoppers that abandon their carts at the payment part of the checkout flow. Did it happen because your payment or shipping options didn’t suit them? To increase your conversion rates, you should consider adding new custom payment or shipping options that are not included in the base options of your site. In this guide, you will learn how to add a new custom payment and shipping methods to your Salesforce Commerce Cloud site. We will also show you how you can configure your custom shipping methods to suit your needs perfectly. Read More...

2020 – A Year of Adversity, Adaptation and Learning

This strange year is nearly reaching its end, so it’s a great time to look back at what we have accomplished, but above all learned during 2020. The year has been full of uncertainty and adversity for the entire world, but it is often hard times that offer the biggest lessons and opportunities for growth. Our company’s core values which are shared by all our employees are the foundation of our success, and this year has made us recognize and appreciate some of them even more. Read More...

Getting started with controllers, models and decorators (SFCC)

Controllers were introduced as an update of pipelines and, eventually they replaced them completely. They are one of the most important parts of the Salesforce Commerce Cloud project because they control the flow of data in our application. On the other hand, models fetch data from a server and provide it as a JSON object that will be used to render a page. In this article we will show you how you can build on your existing RefArch site (or SFRA) to add a new functionality with controllers and models. Read More...

Using the full potential of Salesforce Commerce Cloud (SFCC) SEO functionality

In today’s world, it is increasingly important to do search engine optimization on your website because nearly half of customers start their shopping using a search engine. If we want our business to be successful online it is vital to use all available resources that Commerce Cloud offers to optimize your website for search engines. Based on SEO that we can manage, we can divide it into two categories: On-Page SEO and Crawlability. On-Page SEO refers to the keyword strategy that we will apply on on-site content across different pages of our website. It includes storefront URLs, titles, descriptions, H1 tags, Image Alt tags, and other on-site content. Another category we must pay attention to is crawlability, which refers to the ability of search engines to find and index pages on our website. It includes the following elements: sitemaps, canonical tags, robot.txt, redirects, error handling, and 404 pages. Let’s start exploring all that we are offered in Merchant Tools under SEO. Read More...

The Basics of Salesforce Commerce Cloud SEO

Before we start going into basics and best practices of SEO on your Salesforce site, you should also understand URL Request Analyzer. This tool can show you what URL requests are being processed on your storefront so you can see what configuration is being used to open that page. This can help us understand some parts of SEO we are still not familiar with and let us reach our goal faster. Basics of every page: title and description.... Read More...

Salesforce Commerce Cloud OCAPI and Hooks

In this blog, I will give an overview of what hooks actually are, and how they can help in developing great features. Hooks help you a lot when you are in need of dynamic functionality that will execute only at certain times, and only when it's crucial for your software solution to do so. Hooks listen to certain events in the shop or in the data layer of your storefront. Which events will the hooks listen to is totally up to the development plan and customer needs. Read More...

Creating a breakout custom attribute editor in Page Designer for Salesforce Commerce Cloud (SFCC)

How to implement a custom attribute editor in Salesforce Commerce Cloud? This is what we will focus on in this article. The next logical question would be “Why do I need to implement a custom attribute editor in SFCC?”. Well the answer is quite simple. If your storefront website needs a component which doesn’t have a predefined Page Designer type, implementing a custom attribute editor is the way to go. Read More...