Custom Apps

Building a Front End Custom App and Embedding into Commerce7 Widgets

Let's assume you want a custom app to display on every product. For example you want to install a reviews/rating widget from a company like https://www.powerreviews.com/. You want each review to be product specific.

You read the documentation for powerreviews.com and you realize you need to map each Commerce7 product to an PowerReviews product ID.

Furthermore you want to embed the reviews right below the product title and above the product description.

The High Level Strategy

  1. Use commerce7 meta-data to store the powerreviews.com ID
  2. Use commerce7 custom product layout to insert powerreviews.com div tags on the layout
  3. Write a piece of javascript to access the commerce7 product and then feed the meta data to powerreviews.

Our Javascript to Execute the Above Strategy

The following code is simplified. A try/catch and error handling has been removed.

const tenant = 'tenant';
const apiUrl = 'https://api.commerce7.com';

//We use jQuery to make it easier for the designer implementing
//Typically we do not recommend jQuery 

jQuery(document).ready($ => {
  
  // Lets find the product slug from the URL
  const pathArray = window.location.pathname.split('/');
  const marketingUrl = pathArray[pathArray.length - 1];

  // Let's retrieve the product from Commerce7
  $.ajax({
    url: `${apiUrl}/beta/product-for-web/${marketingUrl}`,
    headers: { tenant }
  }).done(product => {
    
    // Now that we have the product - let's find the powerReviewPageId in the meta data
    const metaDataElement = product.metaData.find(
      metaData => metaData.code === 'power-review-page-id'
    );`
    const powerReviewPageId = metaDataElement.value;

    // Because React loads after the page load
    // we have to figure out when the power review-div are inserted into the page

    let isPRDivRendered = 0;
    document.addEventListener(
      'DOMNodeInserted',
      () => {

        // we look for the div id="pr-reviewsnippet" in the dom - 
        // once its there we render out the PowerReview`

        if ($('#pr-reviewsnippet').length && isPRDivRendered === 0) {
          isPRDivRendered = 1;
          POWERREVIEWS.display.render({
            api_key: '<API Key>',
            locale: 'en_US',
            merchant_group_id: '<Merchant Group Id>',
            merchant_id: '<Merchand Id>',
            page_id: powerReviewPageId,
            components: {
              ReviewSnippet: 'pr-reviewsnippet',
              ReviewDisplay: 'pr-reviewdisplay'
            }
          });
        }
      },
      false
    );
  });
});

Questions? Reach out to [email protected] or hit us on Slack.