Apply Facebook SDK to Shopify
Getting Hands-on
- You should duplicate and back up your code base on Shopify. To do so, please access the admin panel of your Shopify store.
- Head to "Themes" under “Online Store” and duplicate your current theme.
Duplicate theme
- Go to “Edit code”.
Edit code
- Search for “theme.liquid” on the left side of the menu
Search for theme.liquid
- Insert the following code right after the
<body>
tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
<script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuidv4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
- Insert the following code after the above code.
Click to view code
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '2087214101500691',
xfbml: true,
version: "v9.0",
});
// Parse Send to Messenger
(function() {
var sessionId = constructSessionId()
// Restock Send To Messenger is always there
var restockDiv = $('.fb-send-to-messenger-restock-container');
if (restockDiv.length > 0) {
var restockMessenger = $('.fb-send-to-messenger-restock-container .fb-send-to-messenger');
var dataRef = restockMessenger.attr("data-ref");
var dataRefArray = dataRef.split('_');
var newDataRef = dataRefArray[0] + "_" + dataRefArray[1] + "_" + sessionId;
restockMessenger.attr("data-ref", newDataRef);
FB.XFBML.parse(document.getElementsByClassName('fb-send-to-messenger-restock-container')[0]);
}
// Product Send To Messenger
var productTagDiv = $('.fb-send-to-messenger-product-tag-container')
if (productTagDiv.length > 0) {
productTagDiv.each((index, div) => {
var productTagMessenger = $(div).find(".fb-send-to-messenger");
var dataRef = productTagMessenger.attr("data-ref");
var dataRefArray = dataRef.split('_');
var newDataRef = dataRefArray[0] + "_" + dataRefArray[1] + "_" + sessionId;
productTagMessenger.attr("data-ref", newDataRef);
FB.XFBML.parse(document.getElementsByClassName('fb-send-to-messenger-product-tag-container')[index]);
})
}
})()
FB.Event.subscribe('send_to_messenger', function(e) {
console.log(e)
if (e.event === "opt_in") {
console.log("Clicked Send To Messenger Plugin")
updateCartCookies({ updateCart: true, onPressFBButton: true })
}
});
};
</script>
<script>
function constructSessionId() {
var sessionId = Cookies.get("sessionId")
console.log("sessionId", sessionId)
if (!sessionId) {
var uuid = uuidv4()
sessionId = uuid.replace(/-/g, '')
Cookies.set("sessionId", sessionId)
}
return sessionId;
}
function getCookiesInterval() {
var getCookiesHandle = window.setInterval(function () {
var cartCookies = Cookies.get("cart")
console.log("Cookies not found. Continue looping...")
if (cartCookies) {
console.log("Cookies found!")
clearInterval(getCookiesHandle)
updateCartCookies({ updateCart: true })
}
}, 5000)
}
function updateCartCookies({ updateCart, onPressFBButton }) {
var sessionId = constructSessionId()
var cartCookies = Cookies.get("cart")
var checkoutCookies = Cookies.get("checkout_token")
var threadContext = null
console.log("checkoutCookies", checkoutCookies)
var lineItems;
// Call Api to Update
if (!((cartCookies || checkoutCookies) || onPressFBButton)) {
return getCookiesInterval()
}
window.setTimeout(function() {
$.ajax({
type: 'GET',
url: '/cart.js',
async: false,
cache: false,
dataType: 'json',
success: function(data) {
lineItems = data.items
}
});
console.log('lineItems', lineItems)
if (sessionId && cartCookies && lineItems.length > 0) {
$.ajax({
type: 'POST',
url: 'https://z0jhk3u2gd.execute-api.ap-southeast-1.amazonaws.com/prod/shopifyCookiesUpdate?shopifyDomain={{STORE_DOMAIN}}',
async: false,
cache: false,
data: JSON.stringify({
sessionId: sessionId,
cartId: cartCookies,
checkoutToken: checkoutCookies,
updateCart: updateCart,
lineItems: lineItems,
threadContext
})
})
.done((data) => {
if (data.modified) {
} else {
}
})
}
}, 2000)
}
function addToCartEvent() {
console.log('Cart Added')
updateCartCookies({ updateCart: true })
}
$(document).ready(function () {
function onPageLoad() {
constructSessionId()
updateCartCookies({ updateCart: true })
}
onPageLoad()
$("[name='add']").bind('click', function () {
addToCartEvent();
});
})
</script>
Replace
{{STORE_DOMAIN}}
in the above code with the real domain of your store.Search for “product-template.liquid” in the left side of the menu.
Search for product-template.liquid
- Insert the following code before
{% if section.settings.show_share_buttons %}
block ("Let me know when it is in stock!" can be changed to any desired wordings):
{% if product.available == false %}
<!-- Restock Send To Messenger -->
<div class="fb-send-to-messenger-restock-container {% unless current_variant.available %}variant-not-available{% endunless %}">
<div style="display: flex; flex-direction: column; font-size: 12px;">
<div style="margin-bottom: 4px; font-size: 15px;">Let me know when it is in stock!</div>
<div id="fb-send-to-messenger-restock"
class="fb-send-to-messenger"
messenger_app_id="2087214101500691"
page_id={{PAGE_ID}}
data-ref="STOCK_{{ current_variant.id }}"
color="blue"
size="large"
></div>
</div>
</div>
{% endif %}
- Insert the below code after the above code ("Notify me when there is a sale! and I would like to receive a coupon code" can be changed to any desired wordings):
{% if product.tags contains 'WAITING_SALE' %}
<div class="fb-send-to-messenger-product-tag-container">
<div style="display: flex; flex-direction: column; font-size: 12px;">
<div style="margin-bottom: 4px; font-size: 15px;">Notify me when there is a sale!</div>
<div id="fb-send-to-messenger-product-tag"
class="fb-send-to-messenger"
messenger_app_id="2087214101500691"
page_id={{PAGE_ID}}
data-ref="SALE_{{ current_variant.id }}"
color="blue"
size="large"
></div>
</div>
</div>
{% endif %}
{% if product.tags contains 'COUPON' %}
<div class="fb-send-to-messenger-product-tag-container">
<div style="display: flex; flex-direction: column; font-size: 12px;">
<div style="margin-bottom: 4px; font-size: 15px;">I would like to receive a coupon code</div>
<div id="fb-send-to-messenger-product-tag"
class="fb-send-to-messenger"
messenger_app_id="2087214101500691"
page_id={{PAGE_ID}}
data-ref="COUPON_{{ current_variant.id }}"
color="blue"
size="large"
></div>
</div>
</div>
{% endif %}
Replace the
{{PAGE_ID}}
in the above code with your real Facebook page ID.You are all set! You may proceed to build the messenger chatbot for Shopify.