📚 Complete Examples
Real-world implementation patterns. Copy, customize, and ship.
Choose Your Template
E-Commerce Store
Product catalog with cart, checkout, and order history.
SaaS Dashboard
Subscription management with tiered plans.
Learning Platform
Courses with progress tracking and AI tutor.
Membership Site
Exclusive content with member-only access.
E-Commerce Store
Complete shopping experience with cart persistence
<script src="https://api.gammal.tech/sdk-web.js"></script>
<script>
// ==========================================
// E-COMMERCE STORE WITH GAMMAL TECH
// ==========================================
class Store {
constructor() {
this.cart = [];
this.init();
}
async init() {
// Load cart from user data if logged in
if (GammalTech.isLoggedIn()) {
const data = await GammalTech.user.get();
this.cart = data.cart || [];
this.updateCartUI();
}
// Recover any pending payments
await this.recoverPendingPayments();
}
// Add item to cart
async addToCart(product) {
const existing = this.cart.find(i => i.id === product.id);
if (existing) {
existing.quantity++;
} else {
this.cart.push({ ...product, quantity: 1 });
}
await this.saveCart();
this.updateCartUI();
}
// Save cart to user data (syncs across devices)
async saveCart() {
if (!GammalTech.isLoggedIn()) return;
const data = await GammalTech.user.get();
data.cart = this.cart;
await GammalTech.user.save(data);
}
// Calculate total
getTotal() {
return this.cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
// Checkout
async checkout() {
if (!GammalTech.isLoggedIn()) {
await GammalTech.login();
}
const total = this.getTotal();
const items = this.cart.map(i => i.name).join(', ');
await GammalTech.pay(total, `Order: ${items}`, async (payment) => {
// Save order to user history
const data = await GammalTech.user.get();
data.orders = data.orders || [];
data.orders.push({
id: payment.payment_id,
items: [...this.cart],
total: total,
date: new Date().toISOString()
});
data.cart = []; // Clear cart
await GammalTech.user.save(data);
// Confirm delivery
await GammalTech.confirmDelivery(payment.payment_id);
// Update UI
this.cart = [];
this.updateCartUI();
this.showOrderConfirmation(payment.payment_id);
});
}
// Recover interrupted payments
async recoverPendingPayments() {
const pending = await GammalTech.settlePending();
for (const payment of pending) {
// Process each recovered payment
await this.processOrder(payment);
await GammalTech.confirmDelivery(payment.payment_id);
}
}
updateCartUI() {
document.getElementById('cartCount').textContent = this.cart.length;
document.getElementById('cartTotal').textContent = this.getTotal() + ' EGP';
}
showOrderConfirmation(orderId) {
alert(`Order confirmed! ID: ${orderId}`);
}
}
const store = new Store();
</script>
SaaS Dashboard
Subscription tiers with AI-powered features
<script src="https://api.gammal.tech/sdk-web.js"></script>
<script>
// ==========================================
// SAAS DASHBOARD WITH SUBSCRIPTIONS
// ==========================================
const PLANS = {
free: { name: 'Free', price: 0, aiCalls: 10, features: ['Basic analytics'] },
pro: { name: 'Pro', price: 199, aiCalls: 100, features: ['Advanced analytics', 'AI insights'] },
enterprise: { name: 'Enterprise', price: 499, aiCalls: 1000, features: ['All features', 'Priority support'] }
};
class SaaSApp {
constructor() {
this.user = null;
this.init();
}
async init() {
if (GammalTech.isLoggedIn()) {
this.user = await GammalTech.user.get();
this.showDashboard();
} else {
this.showLoginScreen();
}
}
async login() {
await GammalTech.login();
this.user = await GammalTech.user.get();
// Initialize new users
if (!this.user.plan) {
this.user.plan = 'free';
this.user.aiCallsUsed = 0;
this.user.aiCallsResetDate = this.getNextMonth();
await GammalTech.user.save(this.user);
}
this.showDashboard();
}
// Get current plan details
getCurrentPlan() {
return PLANS[this.user?.plan || 'free'];
}
// Check if user can use AI feature
canUseAI() {
const plan = this.getCurrentPlan();
return this.user.aiCallsUsed < plan.aiCalls;
}
// AI-powered insights (with usage tracking)
async getAIInsights(data) {
if (!this.canUseAI()) {
alert('AI limit reached. Upgrade your plan!');
return null;
}
const response = await GammalTech.ai.ask(`
Analyze this business data and provide 3 actionable insights:
${JSON.stringify(data)}
`, {
system: 'You are a business analyst. Be concise and specific.'
});
// Track usage
this.user.aiCallsUsed++;
await GammalTech.user.save(this.user);
this.updateUsageDisplay();
return response;
}
// Upgrade subscription
async upgradePlan(planId) {
const plan = PLANS[planId];
if (!plan || plan.price === 0) return;
await GammalTech.pay(plan.price, `${plan.name} Plan - Monthly`, async (payment) => {
this.user.plan = planId;
this.user.planExpiry = this.getNextMonth();
this.user.aiCallsUsed = 0; // Reset on upgrade
await GammalTech.user.save(this.user);
await GammalTech.confirmDelivery(payment.payment_id);
this.showDashboard();
alert(`Upgraded to ${plan.name}!`);
});
}
getNextMonth() {
const d = new Date();
d.setMonth(d.getMonth() + 1);
return d.toISOString();
}
showDashboard() { /* Update UI */ }
showLoginScreen() { /* Show login */ }
updateUsageDisplay() { /* Update AI usage counter */ }
}
const app = new SaaSApp();
</script>
Learning Platform
Course progress tracking with AI tutor
<script src="https://api.gammal.tech/sdk-web.js"></script>
<script>
// ==========================================
// LEARNING PLATFORM WITH AI TUTOR
// ==========================================
class LearningPlatform {
constructor() {
this.userData = null;
this.init();
}
async init() {
if (GammalTech.isLoggedIn()) {
this.userData = await GammalTech.user.get();
this.initializeProgress();
}
}
initializeProgress() {
if (!this.userData.progress) {
this.userData.progress = {
completedLessons: [],
currentLesson: null,
quizScores: {},
totalXP: 0,
streak: 0,
lastActivity: null
};
}
}
// Mark lesson as complete
async completeLesson(lessonId, xpEarned = 10) {
if (!this.userData.progress.completedLessons.includes(lessonId)) {
this.userData.progress.completedLessons.push(lessonId);
this.userData.progress.totalXP += xpEarned;
this.updateStreak();
await GammalTech.user.save(this.userData);
this.showXPAnimation(xpEarned);
}
}
// Save quiz score
async saveQuizScore(quizId, score) {
this.userData.progress.quizScores[quizId] = {
score,
date: new Date().toISOString(),
attempts: (this.userData.progress.quizScores[quizId]?.attempts || 0) + 1
};
await GammalTech.user.save(this.userData);
}
// AI Tutor - ask questions about the lesson
async askTutor(question, lessonContext) {
const token = GammalTech.getToken();
return await GammalTech.ai.chat(token, question, {
system: `You are a friendly tutor helping a student learn.
Current lesson: ${lessonContext.title}
Topic: ${lessonContext.topic}
Student's completed lessons: ${this.userData.progress.completedLessons.length}
Student's XP: ${this.userData.progress.totalXP}
Guidelines:
- Explain concepts simply
- Use examples relevant to the lesson
- Encourage the student
- If they're struggling, break it down further`
});
}
// AI-generated practice questions
async generatePracticeQuestions(topic, difficulty) {
const response = await GammalTech.ai.ask(`
Generate 3 practice questions about: ${topic}
Difficulty: ${difficulty}
Student level: ${this.userData.progress.totalXP} XP
Return JSON array: [
{ "question": "...", "options": ["a", "b", "c", "d"], "correct": 0 }
]
`);
return JSON.parse(response);
}
// Update learning streak
updateStreak() {
const today = new Date().toDateString();
const lastActivity = this.userData.progress.lastActivity;
if (lastActivity) {
const yesterday = new Date(Date.now() - 86400000).toDateString();
if (lastActivity === yesterday) {
this.userData.progress.streak++;
} else if (lastActivity !== today) {
this.userData.progress.streak = 1;
}
} else {
this.userData.progress.streak = 1;
}
this.userData.progress.lastActivity = today;
}
// Get progress percentage for a course
getCourseProgress(courseLessons) {
const completed = courseLessons.filter(
l => this.userData.progress.completedLessons.includes(l.id)
).length;
return Math.round((completed / courseLessons.length) * 100);
}
showXPAnimation(xp) { /* Animate +XP */ }
}
const platform = new LearningPlatform();
</script>
Membership Site
Gated content with member benefits
<script src="https://api.gammal.tech/sdk-web.js"></script>
<script>
// ==========================================
// MEMBERSHIP SITE WITH GATED CONTENT
// ==========================================
const MEMBERSHIP_PRICE = 299; // EGP per month
class MembershipSite {
constructor() {
this.member = null;
this.init();
}
async init() {
GammalTech.onAuth(
async () => {
this.member = await GammalTech.user.get();
this.updateUI();
},
() => {
this.member = null;
this.updateUI();
}
);
if (GammalTech.isLoggedIn()) {
this.member = await GammalTech.user.get();
this.checkMembershipExpiry();
}
this.updateUI();
}
// Check if user has active membership
isActiveMember() {
if (!this.member?.membership) return false;
return new Date(this.member.membership.expiresAt) > new Date();
}
// Check and handle expiry
async checkMembershipExpiry() {
if (this.member?.membership && !this.isActiveMember()) {
this.member.membership.active = false;
await GammalTech.user.save(this.member);
}
}
// Subscribe to membership
async subscribe() {
if (!GammalTech.isLoggedIn()) {
await GammalTech.login();
this.member = await GammalTech.user.get();
}
await GammalTech.pay(MEMBERSHIP_PRICE, 'Premium Membership - 1 Month', async (payment) => {
// Activate membership
const expiresAt = new Date();
expiresAt.setMonth(expiresAt.getMonth() + 1);
this.member.membership = {
active: true,
startedAt: new Date().toISOString(),
expiresAt: expiresAt.toISOString(),
paymentId: payment.payment_id
};
await GammalTech.user.save(this.member);
await GammalTech.confirmDelivery(payment.payment_id);
this.updateUI();
this.showWelcomeMessage();
});
}
// Gate content - returns true if can access
canAccess(contentType) {
if (contentType === 'free') return true;
if (contentType === 'members') return this.isActiveMember();
return false;
}
// Show content or paywall
renderContent(content) {
if (this.canAccess(content.type)) {
return content.body;
} else {
return this.renderPaywall(content);
}
}
renderPaywall(content) {
return `
<div class="paywall">
<h3>🔒 Members Only</h3>
<p>${content.preview || 'This content is exclusive to members.'}</p>
<button onclick="membership.subscribe()">
Join Now - ${MEMBERSHIP_PRICE} EGP/month
</button>
</div>
`;
}
// Track content views (for analytics)
async trackView(contentId) {
if (!this.member) return;
this.member.viewHistory = this.member.viewHistory || [];
this.member.viewHistory.unshift({
contentId,
viewedAt: new Date().toISOString()
});
this.member.viewHistory = this.member.viewHistory.slice(0, 100);
await GammalTech.user.save(this.member);
}
updateUI() {
const isMember = this.isActiveMember();
document.querySelectorAll('.member-only').forEach(el => {
el.style.display = isMember ? 'block' : 'none';
});
document.querySelectorAll('.guest-only').forEach(el => {
el.style.display = isMember ? 'none' : 'block';
});
}
showWelcomeMessage() {
alert('Welcome to the club! 🎉');
}
}
const membership = new MembershipSite();
</script>
Common Patterns
1. Initialize on load: Check login status and load user data
2. Auth listeners: Use GammalTech.onAuth() for reactive UI
3. Payment recovery: Always call settlePending() on page load
4. Confirm delivery: Only after successful delivery
5. Data caching: Store user data in a class property
AI Prompt for Vibe Coding
ExamplesCopy this prompt to customize these examples: