How to Build a DeepSeek WhatsApp Integration with V4 (2026)

DeepSeek WhatsApp integration: build a bot with deepseek-flash and Meta's Cloud API. Python webhook code, setup steps and peak/off-peak cost math.

Tutorials·April 25, 2026·By DS Guide Editorial
DeepSeek WhatsApp integration title card: eyebrow 'Tutorial · WhatsApp Cloud API', title 'WhatsApp Integration', tagline 'deepseek-flash via Meta's Cloud API; USD per 1M tokens.', and four stats: 0.30 Flash miss, peak (deepseek-flash cache-miss input price); 1.20 Flash out, peak (deepseek-flash output price); 24H service window (WhatsApp customer service window); 4096 text body chars (Meta's text message limit), beside a compact-desktop illustration.

You want users to message your business on WhatsApp and get answers from a model you actually trust — not a brittle keyword tree. This guide walks through a working DeepSeek WhatsApp integration end to end: a Python webhook receiver that listens to Meta’s WhatsApp Cloud API, forwards each message to deepseek-flash, and replies back inside the 24-hour customer service window. By the end you’ll have a deployed bot, a cost model you can check line by line, and a note on migrating code that still uses the retired deepseek-chat ID. Code is in Python with FastAPI; the same pattern works in Node.js. Expect about an afternoon of work to reach a live test number.

What you’ll build

Illustration: Smartphone showing a WhatsApp-style chat where a DeepSeek V4 assistant replies to a user request.

The architecture is three moving parts: WhatsApp Cloud API on Meta’s side, a public HTTPS webhook on your side, and DeepSeek’s POST /chat/completions endpoint for inference. When a user messages your business number, Meta posts a JSON payload to your webhook; your handler extracts the text, calls DeepSeek, and posts the reply back through Meta’s Graph API. DeepSeek’s Flash model (API name deepseek-flash, currently served by DeepSeek-V4.1-Flash-1017) is the right tier here — as of 12 November 2026 it costs $0.30 per million input tokens on a cache miss and $1.20 per million output tokens at peak, and half that off-peak ($0.15 / $0.60), which keeps per-conversation cost in fractions of a cent.

A note on the model choice. DeepSeek’s API offers two models: deepseek-flash and deepseek-v4-pro (currently DeepSeek-V4-Pro-0813). For chat-style customer messages, Flash is plenty. Reserve Pro for agentic coding or research workflows where its extra capability is worth the cost gap: at either period, Pro’s output price is 3.3 times Flash’s ($3.96 ÷ $1.20 at peak).

Prerequisites

  • A Meta Business account (Business Manager) with admin access
  • A Meta for Developers account and a new app with the WhatsApp product added
  • A phone number that can receive SMS or voice for verification — a fresh number is easiest
  • A public HTTPS endpoint for the webhook (ngrok works for testing; Cloud Run, Fly.io, or AWS Lambda for production)
  • A DeepSeek API key — see how to get a DeepSeek API key
  • Python 3.11+ with fastapi, uvicorn, httpx, and the openai SDK

Meta’s prerequisite list maps cleanly: a Business Manager admin account, a Meta Developer account, a phone number that can receive SMS or voice for verification, a public HTTPS endpoint for webhooks, and a basic server (Node, PHP, or in our case Python) to store tokens and call the Graph API.

Step 1: Create the Meta app and connect WhatsApp

In the Meta App Dashboard, create a new app with the use case “Connect with customers through WhatsApp” and choose your business portfolio (the flow described in Meta’s WhatsApp Cloud API get-started guide, checked 12 November 2026). On the API Setup page, connect the app to a WhatsApp Business Account — Meta’s docs now call it a Messaging account — and save its ID for use in API calls. From the same page, copy the test phone number ID and generate a temporary access token.

Meta’s guide says the temporary token “expires quickly and is not suitable for development purposes”. For anything beyond a first test, follow Meta’s instructions to create a System User in Business Settings and generate a permanent token with the business_management, whatsapp_business_messaging and whatsapp_business_management permissions; otherwise your bot will stop sending once the temporary token lapses.

Step 2: Stand up a webhook receiver

