Skip to content

[Phase 3] Facebook Shop Integration — Full Meta API, Webhooks, and OAuth Integration #153

@syed-reza98

Description

@syed-reza98

Here’s a summary of the official Meta/Facebook developer documentation covering integration with Facebook Shops (catalog creation & syncing), Graph API webhooks (orders, messages), OAuth login for Pages, permissions, verifications, and key endpoints and procedures:

1. Facebook Shops & Product Catalogue APIs

  • Meta Commerce Manager is the primary dashboard for setting up and managing Facebook Shops and product catalogues. Developers can create, sync, and update product catalogues via APIs or integrations (e.g., Shopify, WooCommerce)[1][2][3].
  • The Product Catalogue API lets you:
    • Create catalogues (/v19.0/{business_id}/owned_product_catalogs)
    • Add/update products (/v19.0/{catalog_id}/products)
    • Batch update using the /batch endpoint, providing JSON files or CSV via URLs. Batch operations are recommended for syncing large catalogues, and you should monitor job status and error reports via Graph API responses.
    • Collections can be managed via Commerce Manager or API, but Shopify collections only sync to Facebook for US-based stores; otherwise, manual creation is needed in Commerce Manager[1].

2. OAuth Login for Page/Admin Integration

  • OAuth 2.0 flow is used for authenticating users, granting app permissions, and accessing Page assets. The process involves:
    • Registering your app in the Facebook Developer Portal, obtaining App ID/Secret, and specifying callback URLs
    • Initiating OAuth dialogues (https://www.facebook.com/v19.0/dialog/oauth), requesting scopes/permissions such as pages_manage_metadata, pages_read_engagement, pages_show_list, and ads_management for advanced catalogue or Shop features
  • You’ll need to undergo app review for permissions beyond public profile and email (e.g., managing pages, handling shops/catalogs, or messaging customers)[4][5][6].

3. Webhooks (Orders, Messages, Verification & Signature)

  • Webhooks relay realtime updates for orders, messages, and other events:
    • Register a webhook endpoint in your app dashboard, specifying the object (e.g., order, page, message)
    • On webhook subscription, Meta sends a verification request (hub.challenge) to your endpoint which you must echo to confirm setup
  • For message and order events, webhooks POST payloads with a signature (X-Hub-Signature) calculated using your app secret (SHA1 HMAC). Always validate this signature for security before processing the payload.
  • Refer to the Graph API webhook docs for supported event types and payload structure:
    • Orders: commerce_order object webhooks
    • Page messages: page object webhooks for Messenger conversations[5][6].

4. Messaging/Conversations APIs

  • Use Messenger Platform APIs to:
    • List, retrieve, and respond to page conversations (/{page_id}/conversations, /{conversation_id}/messages, /{message_id})
    • Send messages (/me/messages endpoint)
  • You must subscribe your app to the page and approve necessary permissions (pages_messaging, pages_manage_metadata). For persistent messaging access, review and approval are required via the App Review dashboard.

5. Verification, Permissions, App Review, and Domain Verification

  • App verification steps include:
    • Email & business verification in the Facebook Developer Portal
    • Domain verification via DNS or HTML file upload (essential for shops, catalogues, and Messenger/WhatsApp integrations)
    • Permissions approval via App Review, especially for sensitive scopes or advanced commerce/messaging features
    • Commerce eligibility: Your business must meet Meta’s Commerce Eligibility Requirements, pass product review, and agree to Meta’s commerce policies; product uploads are reviewed and may be rejected if requirements aren't met[7].

Key Official Meta Graph API Endpoints

  • Product Catalogue: /v19.0/{catalog_id}/products (CRUD and batch sync)
  • Commerce Order Webhooks: /{page_id}/commerce_orders
  • Page Messaging: /{page_id}/conversations and /me/messages
  • OAuth: https://www.facebook.com/v19.0/dialog/oauth
  • Business Verification: via Commerce Manager/Business Settings dashboard

Additional Guidance from Meta Docs

  • Use the Graph API Explorer for testing queries and debugging API calls
  • Monitor permission, rate limits, and error codes closely in API responses
  • Always validate X-Hub-Signature for webhook calls to ensure authenticity
  • Stay compliant with Meta Commerce and Community Policies for all catalogue/product interactions[1][2][5][7].

For authoritative, in-depth integration steps and API references, visit the Meta for Developers documentation and Meta Business Help Center for shop/catalog/commerce-specific guides.


  1. Publishing products on Facebook and Instagram by Meta
  2. How to Connect Shopify Catalog to Facebook - avada.io
  3. Facebook Shop and Shopify: Complete Integration Guide
  4. Facebook API Guide for New Developers Step by Step | MoldStud
  5. Facebook API Explained : Features, Types, & How to Use It
  6. Facebook for Developers: How to Use Facebook for Developers to Build ...
  7. Facebook Shops - BigCommerce

Purpose

Enable merchants to list StormCom products in Facebook Shop (catalog), keep product and inventory data synchronized, import Facebook orders into StormCom, and surface page conversations/messages to merchants — fully integrated, production-grade (OAuth, webhooks, retries, error reporting, app verification).

Primary Meta docs to read and use (authoritative)

dependencies (explicit permalinks)

Technical scope & concrete implementation plan

  1. Authentication & App registration

    • Register app in Facebook Developer Portal (App ID & Secret)
    • Implement OAuth 2.0 Page connect flow requesting:
      • pages_manage_metadata, pages_read_engagement, pages_read_user_content (read page content), pages_manage_ads (if needed), pages_messaging (if message forwarding), business_management, commerce_management
    • Store short-lived Page access token and exchange for long-lived token where applicable. Persist encrypted tokens in DB.
    • File locations:
      • OAuth start: src/app/dashboard/integrations/facebook/connect.tsx (client)
      • OAuth callback: src/app/api/integrations/facebook/oauth/callback/route.ts
  2. App Review & Domain Verification

    • Domain verification in Business Settings (DNS HTML file) is required for some commerce features and for Messenger webhook verification.
    • Prepare App Review submission with screencasts and test users for these permissions (pages_messaging, commerce_management).
    • Ensure business verification (Business Manager) for commerce capability.
  3. Catalog creation & product sync (recommended pattern)

    • Create/attach a Catalog: POST /v{api_version}/{business_id}/owned_product_catalogs
    • Product creation/upsert:
      • Create product: POST /v{api_version}/{catalog_id}/products with required fields (id, title, description, availability, currency, price, image_url, gtin/sku)
      • Use batch update for large sets:
        • Upload CSV/JSON to an accessible URL or use batch operations (monitor job status)
        • Monitor import status, parse errors, and correlate external IDs for reconciliation
    • Implementation sketch:
      • Connector: src/lib/integrations/facebook.connector.ts (implement connect, createCatalog, pushProductsBatch, updateInventory)
      • API route to trigger sync: src/app/api/integrations/facebook/catalog/sync/route.ts
      • Background job worker for batching and retry (BullMQ / Redis queue): src/lib/queues/facebook-sync.worker.ts
  4. Inventory updates & conflict handling

    • On StormCom inventory change:
      • Update central inventory and enqueue update jobs to connector.updateInventory(productExternalId, newQty)
    • Implement per-channel InventorySnapshot table to record lastSyncAt and last known channel quantity
      • Prisma model: InventorySnapshot { id, storeId, productId, channel, externalProductId, quantity, lastSyncAt, lastError }
    • Retry policy: exponential backoff, 3 attempts, escalate to merchant on repeated failure
  5. Orders & webhooks

    • Webhook route: src/app/api/webhooks/facebook/route.ts
      • Must implement verification handshake (respond to hub.challenge)
      • Validate X-Hub-Signature (HMAC with app secret) before processing
      • Supported webhook objects to subscribe:
        • orders / commerce events (commerce_order updates)
        • page for messages and conversations
    • On order.created from FB:
      • Deduplicate by external_order_id; if new → create StormCom Order (source="FACEBOOK"), decrement inventory transactionally, send confirmation email
    • Maintain mapping table: ExternalOrderMapping { storeId, externalOrderId, localOrderId }
  6. Messaging / conversations

    • Use Page Conversations APIs:
      • GET /v{api_version}/{page_id}/conversations (list)
      • GET /v{api_version}/{conversation_id}/messages
      • Respond via /me/messages with Page access token
    • For incoming messages (webhook event messages or messaging), create vendor-side conversation threads in dashboard (src/app/dashboard/messages)
    • Respect rate limits and ensure the page has messaging permissions approved
  7. Health & monitoring

    • Integration status: lastSyncAt, lastError, errorCount visible in dashboard UI
    • Logs for each product push, inventory update, and order import
    • Alert merchant by email when sync repeatedly fails
  8. Security & compliance

    • Validate webhook signature (X-Hub-Signature); confirm request body raw string used for HMAC SHA1 (or signature as per Graph API doc version)
    • Use appsecret_proof on outgoing Graph API calls to improve security
    • Encrypt tokens at rest (KMS or environment-based secret)
    • Respect policy: do not store or misuse customer personal data beyond order handling and required functions

Acceptance criteria (user-facing)

  • Dashboard "Connect Facebook" button starts OAuth and completes Page connect flow.
  • OAuth callback securely stores page tokens (encrypted) and shows connected page(s) in integration UI.
  • StormCom can create or link a Facebook Catalog for the merchant.
  • Products pushed from StormCom appear in Catalog and in Page Shop; images, variants, price fields map correctly.
  • Inventory updates from StormCom reflect on Facebook within the configured SLA (target < 30s for small updates; batching allowed).
  • Facebook orders are imported into StormCom with deduplication and proper order.source field (FACEBOOK).
  • Page messages surface in vendor dashboard and vendor can respond (or forward to email).
  • Integration health dashboard (last sync time, error count) present and accurate.
  • App review & domain verification steps documented and executed for required permissions.

Testing checklist

  • App OAuth works end-to-end with test Page and test user (short-lived token → exchange to long-lived token).
  • Create a catalog and push ~100 products; verify mapping and images appear in Commerce Manager.
  • Simulate webhook order created and verify StormCom order import and inventory decrement.
  • Simulate webhook message event and verify message appears in vendor dashboard.
  • Simulate failures (rate limit, API error) and validate retry/backoff and merchant alert.
  • Validate webhook signature verification rejects tampered payloads.

Suggested DB models & routes (concrete)

  • Prisma models (examples):
    • FacebookIntegration { id, storeId, pageId, pageAccessTokenEncrypted, catalogId, connectedAt, lastSyncAt, status }
    • InventorySnapshot { id, storeId, productId, channel: 'FACEBOOK', externalProductId, quantity, lastSyncAt, lastError }
    • ExternalOrderMapping { id, storeId, channel: 'FACEBOOK', externalOrderId, localOrderId, createdAt }
  • API routes:
    • POST /api/integrations/facebook/connect (start OAuth)
    • GET /api/integrations/facebook/oauth/callback (OAuth callback)
    • POST /api/integrations/facebook/catalog/sync (enqueue sync job)
    • POST /api/webhooks/facebook (single webhook receiver; dispatch internally)
    • GET /api/integrations/facebook/status (integration health)

References (Meta docs you should read fully)

Notes & recommendations

  • Start with a sandboxed Facebook App and a test Page. Use the Graph API Explorer and test users to validate flows before requesting App Review.
  • Implement the connector incrementally: OAuth + Webhook verification + simple product create/update → orders → messages → batch sync for large catalogs.
  • Use background jobs for batch uploads and inventory updates (avoid blocking request threads).
  • Maintain robust logs and a reconciliation UI for merchants to resolve missed items or conflicts manually.

If you want I can:

  • create a draft PR that adds the connector skeleton files, the webhook receiver route, and the Prisma models (InventorySnapshot, FacebookIntegration, ExternalOrderMapping) so the team can iterate on implementation; or
  • open a PR that only updates the GitHub issue body with the refined content above (I can do either — tell me which).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions