WhatsApp Checkout

francis-igbiriki

francis-igbiriki

View Profile
77 views
Oct 13, 2025
Updated Oct 13, 2025
/**
 * Format price with currency symbol
 */
export function formatPrice(price: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(price);
}

/**
 * Generate WhatsApp message templates for different contexts
 */
export function generateWhatsAppMessage(message: WhatsAppMessage): string {
  if (message.messageType === 'cart' && message.cartItems && message.cartItems.length > 0) {
    return generateCartWhatsAppMessage(message.cartItems, message.totalPrice || 0);
  } else if (message.messageType === 'product-specific' && message.productName) {
    let messageText = `Hi! I'm interested in the ${message.productName}`;
    
    if (message.condition) {
      messageText += ` (${message.condition})`;
    }
    
    if (message.price) {
      messageText += ` listed for ${formatPrice(message.price)}`;
    }
    
    messageText += '. Is it still available?';
    return messageText;
  } else {
    return 'Hi! I\'d like to know more about your products. Can you help me?';
  }
}

/**
 * Generate WhatsApp URL with pre-filled message
 */
export function generateWhatsAppUrl(
  phoneNumber: string,
  message: WhatsAppMessage
): string {
  try {
    // Validate phone number format (basic validation)
    const cleanPhoneNumber = phoneNumber.replace(/\D/g, '');
    if (!cleanPhoneNumber || cleanPhoneNumber.length < 10) {
      throw new Error('Invalid phone number format');
    }
    
    const messageText = generateWhatsAppMessage(message);
    const encodedMessage = encodeURIComponent(messageText);
    
    return `https://wa.me/${cleanPhoneNumber}?text=${encodedMessage}`;
  } catch (error) {
    console.error('Error generating WhatsApp URL:', error);
    // Return fallback URL without message
    return `https://wa.me/${phoneNumber.replace(/\D/g, '')}`;
  }
}

/**
 * Create WhatsApp message for product inquiry
 */
export function createProductWhatsAppMessage(product: Product): WhatsAppMessage {
  return {
    productId: product.id,
    productName: product.name,
    price: product.price,
    condition: product.condition,
    messageType: 'product-specific'
  };
}

/**
 * Create general WhatsApp message
 */
export function createGeneralWhatsAppMessage(): WhatsAppMessage {
  return {
    messageType: 'general'
  };
}

/**
 * Create WhatsApp message for cart inquiry
 */
export function createCartWhatsAppMessage(cartItems: Array<{
  product: Product;
  quantity: number;
}>, totalPrice: number, totalItems: number): WhatsAppMessage {
  return {
    messageType: 'cart',
    cartItems,
    totalPrice,
    totalItems
  };
}

/**
 * Handle WhatsApp integration with fallback
 */
export function openWhatsApp(
  phoneNumber: string,
  message: WhatsAppMessage,
  fallbackCallback?: (phoneNumber: string) => void
): void {
  try {
    const whatsappURL = generateWhatsAppUrl(phoneNumber, message);
    
    // Check if WhatsApp is available (basic check)
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );
    
    if (isMobile) {
      // On mobile, try to open WhatsApp app first
      window.location.href = whatsappURL;
    } else {
      // On desktop, open in new tab
      const newWindow = window.open(whatsappURL, '_blank', 'noopener,noreferrer');
      
      // If popup was blocked, try alternative
      if (!newWindow) {
        window.location.href = whatsappURL;
      }
    }
  } catch (error) {
    console.error('Failed to open WhatsApp:', error);
    
    // Execute fallback callback if provided
    if (fallbackCallback) {
      fallbackCallback(phoneNumber);
    } else {
      // Default fallback: copy phone number to clipboard or show alert
      if (navigator.clipboard) {
        navigator.clipboard.writeText(phoneNumber).then(() => {
          alert(`WhatsApp failed to open. Phone number ${phoneNumber} copied to clipboard.`);
        }).catch(() => {
          alert(`Please contact us at: ${phoneNumber}`);
        });
      } else {
        alert(`Please contact us at: ${phoneNumber}`);
      }
    }
  }
}

/**
 * Calculate cart item subtotal
 */
export function calculateCartItemSubtotal(price: number, quantity: number): number {
  return price * quantity;
}

/**
 * Format cart summary for display
 */
export function formatCartSummary(totalItems: number, totalPrice: number): string {
  const itemText = totalItems === 1 ? 'item' : 'items';
  return `${totalItems} ${itemText} • ${formatPrice(totalPrice)}`;
}

/**
 * Generate cart message for WhatsApp
 */
export function generateCartWhatsAppMessage(cartItems: Array<{
  product: Product;
  quantity: number;
}>, totalPrice: number): string {
  if (cartItems.length === 0) {
    return 'Hi! I\'d like to know more about your products. Can you help me?';
  }

  let message = 'Hi! I\'m interested in purchasing the following items from Hikari:\n\n';
  message += '📱 *ORDER DETAILS*\n';
  message += '━━━━━━━━━━━━━━━━━━━━\n\n';
  
  cartItems.forEach((item, index) => {
    const subtotal = calculateCartItemSubtotal(item.product.price, item.quantity);
    message += `${index + 1}. *${item.product.name}*\n`;
    message += `   • Brand: ${item.product.brand}\n`;
    message += `   • Condition: ${item.product.condition.charAt(0).toUpperCase() + item.product.condition.slice(1)}\n`;
    message += `   • Quantity: ${item.quantity}x\n`;
    message += `   • Unit Price: ${formatPrice(item.product.price)}\n`;
    message += `   • Subtotal: ${formatPrice(subtotal)}\n\n`;
  });

  message += '━━━━━━━━━━━━━━━━━━━━\n';
  message += `💰 *TOTAL AMOUNT: ${formatPrice(totalPrice)}*\n\n`;
  message += '❓ Are these items still available?\n';
  message += '📦 What are the delivery options?\n';
  message += '💳 What payment methods do you accept?\n\n';
  message += 'Looking forward to your response!';

  return message;
}