Implementation Examples
Practical code examples and implementation patterns for integrating Webflow with Shopify and Google AI.
UCP Session Manager
This JavaScript module manages the UCP session on the client-side, including session creation, data storage, and retrieval.
class UCPSessionManager {
constructor() {
this.sessionId = this.getOrCreateSessionId();
this.sessionData = this.loadSession();
this.webhookUrl = 'https://your-xano.xano.io/api/webhook';
}
getOrCreateSessionId() {
let sessionId = sessionStorage.getItem('ucp_session_id');
if (!sessionId) {
sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
sessionStorage.setItem('ucp_session_id', sessionId);
}
return sessionId;
}
trackEvent(eventType, eventData = {}) {
const event = {
timestamp: new Date().toISOString(),
type: eventType,
data: eventData,
page: window.location.pathname
};
this.sessionData.userHistory.push(event);
this.saveSession();
this.sendWebhook('event_tracked', event);
}
updateConsent(purpose, granted) {
this.sessionData.consentStatus[purpose] = {
granted: granted,
timestamp: new Date().toISOString()
};
this.saveSession();
this.sendWebhook('consent_updated', { purpose, granted });
}
}
Consent Management UI
Build a consent management interface in Webflow using vanilla JavaScript.
<div class="consent-banner" id="consentBanner">
<h3>Cookie & Data Consent</h3>
<div class="consent-options">
<label>
<input type="checkbox" id="analyticsConsent" />
Analytics & Performance
</label>
<label>
<input type="checkbox" id="marketingConsent" />
Marketing & Personalization
</label>
</div>
<button onclick="saveConsent()">Save Preferences</button>
</div>
<script>
function saveConsent() {
const analytics = document.getElementById('analyticsConsent').checked;
const marketing = document.getElementById('marketingConsent').checked;
window.ucpSession.updateConsent('analytics', analytics);
window.ucpSession.updateConsent('marketing', marketing);
document.getElementById('consentBanner').style.display = 'none';
}
</script>
Xano Webhook Endpoint
Set up a webhook endpoint in Xano to receive data from Webflow.
// Xano Function Stack Pseudo-code
const payload = $input.body;
const eventType = payload.eventType;
const session = payload.session;
// Validate
if (!session.sessionId || !eventType) {
return { success: false, error: 'Missing fields' };
}
// Transform Data
const customerData = {
email: session.email,
tags: ['ucp-user', `session-${session.sessionId}`]
};
// Shopify Sync
const customer = await shopify_find_or_create_customer(customerData);
await shopify_update_metaobject(customer.id, 'ucp_user_profile', {
consent_status: JSON.stringify(session.consentStatus),
user_history: JSON.stringify(session.userHistory)
});
// Google AI Stream
await google_ai_stream_event({
user_id: customer.id,
event_type: eventType,
timestamp: new Date().toISOString()
});
return { success: true, customerId: customer.id };
Idempotency Implementation
Implement idempotency checks when syncing data to Shopify.
async function syncToShopify(session, eventType, eventData) {
const idempotencyKey = `${session.sessionId}_${eventType}_${Date.now()}`;
// Check if already processed
const existing = await xano.query('idempotency_log')
.where('idempotency_key', idempotencyKey)
.first();
if (existing) {
return existing.result;
}
try {
const customer = await shopify.findOrCreateCustomer(session.email);
await shopify.updateMetaobject({
ownerId: customer.id,
namespace: 'ucp',
key: 'user_profile',
value: JSON.stringify(session)
});
const result = { success: true, customerId: customer.id };
await xano.insert('idempotency_log', {
idempotency_key: idempotencyKey,
result: result
});
return result;
} catch (error) {
console.error('Sync error:', error);
throw error;
}
}
Create Customer with Metaobject
GraphQL mutation to create a customer with metafields.
mutation createCustomer($input: CustomerInput!) {
customerCreate(input: $input) {
customer {
id
email
metafields(first: 10) {
edges {
node {
namespace
key
value
}
}
}
}
}
}
// Variables
{
"input": {
"email": "user@example.com",
"tags": ["ucp-user"],
"metafields": [
{
"namespace": "ucp",
"key": "consent_status",
"value": "{\"analytics\":true}",
"type": "json"
}
]
}
}
Metaobject Definition Setup
Steps to create a Metaobject definition in Shopify admin.
- 01. Navigate to Settings โ Custom data โ Metaobjects
- 02. Create new Metaobject definition: "UCP User Profile"
-
03.
Add these fields:
- โข consent_status (JSON)
- โข user_history (JSON)
- โข last_seen (DateTime)
- 04. Associate with customer records
JWT Token Generation
Generate JWT tokens for secure communication between services.
function generateJWT(userId, sessionId) {
const payload = {
userId: userId,
sessionId: sessionId,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 60)
};
const secret = process.env.JWT_SECRET;
return jwt.sign(payload, secret);
}
Security Best Practices
- โช Always use TLS/HTTPS for all API communications
- โช Store API keys and secrets in environment variables
- โช Implement rate limiting on webhook endpoints
- โช Use JWT tokens with short expiration times
- โช Validate and sanitize all incoming data
- โช Log all security-related events for auditing