ANG SILAKBO

Official Documentation

Introduction to ANG SILAKBO API Integrations

Welcome to the ANG SILAKBO API integration guide. This documentation will help you integrate our platform with popular third-party services such as Firebase, Supabase, Cloudinary, and more.

Our API is designed to work seamlessly with these services, allowing you to leverage their capabilities while maintaining a consistent development experience. Whether you need real-time databases, cloud storage, payment processing, or other functionality, this guide will show you how to integrate these services with ANG SILAKBO.

Integration Benefits

  • Simplified authentication flows
  • Consistent data handling
  • Reduced development time
  • Unified error handling

Integration Overview

ANG SILAKBO can be integrated with various third-party services to enhance your application's capabilities. Below are the key integrations we support:

Firebase

Google's app development platform

Database
  • Real-time Database

    Store and sync data in real-time across all your users' devices

  • Authentication

    Secure user authentication with multiple providers

  • Cloud Storage

    Store and serve user-generated content

Supabase

Open source Firebase alternative

Database
  • PostgreSQL Database

    Powerful and scalable relational database with realtime capabilities

  • Authentication

    User management with row-level security

  • Storage

    Store and serve large files efficiently

Cloudinary

Cloud-based media management

Media
  • Image & Video Storage

    Store, transform, optimize, and deliver media assets

  • Auto-Transformations

    Resize, crop, and optimize media on-the-fly

  • AI-Powered Analysis

    Automatic tagging and content moderation

Stripe

Payment processing platform

Payments
  • Payment Processing

    Accept payments online with secure checkout

  • Subscription Management

    Recurring billing and subscription management

  • Fraud Prevention

    Advanced fraud detection and prevention

MongoDB

NoSQL document database

Database
  • Document Database

    Flexible schema design and powerful querying

  • Atlas Cloud

    Fully managed database-as-a-service

  • Data Analytics

    Real-time data analytics and visualization

AWS S3

Cloud object storage

Storage
  • Object Storage

    Store and retrieve any amount of data from anywhere

  • Scalability

    Virtually unlimited storage capacity

  • Security

    Fine-grained access controls and encryption

Firebase Integration
Database

Firebase is a comprehensive app development platform by Google that provides a variety of tools and services to help you develop high-quality apps. ANG SILAKBO integrates seamlessly with Firebase to provide you with real-time database capabilities, authentication, cloud storage, and more.

Setting Up Firebase

Follow these steps to set up Firebase with your ANG SILAKBO project:

1

Create a Firebase Project

Go to the Firebase Console and create a new project. Follow the on-screen instructions to set up your project.

2

Register Your App

In the Firebase console, click on "Add app" and select the web platform. Follow the instructions to register your app and get your Firebase configuration.

3

Install Firebase SDK

Install the Firebase SDK in your ANG SILAKBO project using npm:

Terminal

npm install firebase
4

Initialize Firebase

Create a Firebase configuration file in your project:

firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firebase services
const auth = getAuth(app);
const db = getFirestore(app);
const storage = getStorage(app);

export { app, auth, db, storage };
5

Connect with ANG SILAKBO

Import your Firebase configuration into your ANG SILAKBO project:

app.js

import { app, auth, db, storage } from './firebase';
import { SILAKBO } from '@silakbo/sdk';

// Initialize ANG SILAKBO with Firebase
const silakbo = new SILAKBO({
  firebase: {
    app,
    auth,
    db,
    storage
  }
});

// Now you can use Firebase with ANG SILAKBO
export default silakbo;

Firebase Authentication

ANG SILAKBO provides a seamless integration with Firebase Authentication, allowing you to easily implement user authentication in your application.

User Sign Up

import silakbo from './app';

async function signUpUser(email, password) {
  try {
    const user = await silakbo.firebase.auth.createUser({
      email,
      password
    });
    
    // Store additional user data in Firestore
    await silakbo.firebase.db.setUserData(user.uid, {
      email: user.email,
      createdAt: new Date(),
      role: 'user'
    });
    
    return user;
  } catch (error) {
    console.error('Error signing up user:', error);
    throw error;
  }
}

User Sign In

import silakbo from './app';

async function signInUser(email, password) {
  try {
    const user = await silakbo.firebase.auth.signInUser({
      email,
      password
    });
    
    // Log user sign in
    await silakbo.firebase.db.updateUserLastLogin(user.uid);
    
    return user;
  } catch (error) {
    console.error('Error signing in user:', error);
    throw error;
  }
}

Social Authentication

import silakbo from './app';
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";

async function signInWithGoogle() {
  try {
    const provider = new GoogleAuthProvider();
    const result = await silakbo.firebase.auth.signInWithProvider(provider);
    
    // Handle the signed-in user
    const user = result.user;
    
    // Check if this is a new user
    const isNewUser = result.additionalUserInfo.isNewUser;
    
    if (isNewUser) {
      // Create a new user profile
      await silakbo.firebase.db.setUserData(user.uid, {
        email: user.email,
        displayName: user.displayName,
        photoURL: user.photoURL,
        createdAt: new Date(),
        role: 'user'
      });
    }
    
    return user;
  } catch (error) {
    console.error('Error signing in with Google:', error);
    throw error;
  }
}

Firebase Realtime Database & Firestore

ANG SILAKBO provides utilities for working with both Firebase Realtime Database and Firestore, allowing you to choose the database that best fits your needs.

Creating and Reading Data in Firestore

import silakbo from './app';
import { collection, addDoc, query, where, getDocs } from "firebase/firestore";

// Create a new document in a collection
async function createPost(userId, postData) {
  try {
    const postsCollection = collection(silakbo.firebase.db, "posts");
    
    const newPost = {
      title: postData.title,
      content: postData.content,
      author: userId,
      createdAt: new Date(),
      likes: 0,
      comments: []
    };
    
    const docRef = await addDoc(postsCollection, newPost);
    console.log("Document written with ID: ", docRef.id);
    
    return {
      id: docRef.id,
      ...newPost
    };
  } catch (error) {
    console.error("Error adding document: ", error);
    throw error;
  }
}

// Query for documents in a collection
async function getUserPosts(userId) {
  try {
    const postsCollection = collection(silakbo.firebase.db, "posts");
    const q = query(postsCollection, where("author", "==", userId));
    
    const querySnapshot = await getDocs(q);
    const posts = [];
    
    querySnapshot.forEach((doc) => {
      posts.push({
        id: doc.id,
        ...doc.data()
      });
    });
    
    return posts;
  } catch (error) {
    console.error("Error getting documents: ", error);
    throw error;
  }
}

Real-time Updates with Firestore

import silakbo from './app';
import { collection, query, onSnapshot } from "firebase/firestore";

// Subscribe to real-time updates
function subscribeToPostUpdates(callback) {
  const postsCollection = collection(silakbo.firebase.db, "posts");
  
  // Create a query against the collection
  const q = query(postsCollection);
  
  // Subscribe to query snapshot
  const unsubscribe = onSnapshot(q, (querySnapshot) => {
    const posts = [];
    querySnapshot.forEach((doc) => {
      posts.push({
        id: doc.id,
        ...doc.data()
      });
    });
    
    // Call the callback function with the updated data
    callback(posts);
  }, (error) => {
    console.error("Error getting real-time updates: ", error);
  });
  
  // Return the unsubscribe function to stop listening to updates
  return unsubscribe;
}

// Usage example
const unsubscribe = subscribeToPostUpdates((posts) => {
  console.log("Current posts: ", posts);
  // Update UI with the latest posts
  updateUIWithPosts(posts);
});

// When you want to stop listening to updates
// unsubscribe();

Firebase Storage

ANG SILAKBO provides utilities for working with Firebase Storage, allowing you to upload, download, and manage files in your application.

Uploading Files

import silakbo from './app';
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";

async function uploadUserProfileImage(userId, file) {
  try {
    // Create a storage reference
    const storageRef = ref(silakbo.firebase.storage, `users/${userId}/profile.jpg`);
    
    // Upload the file
    const snapshot = await uploadBytes(storageRef, file);
    console.log('Uploaded profile image!');
    
    // Get the download URL
    const downloadURL = await getDownloadURL(snapshot.ref);
    
    // Update user profile with the new image URL
    await silakbo.firebase.db.updateUserData(userId, {
      photoURL: downloadURL
    });
    
    return downloadURL;
  } catch (error) {
    console.error('Error uploading image:', error);
    throw error;
  }
}

Downloading Files

import silakbo from './app';
import { ref, getDownloadURL } from "firebase/storage";

async function getUserProfileImageURL(userId) {
  try {
    // Create a reference to the file
    const storageRef = ref(silakbo.firebase.storage, `users/${userId}/profile.jpg`);
    
    // Get the download URL
    const url = await getDownloadURL(storageRef);
    
    return url;
  } catch (error) {
    console.error('Error getting download URL:', error);
    throw error;
  }
}

Deleting Files

import silakbo from './app';
import { ref, deleteObject } from "firebase/storage";

async function deleteUserProfileImage(userId) {
  try {
    // Create a reference to the file
    const storageRef = ref(silakbo.firebase.storage, `users/${userId}/profile.jpg`);
    
    // Delete the file
    await deleteObject(storageRef);
    console.log('Profile image deleted successfully');
    
    // Update user profile to remove the image URL
    await silakbo.firebase.db.updateUserData(userId, {
      photoURL: null
    });
    
    return true;
  } catch (error) {
    console.error('Error deleting image:', error);
    throw error;
  }
}
Supabase Integration
Database

Supabase is an open-source Firebase alternative that provides a PostgreSQL database, authentication, storage, and more. ANG SILAKBO integrates seamlessly with Supabase to provide you with powerful database capabilities and authentication.

Setting Up Supabase

Follow these steps to set up Supabase with your ANG SILAKBO project:

1

Create a Supabase Project

Go to the Supabase Dashboard and create a new project. Follow the on-screen instructions to set up your project.

2

Get Your API Keys

After creating your project, go to the Project Settings > API section to find your project URL and API keys.

3

Install Supabase Client

Install the Supabase JavaScript client in your ANG SILAKBO project using npm:

Terminal

npm install @supabase/supabase-js
4

Initialize Supabase

Create a Supabase client in your project:

supabase.js

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseKey = 'YOUR_SUPABASE_KEY';
const supabase = createClient(supabaseUrl, supabaseKey);

export default supabase;
5

Connect with ANG SILAKBO

Import your Supabase client into your ANG SILAKBO project:

app.js

import supabase from './supabase';
import { SILAKBO } from '@silakbo/sdk';

// Initialize ANG SILAKBO with Supabase
const silakbo = new SILAKBO({
  supabase: supabase
});

// Now you can use Supabase with ANG SILAKBO
export default silakbo;

Supabase Authentication

ANG SILAKBO provides a seamless integration with Supabase Authentication, allowing you to easily implement user authentication in your application.

User Sign Up

import silakbo from './app';

async function signUpUser(email, password) {
  try {
    const { data, error } = await silakbo.supabase.auth.signUp({
      email,
      password
    });
    
    if (error) throw error;
    
    // Create a user profile if sign up was successful
    if (data?.user) {
      await silakbo.supabase
        .from('profiles')
        .insert([
          {
            id: data.user.id,
            email: data.user.email,
            created_at: new Date()
          }
        ]);
    }
    
    return data;
  } catch (error) {
    console.error('Error signing up user:', error);
    throw error;
  }
}

User Sign In

import silakbo from './app';

async function signInUser(email, password) {
  try {
    const { data, error } = await silakbo.supabase.auth.signInWithPassword({
      email,
      password
    });
    
    if (error) throw error;
    
    // Update last login timestamp
    if (data?.user) {
      await silakbo.supabase
        .from('profiles')
        .update({ last_login: new Date() })
        .eq('id', data.user.id);
    }
    
    return data;
  } catch (error) {
    console.error('Error signing in user:', error);
    throw error;
  }
}

Social Authentication

import silakbo from './app';
import { Auth } from '@supabase/auth-ui-react';
import { ThemeSupa } from '@supabase/auth-ui-shared';

// Component for social login
function AuthUI() {
  return (
    <Auth
      supabaseClient={silakbo.supabase}
      appearance={{ theme: ThemeSupa }}
      providers={['google', 'github', 'facebook']}
      redirectTo={window.location.origin}
      onSuccess={async (session) => {
        // Check if user profile exists
        const { data: profile } = await silakbo.supabase
          .from('profiles')
          .select('*')
          .eq('id', session.user.id)
          .single();
        
        // Create profile if it doesn't exist
        if (!profile) {
          await silakbo.supabase
            .from('profiles')
            .insert([
              {
                id: session.user.id,
                email: session.user.email,
                created_at: new Date()
              }
            ]);
        }
      }}
    />
  );
}

Supabase Database

ANG SILAKBO provides utilities for working with Supabase's PostgreSQL database, allowing you to perform CRUD operations and real-time subscriptions.

Creating and Reading Data

import silakbo from './app';

// Create a new post
async function createPost(userId, postData) {
  try {
    const { data, error } = await silakbo.supabase
      .from('posts')
      .insert([
        {
          title: postData.title,
          content: postData.content,
          user_id: userId,
          created_at: new Date()
        }
      ])
      .select();
    
    if (error) throw error;
    
    return data[0];
  } catch (error) {
    console.error('Error creating post:', error);
    throw error;
  }
}

// Get posts for a user
async function getUserPosts(userId) {
  try {
    const { data, error } = await silakbo.supabase
      .from('posts')
      .select('*')
      .eq('user_id', userId)
      .order('created_at', { ascending: false });
    
    if (error) throw error;
    
    return data;
  } catch (error) {
    console.error('Error fetching posts:', error);
    throw error;
  }
}

Real-time Subscriptions

import silakbo from './app';

// Subscribe to real-time changes on the posts table
function subscribeToPostUpdates(callback) {
  // Enable real-time for this table
  const subscription = silakbo.supabase
    .channel('public:posts')
    .on('postgres_changes', 
      { 
        event: '*', 
        schema: 'public', 
        table: 'posts' 
      }, 
      (payload) => {
        // Call the callback with the payload
        callback(payload);
      }
    )
    .subscribe();
  
  // Return the subscription so it can be unsubscribed later
  return subscription;
}

// Usage example
const subscription = subscribeToPostUpdates((payload) => {
  console.log('Change received!', payload);
  
  if (payload.eventType === 'INSERT') {
    console.log('New post added:', payload.new);
    addPostToUI(payload.new);
  } else if (payload.eventType === 'UPDATE') {
    console.log('Post updated:', payload.new);
    updatePostInUI(payload.new);
  } else if (payload.eventType === 'DELETE') {
    console.log('Post deleted:', payload.old);
    removePostFromUI(payload.old.id);
  }
});

// To unsubscribe
// subscription.unsubscribe();

Supabase Storage

ANG SILAKBO provides utilities for working with Supabase Storage, allowing you to upload, download, and manage files in your application.

Uploading Files

import silakbo from './app';

async function uploadUserProfileImage(userId, file) {
  try {
    // Define a unique file path
    const filePath = `${userId}/profile-${Date.now()}.jpg`;
    
    // Upload the file
    const { data, error } = await silakbo.supabase
      .storage
      .from('avatars')
      .upload(filePath, file, {
        cacheControl: '3600',
        upsert: true
      });
    
    if (error) throw error;
    
    // Get the public URL for the file
    const { data: { publicUrl } } = silakbo.supabase
      .storage
      .from('avatars')
      .getPublicUrl(data.path);
    
    // Update the user's profile with the new avatar URL
    const { error: updateError } = await silakbo.supabase
      .from('profiles')
      .update({ avatar_url: publicUrl })
      .eq('id', userId);
    
    if (updateError) throw updateError;
    
    return publicUrl;
  } catch (error) {
    console.error('Error uploading profile image:', error);
    throw error;
  }
}

Downloading Files

import silakbo from './app';

async function downloadUserProfileImage(filePath) {
  try {
    // Download the file
    const { data, error } = await silakbo.supabase
      .storage
      .from('avatars')
      .download(filePath);
    
    if (error) throw error;
    
    // Create a URL for the downloaded blob
    const url = URL.createObjectURL(data);
    
    return url;
  } catch (error) {
    console.error('Error downloading file:', error);
    throw error;
  }
}

Deleting Files

import silakbo from './app';

async function deleteUserProfileImage(userId, filePath) {
  try {
    // Delete the file
    const { error } = await silakbo.supabase
      .storage
      .from('avatars')
      .remove([filePath]);
    
    if (error) throw error;
    
    // Update the user's profile to remove the avatar URL
    const { error: updateError } = await silakbo.supabase
      .from('profiles')
      .update({ avatar_url: null })
      .eq('id', userId);
    
    if (updateError) throw updateError;
    
    return true;
  } catch (error) {
    console.error('Error deleting file:', error);
    throw error;
  }
}
Cloudinary Integration
Media

Cloudinary is a cloud-based media management platform that provides end-to-end media management solutions including uploads, storage, transformations, optimizations, and delivery. ANG SILAKBO integrates seamlessly with Cloudinary to provide you with powerful media management capabilities.

Setting Up Cloudinary

Follow these steps to set up Cloudinary with your ANG SILAKBO project:

1

Create a Cloudinary Account

Go to the Cloudinary Sign-up page and create a new account.

2

Get Your API Credentials

After creating your account, go to the Dashboard to find your cloud name, API key, and API secret.

3

Install Cloudinary SDK

Install the Cloudinary SDK in your ANG SILAKBO project using npm:

Terminal

npm install cloudinary
4

Initialize Cloudinary

Create a Cloudinary configuration file in your project:

cloudinary.js

import { v2 as cloudinary } from 'cloudinary';

// Configure Cloudinary
cloudinary.config({
  cloud_name: 'YOUR_CLOUD_NAME',
  api_key: 'YOUR_API_KEY',
  api_secret: 'YOUR_API_SECRET'
});

export default cloudinary;
5

Connect with ANG SILAKBO

Import your Cloudinary configuration into your ANG SILAKBO project:

app.js

import cloudinary from './cloudinary';
import { SILAKBO } from '@silakbo/sdk';

// Initialize ANG SILAKBO with Cloudinary
const silakbo = new SILAKBO({
  cloudinary: cloudinary
});

// Now you can use Cloudinary with ANG SILAKBO
export default silakbo;

Uploading Media to Cloudinary

ANG SILAKBO provides utilities for uploading images, videos, and other media files to Cloudinary.

Upload an Image

import silakbo from './app';

// Server-side upload using file path
async function uploadImage(imagePath, folder = 'general') {
  try {
    const result = await silakbo.cloudinary.uploader.upload(imagePath, {
      folder: folder,
      resource_type: 'image'
    });
    
    console.log('Image uploaded successfully:', result);
    return result;
  } catch (error) {
    console.error('Error uploading image:', error);
    throw error;
  }
}

// Client-side upload using a File object
async function uploadImageFromClient(file, folder = 'general') {
  try {
    // Create a FormData object
    const formData = new FormData();
    formData.append('file', file);
    formData.append('upload_preset', 'YOUR_UNSIGNED_UPLOAD_PRESET'); // Create this in your Cloudinary dashboard
    formData.append('folder', folder);
    
    // Upload the image to Cloudinary
    const response = await fetch(`https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload`, {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    console.log('Image uploaded successfully:', result);
    return result;
  } catch (error) {
    console.error('Error uploading image:', error);
    throw error;
  }
}

Upload a Video

import silakbo from './app';

// Server-side upload using file path
async function uploadVideo(videoPath, folder = 'videos') {
  try {
    const result = await silakbo.cloudinary.uploader.upload(videoPath, {
      folder: folder,
      resource_type: 'video',
      eager: [
        { format: 'mp4', transformation: [
          { width: 640, crop: 'scale' },
          { quality: 'auto' }
        ]}
      ],
      eager_async: true
    });
    
    console.log('Video uploaded successfully:', result);
    return result;
  } catch (error) {
    console.error('Error uploading video:', error);
    throw error;
  }
}

Upload with Progress Tracking

import silakbo from './app';

// Client-side upload with progress tracking
function uploadWithProgress(file, folder = 'general', progressCallback) {
  return new Promise((resolve, reject) => {
    // Create a FormData object
    const formData = new FormData();
    formData.append('file', file);
    formData.append('upload_preset', 'YOUR_UNSIGNED_UPLOAD_PRESET');
    formData.append('folder', folder);
    
    // Create a new XMLHttpRequest
    const xhr = new XMLHttpRequest();
    
    // Track upload progress
    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        const progress = Math.round((event.loaded / event.total) * 100);
        progressCallback(progress);
      }
    };
    
    // Handle the response
    xhr.onload = () => {
      if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        resolve(response);
      } else {
        reject(new Error('Upload failed'));
      }
    };
    
    // Handle errors
    xhr.onerror = () => {
      reject(new Error('Upload failed'));
    };
    
    // Open and send the request
    xhr.open('POST', `https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/auto/upload`, true);
    xhr.send(formData);
  });  `https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/auto/upload`, true);
    xhr.send(formData);
  });
}

// Usage example
async function handleFileUpload(file) {
  try {
    const result = await uploadWithProgress(file, 'user_uploads', (progress) => {
      console.log(`Upload progress: ${progress}%`);
      updateProgressBar(progress); // Update UI progress bar
    });
    
    console.log('Upload complete:', result);
    return result;
  } catch (error) {
    console.error('Upload failed:', error);
    throw error;
  }
}

Image Transformations

Cloudinary provides powerful image transformation capabilities that you can leverage through ANG SILAKBO.

Basic Transformations

import silakbo from './app';

function getOptimizedImageUrl(publicId, options = {}) {
  // Default transformations
  const defaultTransformations = {
    width: options.width || 800,
    height: options.height || 600,
    crop: options.crop || 'fill',
    quality: options.quality || 'auto',
    format: options.format || 'auto'
  };
  
  // Generate the URL
  const imageUrl = silakbo.cloudinary.url(publicId, {
    transformation: [defaultTransformations]
  });
  
  return imageUrl;
}

// Usage example
const optimizedUrl = getOptimizedImageUrl('folder/image1', {
  width: 500,
  height: 300,
  crop: 'fill',
  quality: 'auto:best'
});

Advanced Transformations

import silakbo from './app';

function getProfilePictureUrl(publicId, options = {}) {
  // Create a round profile picture with a border
  const transformations = [
    {
      width: options.size || 300,
      height: options.size || 300,
      gravity: 'face',
      crop: 'thumb',
      radius: 'max'
    },
    {
      border: '3px_solid_white'
    },
    {
      effect: 'shadow:50'
    }
  ];
  
  // Generate the URL
  const imageUrl = silakbo.cloudinary.url(publicId, {
    transformation: transformations
  });
  
  return imageUrl;
}

function getWatermarkedImageUrl(publicId, options = {}) {
  // Add a watermark to an image
  const transformations = [
    {
      width: options.width || 800,
      crop: 'scale'
    },
    {
      overlay: 'company_logo',
      gravity: 'south_east',
      x: 20,
      y: 20,
      width: 100,
      opacity: 70
    }
  ];
  
  // Generate the URL
  const imageUrl = silakbo.cloudinary.url(publicId, {
    transformation: transformations
  });
  
  return imageUrl;
}

Responsive Images

import silakbo from './app';

function getResponsiveImageSrcSet(publicId, options = {}) {
  // Generate srcset for responsive images
  const breakpoints = options.breakpoints || [320, 480, 640, 768, 1024, 1280, 1536];
  const transformations = {
    crop: options.crop || 'fill',
    quality: options.quality || 'auto'
  };
  
  // Generate srcset string
  const srcset = breakpoints.map(width => {
    const url = silakbo.cloudinary.url(publicId, {
      transformation: [
        { ...transformations, width }
      ]
    });
    
    return `${url} ${width}w`;
  }).join(', ');
  
  return srcset;
}

// Usage in a React component
function ResponsiveImage({ publicId, alt, className }) {
  const srcset = getResponsiveImageSrcSet(publicId);
  const defaultUrl = silakbo.cloudinary.url(publicId, {
    transformation: [
      { width: 800, crop: 'fill', quality: 'auto' }
    ]
  });
  
  return (
    {alt}
  );
}

Advanced Cloudinary Features

ANG SILAKBO integrates with Cloudinary's advanced features like AI-powered content analysis, auto-tagging, and content moderation.

AI Content Analysis

import silakbo from './app';

async function uploadWithAutoTagging(imagePath, folder = 'products') {
  try {
    // Upload image with auto-tagging
    const result = await silakbo.cloudinary.uploader.upload(imagePath, {
      folder: folder,
      resource_type: 'image',
      categorization: 'google_tagging',
      auto_tagging: 0.6 // Confidence threshold (0.0 to 1.0)
    });
    
    console.log('Image uploaded with tags:', result.tags);
    return result;
  } catch (error) {
    console.error('Error uploading image with auto-tagging:', error);
    throw error;
  }
}

async function detectFaces(publicId) {
  try {
    // Get facial detection data for an image
    const result = await silakbo.cloudinary.api.resource(publicId, {
      detection: 'adv_face'
    });
    
    const faceInfo = result.info.detection.adv_face;
    console.log('Face detection results:', faceInfo);
    
    return faceInfo;
  } catch (error) {
    console.error('Error detecting faces:', error);
    throw error;
  }
}

Content Moderation

import silakbo from './app';

async function uploadWithModeration(imagePath, folder = 'user_content') {
  try {
      // Upload image with automatic content moderation
      const result = await silakbo.cloudinary.uploader.upload(imagePath, {
      folder: folder,
      resource_type: 'image',
      moderation: 'aws_rek', // AWS Rekognition moderation
      notification_url: 'https://your-webhook-url.com/cloudinary-moderation'
    });
    
    console.log('Image uploaded with moderation:', result);
    
    // Check moderation status if available immediately
    if (result.moderation) {
      if (result.moderation[0].status === 'rejected') {
        console.log('Image was rejected by moderation');
        // Handle rejected content
        await handleRejectedContent(result.public_id);
      }
    }
    
    return result;
  } catch (error) {
    console.error('Error uploading image with moderation:', error);
    throw error;
  }
}

// Handle webhook notification for moderation results
async function handleModerationWebhook(req, res) {
  const moderationData = req.body;
  
  if (moderationData.moderation && moderationData.moderation.status === 'rejected') {
    // Handle rejected content
    await handleRejectedContent(moderationData.public_id);
  }
  
  res.status(200).send('Webhook received');
}

async function handleRejectedContent(publicId) {
  try {
    // Option 1: Delete the rejected content
    await silakbo.cloudinary.uploader.destroy(publicId);
    
    // Option 2: Move to a quarantine folder for review
    // await silakbo.cloudinary.uploader.rename(publicId, `quarantine/${publicId}`);
    
    // Update your database to mark content as rejected
    await updateContentStatus(publicId, 'rejected');
    
    console.log('Handled rejected content:', publicId);
  } catch (error) {
    console.error('Error handling rejected content:', error);
    throw error;
  }
}