The webhook has two jobs. On GET, it answers Meta’s verification handshake by checking hub.verify_token and responding with HTTP 200 and the hub.challenge value. On POST, it receives inbound messages and acknowledges them with HTTP 200. According to Meta’s webhook docs (checked 12 November 2026), a delivery that gets any status other than 200 is retried with decreasing frequency for up to 7 days, and retries can produce duplicate notifications — so return 200 straight away and push the DeepSeek call to a background task.

Save the following as main.py. It uses FastAPI plus a background task so the HTTP response is immediate. The Graph API URL uses v27.0, the version in Meta’s text-message example (checked 12 November 2026).

import os
import httpx
from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
from fastapi.responses import PlainTextResponse
from openai import AsyncOpenAI

VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]
WA_TOKEN     = os.environ["WA_ACCESS_TOKEN"]
PHONE_ID     = os.environ["WA_PHONE_NUMBER_ID"]
GRAPH_URL    = f"https://graph.facebook.com/v27.0/{PHONE_ID}/messages"

deepseek = AsyncOpenAI(
    base_url="https://api.deepseek.com",
    api_key=os.environ["DEEPSEEK_API_KEY"],
)

app = FastAPI()

@app.get("/webhook")
async def verify(request: Request):
    params = request.query_params
    if (params.get("hub.mode") == "subscribe"
            and params.get("hub.verify_token") == VERIFY_TOKEN):
        return PlainTextResponse(params.get("hub.challenge", ""))
    raise HTTPException(status_code=403)

@app.post("/webhook")
async def receive(request: Request, background: BackgroundTasks):
    payload = await request.json()
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            if change.get("field") != "messages":
                continue
            for msg in change.get("value", {}).get("messages", []):
                if msg.get("type") == "text":
                    background.add_task(handle_message, msg)
    # status callbacks and other event shapes carry no "messages" and are ignored
    return {"status": "ok"}

The verification branch matches the pattern in Meta’s own developer docs: the endpoint compares hub.verify_token with the string stored on your server and returns the hub.challenge value with HTTP 200. The POST branch loops over every entry, change and message (Meta batches notifications) and tolerates non-text payloads (status receipts, reactions, media) without crashing.

Step 3: Wire DeepSeek into the message handler

Chat requests hit POST /chat/completions, the OpenAI-compatible endpoint at https://api.deepseek.com. The OpenAI Python SDK works unchanged — only base_url and api_key change. Critically, the API is stateless: DeepSeek does not remember prior turns on its side, so for multi-turn chat you must resend the conversation history with each request. Plan for a small per-user message store (Redis, DynamoDB, Postgres) if you need memory.

For this minimal bot, we’ll keep a tiny in-memory store keyed by the sender’s business-scoped user ID (from_user_id). Meta’s webhook reference (checked 12 November 2026) says that ID is always included, while the phone-number field from is omitted when a user has adopted a username and their number is unavailable. Replace the store with a real database before production.

HISTORY: dict[str, list[dict]] = {}

SYSTEM_PROMPT = (
    "You are a concise WhatsApp assistant for ACME Coffee. "
    "Answer in under 60 words. If you do not know, say so."
)

async def handle_message(msg: dict):
    user_key = msg.get("from_user_id") or msg["from"]
    history = HISTORY.setdefault(user_key, [])
    history.append({"role": "user", "content": msg["text"]["body"]})

    resp = await deepseek.chat.completions.create(
        model="deepseek-flash",
        messages=[{"role": "system", "content": SYSTEM_PROMPT}] + history,
        extra_body={"thinking": {"type": "disabled"}},  # non-thinking mode
        temperature=1.3,        # general conversation (non-thinking mode only)
        max_tokens=400,
    )
    reply = (resp.choices[0].message.content or "").strip()
    if not reply:
        return  # nothing usable came back; see the fallback tip below
    history.append({"role": "assistant", "content": reply})
    HISTORY[user_key] = history[-20:]  # keep last 10 turns

    # reply by phone number when Meta sent one, otherwise by business-scoped user ID
    to_field = {"to": msg["from"]} if msg.get("from") else {"recipient": msg["from_user_id"]}
    async with httpx.AsyncClient(timeout=15) as client:
        r = await client.post(
            GRAPH_URL,
            headers={"Authorization": f"Bearer {WA_TOKEN}"},
            json={
                "messaging_product": "whatsapp",
                "recipient_type": "individual",
                **to_field,
                "type": "text",
                "text": {"body": reply[:4096]},  # Meta's text body limit
            },
        )
        r.raise_for_status()

Four parameter choices to flag. model="deepseek-flash" targets the cost-efficient tier directly. Thinking mode is DeepSeek’s default, so extra_body={"thinking": {"type": "disabled"}} switches to non-thinking mode for quick chat replies. temperature=1.3 matches DeepSeek’s official guidance for general conversation and translation; it only applies in non-thinking mode, because thinking mode accepts but ignores temperature. max_tokens=400 caps reply length; WhatsApp’s reading experience falls apart past a few short paragraphs, and Meta caps a text message body at 4,096 characters. If you want thinking mode for harder questions, drop the disabled setting and pass reasoning_effort="high" with extra_body={"thinking": {"type": "enabled"}}; the response will then contain reasoning_content alongside the final content, and you should send only the latter back to WhatsApp.

Step 4: Expose the webhook and subscribe in Meta

For local testing, run uvicorn main:app --port 8000 and tunnel through ngrok. In production, deploy behind HTTPS on whatever you already use (Meta’s docs say self-signed certificates are not supported). In the Meta App Dashboard, open your app’s WhatsApp webhook configuration, paste the public URL plus your verify token, and subscribe to the messages field. Meta’s documentation on creating a webhook endpoint confirms this is the right surface to register.

Step 5: Send a test message

Illustration of a phone showing a WhatsApp-style chat in which a ‘ping’ message gets a ‘pong - V4 online’ reply from a DeepSeek assistant contact.

From the API Setup panel in Meta, send the hello_world template to your own WhatsApp number. Reply to that thread with any text. The webhook should fire, your handler should call DeepSeek, and the reply should appear in the thread shortly afterwards. Once your test webhook application is established, respond in the WhatsApp chat thread you created with yourself, then check your test webhook to view the event confirming the message receipt.

Verify it worked

  • Server logs show a 200 response on the POST and the parsed message body
  • The DeepSeek response’s usage object reports the tokens consumed by deepseek-flash
  • The user receives a coherent reply on WhatsApp within a few seconds
  • A second message in the same thread references the first (proving history is being resent)

Cost math: a worked example for deepseek-flash

Pricing as of 12 November 2026 from DeepSeek’s own pricing page, in USD per million tokens for deepseek-flash: input cache hit $0.006 peak / $0.003 off-peak, input cache miss $0.30 / $0.15, output $1.20 / $0.60. Off-peak rates are half the peak rates; peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays, and every other hour is off-peak. For comparison, deepseek-v4-pro costs $0.044 / $0.022 (cache hit), $1.32 / $0.66 (cache miss) and $3.96 / $1.98 (output).

Imagine a busy support line: 100,000 conversations a month, average 6 turns each, 100-token user messages, 200-token replies, with a stable 300-token system prompt that stays cached after the first call. That is 600,000 model calls; cost = tokens ÷ 1,000,000 × rate. The figures below are illustrative arithmetic, not measurements.

Bucket Tokens Rate ($/M), peak / off-peak Cost, peak / off-peak
Input, cache hit (system prompt) 300 × 600,000 = 180,000,000 $0.006 / $0.003 $1.08 / $0.54
Input, cache miss (user turns + history) ~250 × 600,000 = 150,000,000 $0.30 / $0.15 $45.00 / $22.50
Output 200 × 600,000 = 120,000,000 $1.20 / $0.60 $144.00 / $72.00
Total / month $190.08 / $95.04

That is $190.08 if every call ran at peak rates and $95.04 if every call ran off-peak, for 600,000 model calls; a real month lands between the two depending on when your users write. Per conversation, that is $190.08 ÷ 100,000 ≈ $0.0019 at peak and $0.00095 off-peak. Meta bills WhatsApp messaging separately: according to Meta’s pricing page (checked 12 November 2026), Meta has charged per message since 1 July 2025, and since 1 October 2026 each business phone number gets 1,000 delivered service messages a month free, with Meta charging from the 1,001st. Check Meta’s rate card for your market before you budget. For a deeper walkthrough of the DeepSeek rate card, see the breakdown of DeepSeek API pricing and the DeepSeek context caching guide. Do not skip the cache-miss line — every new user message is a miss against the cached prefix until the model sees it again. Don’t mix deepseek-flash and deepseek-v4-pro rates in one calculation; pick a tier and stay in it.

