Webflow

Integrate Rocketfuel on Webflow

To integrate Rocketfuel on Webflow, you need the below

i. Custom place order button on the checkout page.

ii. JS SDK on the checkout page.

iii. Two Backend endpoints. One generates invoice links and the other receives webhooks to update transactions after payment confirmation.

Place Order Button

This can be added through webflow, anywhere on the checkout page. The button must have an id of rocketfuel-payment-button.This will trigger the payment iframe on click.

Checkout JS SDK

Add the below

const currentHostDomain = new URL(window.location.href).origin
function updateOrder(result) {
		let status = "pending";
		let result_status = parseInt(result.status);
		switch (result_status) {
			case 101:
				status = "partial-payment";
				break;
			case 1:
				status = "completed";
				break;
			default:
				status = "failed";
				break;
		}
		const url = 'ENDPOINT_TO_UPDATE_WEBFLOW_ORDER';
		const options = {
			method: 'POST',
			body: JSON.stringify({
				"status": status,
				"order_id": rocketFuelOptions.order.id
			}),
			headers: {
				'Content-Type': 'application/json'
			}
		}
		let response = fetch(url, options);
	}
    let rocketFuelOptions = {
        order: {},
        rkfl: {},
        iframe_url: 'https://iframe.rocketfuelblockchain.com',
        fetch_url: ''
    }

async function getUUID() {
    let body = getCartFunctionData();
    url = 'BACKEND_URL_TO_GET_UUID';
    const options = {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {
            'Content-Type': 'application/json'
        }
    }
    let response = await fetch(url, options);

    let result = await response.json();
    return result.uuid;
}
async function start() {
    let csrf = document.cookie.split('csrf=')[1].split(';')[0]

    let apolloEndpoint = `${currentHostDomain}/.wf_graphql/apollo`;
    let response = await fetch(apolloEndpoint, {
        method: "post", headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-wf-csrf': csrf, 'Content-Type': 'application/json' }, body: JSON.stringify([{
            operationName: 'Dynamo2',
            variables: {},
            query: 'query Dynamo2 { database { id commerceOrder { availableShippingMethods { description id mode name price { value unit decimalValue string } selected } comment customData { checkbox name textArea textInput } customerInfo { identity { email fullName } } extraItems { name pluginId pluginName price { value unit decimalValue string } } id paymentProcessor startedOn statusFlags { billingAddressRequiresPostalCode hasDownloads hasSubscription isFreeOrder needAddress needIdentity needItems needPayment requiresShipping shippingAddressRequiresPostalCode shouldRecalc } subtotal { value unit decimalValue string } total { value unit decimalValue string } updatedOn userItems { count rowTotal { value unit decimalValue string } sku { f__draft_0ht f__archived_0ht f_main_image_4dr { url file { size origFileName createdOn updatedOn mimeType width height variants { origFileName quality height width s3Url error size } } alt } f_sku_values_3dr { property { id } value { id } } id } product { id f__draft_0ht f__archived_0ht f_name_ f_sku_properties_3dr { id name enum { id name slug } } } id } userItemsCount } } site { id commerce { businessAddress { country } defaultCountry defaultCurrency quickCheckoutEnabled } } }'
        }])
    })
    let result = await response.json();
    rocketFuelOptions.order = result[0].data.database.commerceOrder;
}

function getCartFunctionData() {
    let cart = rocketFuelOptions.order.userItems.map(item => {
        return { id: item.product.id, name: item.product.f_name_, price: item.rowTotal.decimalValue, quantity: item.count }
      }
    )
    data = {
        'amount': rocketFuelOptions.order.total.decimalValue.toString(),
        'currency': 'USD',
        cart,
        order_id: rocketFuelOptions.order.id
    };
    return data
}

async function initializePayment() {
    if (document.querySelector('#rocketfuel-payment-button').disabled) return;
    document.querySelector('#rocketfuel-payment-button').disabled = true
    document.querySelector('#rocketfuel-payment-button').innerHTML = `<strong class="bold-text-2">Processing Payment...</strong>`

    try {
        await start();
        let uuid = await getUUID();

        rocketFuelOptions.rkfl = new RocketFuel({
            uuid: uuid,
            callback: updateOrder,
            environment: "prod"
        });
        let checkIframe = setInterval(() => {

            if (rocketFuelOptions.rkfl.iframeInfo.iframe) {
                document.querySelector('#rocketfuel-payment-button').innerHTML = `<strong class="bold-text-2">Preparing window...</strong>`;
                rocketFuelOptions.rkfl.initPayment();
                clearInterval(checkIframe);
            }

        }, 500);
 
    } catch (e) {
        document.querySelector('#rocketfuel-payment-button').disabled = false
        document.querySelector('#rocketfuel-payment-button').innerHTML = `<strong class="bold-text-2">Error! Please reload</strong>`

    }

}

function initRocketfuelProcess() {
    if (document.querySelector('#rocketfuel-payment-button')) {
      const rkflSDK = document.createElement('script');
      rkflSDK.src='https://d3rpjm0wf8u2co.cloudfront.net/static/rkfl.js';
      document.body.appendChild(rkflSDK);

        document.querySelector('#rocketfuel-payment-button').addEventListener('click', async () => {

            initializePayment();

        })
    }
    rocketfuelWindowListener();
}
function rocketfuelWindowListener() {

    window.addEventListener('message', (event) => {
        switch (event.data.type) {
            case 'rocketfuel_iframe_close':
                document.querySelector('#rocketfuel-payment-button').disabled = false;
                document.querySelector('#rocketfuel-payment-button').innerHTML = `<strong class="bold-text-2">Resume Payment...</strong>`
                break;
            default:
                break;
        }

    })
}
initRocketfuelProcess();

Generate Invoice ID

Invoice Id also known as UUID is needed to complete transaction on the iframe.

To generate an invoice link, you will need to run a backend server that will serve as a bridge between the Checkout script explained above and RKFL.

Follow Generate Invoice Link on how to generate invoice ID.

In getUUID(), replace ENDPOINT_TO_UPDATE_UUID with the backend endpoint, you have created to generate UUID.

Update Order Status

After a successful transaction, update the order status on Webflow to reflect the new status.

To do this, replace ENDPOINT_TO_UPDATE_WEBFLOW_ORDER with the endpoint created to receive webhook and update webflow order status.

You can follow Webhooks to set up the endpoint to handle webhook.

Last updated