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.


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

sfcc

 

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 the 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 the 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

 

hooks ocapi

 

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

ocapi client

 

ocapi client

 

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

blog 5

 

blog 6

 

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.

 

ocapi

 

Request for OCAPI customer data manipulation

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

blog 8

 

blog 9

 

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 :)