Migrating off legacy model IDs

If you copy-pasted code from a 2025 tutorial, you probably have model="deepseek-chat" or model="deepseek-reasoner" in there. Both IDs were scheduled for retirement on July 24, 2026, 15:59 UTC and are no longer listed on DeepSeek’s Models & Pricing page; until then they routed to deepseek-v4-flash in non-thinking and thinking mode respectively. deepseek-v4-flash itself is still accepted, but that model has been retired: such requests are served by DeepSeek-V4.1-Flash-1017 and billed at the Flash price. The migration is a one-line change to model="deepseek-flash" — base_url stays the same. To keep the old deepseek-chat behaviour, also send extra_body={"thinking": {"type": "disabled"}}, since thinking mode is now the default.

Common errors and fixes

Symptom Likely cause Fix
Webhook verification fails in Meta UI Verify token mismatch or non-200 response Confirm WA_VERIFY_TOKEN matches the value pasted in Meta; return the hub.challenge value as plain text with HTTP 200
The bot answers the same message twice Meta retried a delivery that got a non-200 response or failed; retries can produce duplicate notifications Return 200 immediately, deduplicate on the WhatsApp message id, add timeouts on background work
Bot replies once, then ignores user You’re outside the 24-hour customer service window Either get the user to message first, or send an approved utility template
DeepSeek returns 401 Wrong API key or base URL Confirm base_url="https://api.deepseek.com" and the key is from the DeepSeek console — see API authentication
Replies truncate mid-sentence max_tokens too low Raise to 800–1500 for longer answers; both current DeepSeek models support up to 384,000 output tokens
JSON-mode replies are empty Prompt missing the word “json” or schema; if the output cannot be recognised as JSON, the API replaces it with spaces Add an explicit example schema and the literal word “json” in the system prompt, and handle blank replies (for example, retry)

One more behavioural quirk to internalise: both current DeepSeek models have a context window of 1,000,000 tokens with output up to 384,000 tokens. You will not hit either limit on a WhatsApp bot, but the headroom means you can stash long policy documents in the system prompt and trust the cache pricing to keep costs sane.

Hardening for production

Architecture diagram of a WhatsApp Cloud API integration routing messages to DeepSeek V4 and back.
  • Persist history. Replace the in-memory HISTORY dict with Redis keyed by the user’s business-scoped ID (from_user_id). Cap stored turns to keep per-user prompts bounded.
  • Verify Meta signatures. Validate the X-Hub-Signature-256 header on every POST — Meta computes it as an HMAC-SHA256 of the raw request body with your app secret as the key; reject anything that doesn’t match.
  • Add a fallback. If DeepSeek returns a 5xx or an empty reply, send a polite “I’m having trouble — try again in a moment” instead of silence.
  • Respect opt-in. Store consent timestamp and source per user, and follow WhatsApp’s Business Messaging Policy.
  • Rate-limit per user. One inbound burst from a single user shouldn’t fan out to 200 DeepSeek calls.

Next steps

Two natural extensions. First, make the bot multi-modal: receive WhatsApp voice notes, transcribe them, then process the text through DeepSeek. Second, add tool calling so the bot can look up an order status against your real backend rather than guessing. The same FastAPI handler is the foundation for both. If you’d rather build on a chat-platform that’s friendlier for early prototyping, the DeepSeek Telegram bot tutorial covers a near-identical pattern with a much lighter onboarding flow, and the DeepSeek Discord bot guide shows how to run the same handler against Discord’s Gateway. For the broader catalogue of integrations, the DeepSeek tutorials hub indexes every step-by-step on the site.

One reference for primary sources before you ship: DeepSeek’s official Models & Pricing page and Change Log document the current model IDs, thinking-mode behaviour, prices and peak hours in DeepSeek’s own words; on Meta’s side, the WhatsApp pricing page sets out what Meta charges. Bookmark them.

How does a DeepSeek WhatsApp integration actually work?

Three components talk to each other: WhatsApp Cloud API on Meta’s side, a public HTTPS webhook on your server, and DeepSeek’s POST /chat/completions endpoint. Meta sends inbound messages to your webhook as JSON; your handler calls DeepSeek with the OpenAI SDK pointed at https://api.deepseek.com; you post the reply back through Graph API. See DeepSeek API documentation for the full request shape.