Video Processing

Setting Up Stripe

Follow these steps to set up Stripe with your ANG SILAKBO project:

1

Create a Stripe Account

Go to the Stripe Dashboard and create a new account.

2

Get Your API Keys

After creating your account, go to the Developers > API keys section to find your publishable key and secret key.

3

Install Stripe SDK

Install the Stripe SDK in your ANG SILAKBO project using npm:

Terminal

npm install stripe @stripe/stripe-js @stripe/react-stripe-js
4

Initialize Stripe

Create a Stripe configuration file in your project:

stripe.js (Server-side)

import Stripe from 'stripe';
                                        
                                        const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
                                          apiVersion: '2023-10-16', // Use the latest API version
                                        });
                                        
                                        export default stripe;

stripe.js (Client-side)

import { loadStripe } from '@stripe/stripe-js';
                                        
                                        const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
                                        
                                        export default stripePromise;
5

Connect with ANG SILAKBO

Import your Stripe configuration into your ANG SILAKBO project:

app.js

import stripe from './stripe';
                                        import { SILAKBO } from '@silakbo/sdk';
                                        
                                        // Initialize ANG SILAKBO with Stripe
                                        const silakbo = new SILAKBO({
                                          stripe: stripe
                                        });
                                        
                                        // Now you can use Stripe with ANG SILAKBO
                                        export default silakbo;

Processing Payments with Stripe

ANG SILAKBO provides utilities for processing payments with Stripe, allowing you to accept payments in your application.

Create a Payment Intent (Server-side)

import silakbo from './app';
                                        
                                        async function createPaymentIntent(amount, currency = 'usd', metadata = {}) {
                                          try {
                                            const paymentIntent = await silakbo.stripe.paymentIntents.create({
                                              amount: amount, // Amount in cents
                                              currency: currency,
                                              metadata: metadata,
                                              automatic_payment_methods: {
                                                enabled: true,
                                              },
                                            });
                                            
                                            return {
                                              clientSecret: paymentIntent.client_secret,
                                              id: paymentIntent.id
                                            };
                                          } catch (error) {
                                            console.error('Error creating payment intent:', error);
                                            throw error;
                                          }
                                        }

Payment Form (Client-side)

import React, { useState, useEffect } from 'react';
                                        import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
                                        import stripePromise from './stripe-client';
                                        
                                        // Checkout Form Component
                                        function CheckoutForm({ clientSecret, onSuccess }) {
                                          const stripe = useStripe();
                                          const elements = useElements();
                                          const [isLoading, setIsLoading] = useState(false);
                                          const [errorMessage, setErrorMessage] = useState('');
                                          
                                          const handleSubmit = async (e) => {
                                            e.preventDefault();
                                            
                                            if (!stripe || !elements) {
                                              // Stripe.js has not yet loaded.
                                              return;
                                            }
                                            
                                            setIsLoading(true);
                                            setErrorMessage('');
                                            
                                            // Confirm the payment
                                            const { error, paymentIntent } = await stripe.confirmPayment({
                                              elements,
                                              confirmParams: {
                                                return_url: `${window.location.origin}/payment-success`,
                                              },
                                              redirect: 'if_required',
                                            });
                                            
                                            if (error) {
                                              setErrorMessage(error.message);
                                            } else if (paymentIntent && paymentIntent.status === 'succeeded') {
                                              // Payment succeeded
                                              onSuccess(paymentIntent);
                                            }
                                            
                                            setIsLoading(false);
                                          };
                                          
                                          return (
                                            
{errorMessage && (
{errorMessage}
)} ); } // Payment Container Component function PaymentContainer({ amount, onSuccess }) { const [clientSecret, setClientSecret] = useState(''); useEffect(() => { // Fetch payment intent from your server const fetchPaymentIntent = async () => { try { const response = await fetch('/api/create-payment-intent', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: amount, currency: 'usd' }), }); const data = await response.json(); setClientSecret(data.clientSecret); } catch (error) { console.error('Error fetching payment intent:', error); } }; fetchPaymentIntent(); }, [amount]); return (
{clientSecret && ( )}
); }

API Route for Payment Intent

// pages/api/create-payment-intent.js
                                        import silakbo from '../../app';
                                        
                                        export default async function handler(req, res) {
                                          if (req.method !== 'POST') {
                                            return res.status(405).json({ error: 'Method not allowed' });
                                          }
                                          
                                          try {
                                            const { amount, currency = 'usd', metadata = {} } = req.body;
                                            
                                            // Validate the amount
                                            if (!amount || amount < 50) { // Minimum amount is 50 cents
                                              return res.status(400).json({ error: 'Invalid amount' });
                                            }
                                            
                                            // Create a payment intent
                                            const paymentIntent = await silakbo.stripe.paymentIntents.create({
                                              amount: amount,
                                              currency: currency,
                                              metadata: metadata,
                                              automatic_payment_methods: {
                                                enabled: true,
                                              },
                                            });
                                            
                                            // Return the client secret
                                            res.status(200).json({
                                              clientSecret: paymentIntent.client_secret,
                                              id: paymentIntent.id
                                            });
                                          } catch (error) {
                                            console.error('Error creating payment intent:', error);
                                            res.status(500).json({ error: error.message });
                                          }
                                        }

Subscription Management

ANG SILAKBO provides utilities for managing subscriptions with Stripe, allowing you to implement recurring billing in your application.

Create a Subscription (Server-side)

import silakbo from './app';
                                        
                                        async function createSubscription(customerId, priceId) {
                                          try {
                                            // Create the subscription
                                            const subscription = await silakbo.stripe.subscriptions.create({
                                              customer: customerId,
                                              items: [{ price: priceId }],
                                              payment_behavior: 'default_incomplete',
                                              expand: ['latest_invoice.payment_intent'],
                                            });
                                            
                                            return {
                                              subscriptionId: subscription.id,
                                              clientSecret: subscription.latest_invoice.payment_intent.client_secret,
                                              status: subscription.status
                                            };
                                          } catch (error) {
                                            console.error('Error creating subscription:', error);
                                            throw error;
                                          }
                                        }
                                        
                                        async function createCustomer(email, name) {
                                          try {
                                            // Create a new customer
                                            const customer = await silakbo.stripe.customers.create({
                                              email: email,
                                              name: name
                                            });
                                            
                                            return customer.id;
                                          } catch (error) {
                                            console.error('Error creating customer:', error);
                                            throw error;
                                          }
                                        }

Manage Subscriptions

import silakbo from './app';
                                        
                                        // Get all subscriptions for a customer
                                        async function getCustomerSubscriptions(customerId) {
                                          try {
                                            const subscriptions = await silakbo.stripe.subscriptions.list({
                                              customer: customerId,
                                              status: 'all',
                                              expand: ['data.default_payment_method']
                                            });
                                            
                                            return subscriptions.data;
                                          } catch (error) {
                                            console.error('Error fetching subscriptions:', error);
                                            throw error;
                                          }
                                        }
                                        
                                        // Cancel a subscription
                                        async function cancelSubscription(subscriptionId) {
                                          try {
                                            const canceledSubscription = await silakbo.stripe.subscriptions.cancel(subscriptionId);
                                            return canceledSubscription;
                                          } catch (error) {
                                            console.error('Error canceling subscription:', error);
                                            throw error;
                                          }
                                        }
                                        
                                        // Update a subscription
                                        async function updateSubscription(subscriptionId, newPriceId) {
                                          try {
                                            // Get the subscription
                                            const subscription = await silakbo.stripe.subscriptions.retrieve(subscriptionId);
                                            
                                            // Get the subscription item ID
                                            const subscriptionItemId = subscription.items.data[0].id;
                                            
                                            // Update the subscription
                                            const updatedSubscription = await silakbo.stripe.subscriptions.update(subscriptionId, {
                                              items: [{
                                                id: subscriptionItemId,
                                                price: newPriceId,
                                              }],
                                            });
                                            
                                            return updatedSubscription;
                                          } catch (error) {
                                            console.error('Error updating subscription:', error);
                                            throw error;
                                          }
                                        }

Subscription Portal

import silakbo from './app';
                                        
                                        // Create a billing portal session
                                        async function createBillingPortalSession(customerId, returnUrl) {
                                          try {
                                            const session = await silakbo.stripe.billingPortal.sessions.create({
                                              customer: customerId,
                                              return_url: returnUrl,
                                            });
                                            
                                            return session.url;
                                          } catch (error) {
                                            console.error('Error creating billing portal session:', error);
                                            throw error;
                                          }
                                        }
                                        
                                        // API route to create a billing portal session
                                        // pages/api/create-portal-session.js
                                        export default async function handler(req, res) {
                                          if (req.method !== 'POST') {
                                            return res.status(405).json({ error: 'Method not allowed' });
                                          }
                                          
                                          try {
                                            const { customerId } = req.body;
                                            
                                            if (!customerId) {
                                              return res.status(400).json({ error: 'Customer ID is required' });
                                            }
                                            
                                            const returnUrl = `${process.env.NEXT_PUBLIC_APP_URL}/account`;
                                            
                                            const portalUrl = await createBillingPortalSession(customerId, returnUrl);
                                            
                                            res.status(200).json({ url: portalUrl });
                                          } catch (error) {
                                            console.error('Error creating portal session:', error);
                                            res.status(500).json({ error: error.message });
                                          }
                                        }

Stripe Webhooks

Stripe webhooks allow you to receive notifications about events that happen in your Stripe account. ANG SILAKBO provides utilities for handling Stripe webhooks in your application.

Webhook Handler

import silakbo from './app';
                                        import { buffer } from 'micro';
                                        
                                        // Disable body parsing, need the raw body for webhook signature verification
                                        export const config = {
                                          api: {
                                            bodyParser: false,
                                          },
                                        };
                                        
                                        // Webhook handler
                                        // pages/api/webhooks/stripe.js
                                        export default async function handler(req, res) {
                                          if (req.method !== 'POST') {
                                            return res.status(405).json({ error: 'Method not allowed' });
                                          }
                                          
                                          const buf = await buffer(req);
                                          const sig = req.headers['stripe-signature'];
                                          const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
                                          
                                          let event;
                                          
                                          try {
                                            // Verify the webhook signature
                                            event = silakbo.stripe.webhooks.constructEvent(buf, sig, webhookSecret);
                                          } catch (error) {
                                            console.error(`Webhook signature verification failed: ${error.message}`);
                                            return res.status(400).json({ error: error.message });
                                          }
                                          
                                          // Handle the event
                                          try {
                                            switch (event.type) {
                                              case 'payment_intent.succeeded':
                                                await handlePaymentIntentSucceeded(event.data.object);
                                                break;
                                                
                                              case 'payment_intent.payment_failed':
                                                await handlePaymentIntentFailed(event.data.object);
                                                break;
                                                
                                              case 'customer.subscription.created':
                                                await handleSubscriptionCreated(event.data.object);
                                                break;
                                                
                                              case 'customer.subscription.updated':
                                                await handleSubscriptionUpdated(event.data.object);
                                                break;
                                                
                                              case 'customer.subscription.deleted':
                                                await handleSubscriptionDeleted(event.data.object);
                                                break;
                                                
                                              case 'invoice.payment_succeeded':
                                                await handleInvoicePaymentSucceeded(event.data.object);
                                                break;
                                                
                                              case 'invoice.payment_failed':
                                                await handleInvoicePaymentFailed(event.data.object);
                                                break;
                                                
                                              default:
                                                console.log(`Unhandled event type: ${event.type}`);
                                            }
                                            
                                            res.status(200).json({ received: true });
                                          } catch (error) {
                                            console.error(`Error handling webhook: ${error.message}`);
                                            res.status(500).json({ error: error.message });
                                          }
                                        }
                                        
                                        // Event handlers
                                        async function handlePaymentIntentSucceeded(paymentIntent) {
                                          // Update your database
                                          // For example, mark an order as paid
                                          console.log('Payment succeeded:', paymentIntent.id);
                                          
                                          // Get the customer ID from the payment intent
                                          const customerId = paymentIntent.customer;
                                          
                                          // Update the customer's payment status in your database
                                          await updateCustomerPaymentStatus(customerId, 'succeeded');
                                        }
                                        
                                        async function handlePaymentIntentFailed(paymentIntent) {
                                          console.log('Payment failed:', paymentIntent.id);
                                          
                                          // Get the customer ID from the payment intent
                                          const customerId = paymentIntent.customer;
                                          
                                          // Update the customer's payment status in your database
                                          await updateCustomerPaymentStatus(customerId, 'failed');
                                        }
                                        
                                        async function handleSubscriptionCreated(subscription) {
                                          console.log('Subscription created:', subscription.id);
                                          
                                          // Get the customer ID from the subscription
                                          const customerId = subscription.customer;
                                          
                                          // Update the customer's subscription status in your database
                                          await updateCustomerSubscription(customerId, subscription);
                                        }
                                        
                                        async function handleSubscriptionUpdated(subscription) {
                                          console.log('Subscription updated:', subscription.id);
                                          
                                          // Get the customer ID from the subscription
                                          const customerId = subscription.customer;
                                          
                                          // Update the customer's subscription status in your database
                                          await updateCustomerSubscription(customerId, subscription);
                                        }
                                        
                                        async function handleSubscriptionDeleted(subscription) {
                                          console.log('Subscription deleted:', subscription.id);
                                          
                                          // Get the customer ID from the subscription
                                          const customerId = subscription.customer;
                                          
                                          // Update the customer's subscription status in your database
                                          await removeCustomerSubscription(customerId, subscription.id);
                                        }
                                        
                                        async function handleInvoicePaymentSucceeded(invoice) {
                                          console.log('Invoice payment succeeded:', invoice.id);
                                          
                                          // Get the customer ID from the invoice
                                          const customerId = invoice.customer;
                                          
                                          // Update the customer's invoice status in your database
                                          await updateCustomerInvoice(customerId, invoice, 'paid');
                                        }
                                        
                                        async function handleInvoicePaymentFailed(invoice) {
                                          console.log('Invoice payment failed:', invoice.id);
                                          
                                          // Get the customer ID from the invoice
                                          const customerId = invoice.customer;
                                          
                                          // Update the customer's invoice status in your database
                                          await updateCustomerInvoice(customerId, invoice, 'failed');
                                        }

Frequently Asked Questions

Can I use multiple third-party integrations at the same time?

Yes, ANG SILAKBO is designed to work with multiple third-party integrations simultaneously. You can use Firebase for authentication, Supabase for database, and Cloudinary for media storage, all in the same application. Our SDK provides a unified interface for working with these services, making it easy to use them together.

How do I secure my API keys and credentials?

When working with third-party services, it's important to keep your API keys and credentials secure. For server-side applications, store your credentials in environment variables or a secure key management system. For client-side applications, use services like Firebase or Supabase that provide client SDKs with built-in security measures.

Never expose sensitive API keys or secrets in your client-side code. Instead, create server routes that handle sensitive operations and use those routes from your client code.

How do I handle errors from third-party services?

ANG SILAKBO provides a unified error handling system for all third-party integrations. When an error occurs, the SDK will throw an error with information about the service that caused the error and the nature of the error.

We recommend using try-catch blocks around your API calls to catch and handle errors appropriately. You can also implement retry logic for transient errors and fallback mechanisms for critical services.

Can I switch between different providers later?

Yes, ANG SILAKBO's abstraction layer makes it easier to switch between different providers. While it's not entirely seamless (as each service has unique features), the SDK provides a consistent interface that minimizes the changes needed.

We recommend creating service adapters in your application that wrap the SDK calls. This way, if you need to switch providers, you only need to update your adapter code rather than changing calls throughout your application.

What about rate limiting and usage quotas?

Each third-party service has its own rate limits and usage quotas. ANG SILAKBO does not manage these directly, so you should be aware of the limitations of each service you use.

For high-traffic applications, consider implementing caching strategies and rate limiting in your application to avoid hitting service limits. You can also monitor your usage through each service's dashboard and set up alerts for when you approach your limits.