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

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

My journey from starting at Bee IT to getting certified as a Salesforce Commerce Developer

In September 2019, after graduating from the Faculty of technical sciences in Novi Sad I was at the crossroads in my life. I wanted to be independent and get a job as a developer but it was difficult since I only had freelance experience in that field. Due to the lack of experience, willingness to see how a professional workspace operates, and because I wanted to put certain things in practice I decided to apply for an internship at BeeIT. Read More...

Coronavirus: Why Do People Act in Undisciplined Manner?

I'm pretty sure one of the most googled words this year is a coronavirus. And, there is a good reason why this is a hot topic. The current situation is very unstable and dangerous for most people. It affects individuals, groups and communities- the entire world is in crisis. Despite the real and objective danger we are all exposed to, I have noticed that many people don’t follow the advice of the competent authorities. Is it a lack of information? I wouldn't say so, because the media and the general public are constantly talking about one thing- Coronavirus. You can hear often about safety measures and tips on how to protect yourself in this moment of crisis. However, some people still behave in an undisciplined and irresponsible manner. They look at people with masks and gloves with a sneer refusing to maintain the recommended social distance, Read More...

Customizing Page Designer for Salesforce Commerce Cloud (SFCC)

Whether your customers are using SiteGenesis or RefArch, PD is there to help you reduce the developer dependency, improve the speed of the market and significantly lower the Quality Assurance time. If your storefront has a need for marketing content, heavy pages PD can help elevate your productivity by focusing on the key concepts and rules by which the designed pages will work. With PD you can create and manage pages, drag & drop content, preview the current state your page is in, create reusable components which will skyrocket the marketing level of your storefront Read More...

Internships at Bee IT Hive: What to Expect When You Apply for Internship at Bee IT

Our team is small but carefully selected. Currently our Bee IT hive has 34 members and, as our CEO and Co-Founder Zoran Tovarloža said in his recent blog post about Bee IT’s New Year’s resolutions, we do not plan to stop growing. Read More...