What does it cost to run a DeepSeek-powered WhatsApp bot?

DeepSeek inference is the cheap part. As of 12 November 2026, deepseek-flash costs $0.30 per million input tokens (cache miss) and $1.20 per million output at peak, half that off-peak. In the worked example above, a 6-turn support conversation costs about $0.0019 at peak and $0.00095 off-peak on the model side — well under one US cent. Meta’s WhatsApp charges are billed separately per message; check Meta’s pricing page for your market. Run the DeepSeek numbers with the DeepSeek pricing calculator.

Can DeepSeek remember the conversation across WhatsApp messages?

Not by itself. The DeepSeek API is stateless — every request must include the prior messages array. API integrations have to store history client-side, typically keyed by the user’s ID in Redis or a database. The DeepSeek API best practices guide covers patterns for trimming and caching that history.

Which DeepSeek model should I use for WhatsApp — deepseek-flash or deepseek-v4-pro?

Flash for almost every WhatsApp use case: customer support, FAQ deflection, intake bots, scheduling. Its current API name is deepseek-flash (served by DeepSeek-V4.1-Flash-1017; the older deepseek-v4-flash name is still accepted and served by the same model at the Flash price). Use DeepSeek V4-Pro only if your bot does serious agentic work (code generation, multi-step research) where Pro’s output price — 3.3 times Flash’s — pays for itself.

Do I need a Business Solution Provider like Twilio to use the WhatsApp API?

No. Meta’s Cloud API get-started guide walks a business through creating its own app, connecting a Messaging account and sending messages directly, without a partner. Meta still charges for messages as described on its pricing page; BSPs add managed dashboards and tooling on top, on their own terms. If you’re comfortable writing webhook handlers — and you have, given you’ve read this far — go direct. For the broader integration toolkit, see the DeepSeek tutorials catalogue.

Sources & Methodology

Last source check: November 12, 2026

Primary sources

  • OfficialDeepSeek API documentationEndpoints, request/response shape, model IDsLast checked: November 12, 2026
  • Official documentationDeepSeek Models & Pricing pagedeepseek-flash and deepseek-v4-pro prices (peak/off-peak), peak hours, 1M context, 384K max outputLast checked: November 12, 2026
  • Official documentationDeepSeek Change LogV4.1-Flash-1017 serving deepseek-flash; legacy deepseek-v4-flash routing; deepseek-chat/deepseek-reasoner retirement dateLast checked: November 12, 2026
  • Official documentationDeepSeek Thinking Mode guideThinking on by default; thinking toggle in extra_body; temperature ignored in thinking mode; reasoning_contentLast checked: November 12, 2026

Technical references

  • Official documentationMeta: WhatsApp Cloud API get startedApp use case, API Setup, temporary token, system-user permanent token (checked 12 Nov 2026)Last checked: November 12, 2026
  • Official documentationMeta: Create a webhook endpointhub.challenge verification, X-Hub-Signature-256 HMAC-SHA256 with app secret, retries (checked 12 Nov 2026)Last checked: November 12, 2026
  • Official documentationMeta: Text message webhook referenceInbound payload fields from, from_user_id (BSUID), text.body (checked 12 Nov 2026)Last checked: November 12, 2026
  • Official documentationMeta: Send text messagesSend payload (to/recipient), 4,096-character body limit, v27.0 example (checked 12 Nov 2026)Last checked: November 12, 2026

Context sources

  • Official documentationMeta: WhatsApp Business Platform pricingPer-message pricing since 1 Jul 2025; 1,000 free service messages per number per month from 1 Oct 2026; 24-hour customer service window (checked 12 Nov 2026)Last checked: November 12, 2026

Methodology

Information in this article was checked against the official DeepSeek documentation, the article's cited primary sources, and the deepseekai.guide pricing dataset on the date shown above. Where third-party numbers are quoted, the originating source is linked inline so the reader can verify and re-check.

Data confidence

High for facts cited inline with primary-source links; medium for context narrative.

Editorial note

AI tooling moves quickly. If you spot an outdated number or a broken link, the contact link in the footer is the fastest way to flag it for the editorial team.

Leave a Reply

Your email address will not be published. Required fields are marked *