# Migrate a contact table keyed on phone number to BSUIDs

> Move a WhatsApp contact table from phone keys to portfolio plus BSUID: schema, webhook backfill, upsert and merge rules, and a runnable sqlite3 demo.

Published 2026-11-04. Z-API Omni team.

Key each WhatsApp contact on the business portfolio plus the business-scoped user ID (BSUID). Keep the phone number and username as nullable attributes on the same row. A user who adopts a username can write to you with no phone number in the webhook. A table keyed on phone has no row to put them in. Meta's BSUID page says "Partners and businesses must adopt BSUID to continue processing incoming messages from WhatsApp username adopters" ([Meta business-scoped user IDs, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)). [WhatsApp usernames and BSUIDs](/academy/articles/whatsapp-usernames-business-scoped-user-ids/) covers the fields themselves.

## Why the key is portfolio plus BSUID

BSUIDs are "scoped to individual business portfolios", and a send from another portfolio's number "will fail". One person who talks to two of your portfolios has two BSUIDs, so the BSUID alone is not unique across your database. It also changes. A BSUID is "regenerated if a user changes their phone number".

The username is a display attribute. Users "can change it periodically", and a change "does not affect the user's phone number or business-scoped user ID". Overwrite it whenever a new one arrives and never join on it.

Store the BSUID exactly as received. It is an ISO 3166 alpha-2 country code, a period and "up to 128 alphanumeric characters", as in `US.13491208655302741918`. A parent BSUID adds `ENT.` after the country code. Meta says that omitting or changing any part "will cause your request to fail", so don't trim, upper-case or strip the prefix. In Postgres or MySQL, size the column for at least 135 characters.

The phone column stays, and becomes nullable. `wa_id` "will be set to the user's phone number if the user has not enabled the usernames feature". Meta's system webhook reference adds that "A WhatsApp user's ID and phone number may not match" ([Meta system webhook reference, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/system)). Store `wa_id` as Meta sends it, and normalize a copy when you join with other systems, as in [E.164 phone number normalization](/academy/articles/whatsapp-phone-number-format-e164-normalization/). Meta's samples carry no portfolio ID, only the account ID in `entry[].id`, so keep your own map from account to portfolio.

## Migrate the existing table

Run the steps in this order, so phone-keyed code keeps working until the send code switches.

1. If the phone number is the primary key, add a surrogate `id` and point messages, orders and tickets at it.
2. Add nullable `bsuid`, `parent_bsuid` and `username` columns and a unique index on portfolio plus `bsuid`. Make the phone column nullable, unique per portfolio.
3. Deploy a webhook handler that fills whichever identifier a row is missing, like the one below.
4. Switch your send code to choose the phone or the BSUID per contact.

The backfill is passive. Meta documents no API that maps a phone number to a BSUID or back. The contact book check, `GET /v26.0/<BUSINESS_PHONE_NUMBER_ID>/contact_book?messaging_product=whatsapp&bsuid=<BSUID>`, returns only a `present` boolean, and "no phone number is returned." BSUIDs began appearing in webhooks in April 2026. Status webhooks for messages you send to known phones carry `recipient_id` and `recipient_user_id` together, which pairs the two on your existing rows.

The send response returns `contacts[].input` and `contacts[].user_id`. Meta's sample shows it for a send to a BSUID. If your phone sends return a `user_id` too, normalize the input and upsert the pair. Rows you never hear from again stay without a BSUID.

## Upsert and merge rules

Look up by BSUID first, then by phone, both inside the portfolio. Meta withholds the phone from a username user "unless you have interacted with the user before", and the 30-day lookback is "evaluated per business phone number". A customer who last wrote months ago and has since set a username arrives as a BSUID with no phone, in a second row. When a later payload carries both identifiers, the lookups hit two rows, and those rows are one person.

Merge them into the row that holds the BSUID. Fill its empty columns from the other row and move opt-ins and other child rows across. Delete the other row before you write its phone onto the survivor, so the unique index doesn't trip.

Never clear a stored value because a payload left it out. A missing phone means Meta withheld it this time. Failed status webhooks omit `contacts` entirely, so read `statuses[].recipient_user_id` there.

Identity changes arrive on the `messages` field as `type` set to `system`, since "user_id_update is not a subscribable webhook field". A phone change sends `user_changed_number`, which carries the new `wa_id`, the new `user_id` and `previous_user_id`. A BSUID change with no phone to share sends `user_changed_user_id`, without `wa_id`. Find the row by `previous_user_id`, which is "Omitted when it is unavailable". When it is missing, find the row by the old phone in `from`. Write the new values and keep the retired BSUID in a history table.

## Send to the phone when you have it

Meta recommends phone sends: "Sending messages to phone numbers is recommended, primarily so you can continue to receive phone numbers in webhooks." For a contact with no phone, put the BSUID in `recipient` and leave `to` out. If both are present, "`to` (phone number) will take precedence."

BSUIDs work for "any type of message except for one-tap, zero-tap, and copy code authentication templates, which require user phone numbers". Those sends return error 131062. A BSUID-only contact who needs a one-time code has to share the number first. Ask for it with a `REQUEST_CONTACT_INFO` button in a utility or marketing template, or an interactive message. [Authentication templates with copy code](/academy/articles/whatsapp-authentication-templates-otp-copy-code/) covers the OTP side.

## Keep the phone on opt-in records

Meta's opt-in rule is written around the phone number. Businesses may message people who "have given their mobile phone number" and from whom the business has "received opt-in permission" ([Meta opt-in guide, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/getting-opt-in)). The page says nothing about BSUIDs or usernames. Keep the number the person gave on the opt-in record itself. When rows merge, point the record at the survivor and leave its phone alone.

After a number change, the record still shows the old number. Meta doesn't say whether consent carries over to the new one, so decide that with whoever owns consent in your company. [How to collect opt-in](/academy/articles/whatsapp-opt-in-how-to-collect-consent/) covers the record itself.

## The code

Python 3.9 or later, standard-library `sqlite3`. The four payloads are Meta's samples from the BSUID and system webhook pages, with whitespace compacted and content unchanged.

```python
"""contact_identity.py. Python 3.9 or later, standard library only.

One contact row per (portfolio, BSUID). The phone number (wa_id) and the
username are attributes. Run the file to replay Meta's sample webhooks.
"""
import json
import sqlite3
import time

# Webhooks carry the account ID in entry[].id, not the business portfolio.
PORTFOLIO_BY_ACCOUNT = {"102290129340398": "PORTFOLIO_ID"}
PHONE_ONLY_AUTH = {"one_tap", "zero_tap", "copy_code"}
FIELDS = "bsuid, parent_bsuid, wa_id, username, name"

SCHEMA = """
CREATE TABLE IF NOT EXISTS contacts (
  id           INTEGER PRIMARY KEY,
  portfolio_id TEXT NOT NULL,
  bsuid        TEXT,  -- user_id exactly as received, e.g. US.13491208655302741918
  parent_bsuid TEXT,  -- parent_user_id, only for enrolled portfolios
  wa_id        TEXT,  -- as Meta sends it; NULL while Meta withholds it
  username     TEXT,  -- the user can change it: an attribute, never a key
  name         TEXT,
  updated_at   INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS contacts_bsuid ON contacts (portfolio_id, bsuid);
CREATE UNIQUE INDEX IF NOT EXISTS contacts_wa_id ON contacts (portfolio_id, wa_id);
CREATE TABLE IF NOT EXISTS bsuid_history (
  portfolio_id TEXT NOT NULL,
  bsuid        TEXT NOT NULL,
  contact_id   INTEGER NOT NULL REFERENCES contacts (id),
  PRIMARY KEY (portfolio_id, bsuid)
);
CREATE TABLE IF NOT EXISTS opt_ins (
  id          INTEGER PRIMARY KEY,
  contact_id  INTEGER NOT NULL REFERENCES contacts (id),
  phone       TEXT NOT NULL,  -- the number the person gave when opting in
  source      TEXT NOT NULL,
  captured_at INTEGER NOT NULL
);
"""

def phone(value):
    """Never store a BSUID in the phone column: BSUIDs contain a period."""
    return value if value and "." not in value else None

def find(db, portfolio, column, value):
    if not value:
        return None
    if column == "old_bsuid":
        sql = "SELECT contact_id FROM bsuid_history WHERE portfolio_id = ? AND bsuid = ?"
    else:
        sql = f"SELECT id FROM contacts WHERE portfolio_id = ? AND {column} = ?"
    row = db.execute(sql, (portfolio, value)).fetchone()
    return row[0] if row else None

def remember_old(db, portfolio, bsuid, contact_id):
    db.execute(
        "INSERT OR REPLACE INTO bsuid_history (portfolio_id, bsuid, contact_id) VALUES (?, ?, ?)",
        (portfolio, bsuid, contact_id),
    )

def merge(db, portfolio, keep, drop):
    """Rows keep and drop are the same person: fold drop into keep."""
    k = db.execute(f"SELECT {FIELDS} FROM contacts WHERE id = ?", (keep,)).fetchone()
    d = db.execute(f"SELECT {FIELDS} FROM contacts WHERE id = ?", (drop,)).fetchone()
    db.execute("UPDATE opt_ins SET contact_id = ? WHERE contact_id = ?", (keep, drop))
    db.execute("UPDATE bsuid_history SET contact_id = ? WHERE contact_id = ?", (keep, drop))
    db.execute("DELETE FROM contacts WHERE id = ?", (drop,))  # frees its unique keys first
    merged = [a if a is not None else b for a, b in zip(k, d)]
    db.execute(
        "UPDATE contacts SET bsuid = ?, parent_bsuid = ?, wa_id = ?, username = ?, name = ? WHERE id = ?",
        (*merged, keep),
    )
    if k[0] and d[0] and k[0] != d[0]:
        remember_old(db, portfolio, d[0], keep)

def resolve(db, portfolio, *lookups):
    """Return the one row matching any (column, value) pair, merging duplicates."""
    found = []
    for column, value in lookups:
        cid = find(db, portfolio, column, value)
        if cid is not None and cid not in found:
            found.append(cid)
    for drop in found[1:]:
        merge(db, portfolio, found[0], drop)
    return found[0] if found else None

def upsert(db, portfolio, bsuid=None, wa_id=None, parent=None, username=None, name=None):
    """Insert or update a contact. A field the payload left out keeps its stored value."""
    wa_id = phone(wa_id)
    if not (bsuid or wa_id):
        return None
    retired = find(db, portfolio, "old_bsuid", bsuid)
    if retired is not None:
        return retired  # late or retried payload with a replaced BSUID: change nothing
    now = int(time.time())
    cid = resolve(db, portfolio, ("bsuid", bsuid), ("wa_id", wa_id))
    if cid is None:
        return db.execute(
            "INSERT INTO contacts (portfolio_id, bsuid, parent_bsuid, wa_id, username, name, updated_at)"
            " VALUES (?, ?, ?, ?, ?, ?, ?)",
            (portfolio, bsuid, parent, wa_id, username, name, now),
        ).lastrowid
    current = db.execute("SELECT bsuid FROM contacts WHERE id = ?", (cid,)).fetchone()[0]
    if current and bsuid and current != bsuid:
        remember_old(db, portfolio, current, cid)
    db.execute(
        "UPDATE contacts SET bsuid = COALESCE(?, bsuid), parent_bsuid = COALESCE(?, parent_bsuid),"
        " wa_id = COALESCE(?, wa_id), username = COALESCE(?, username), name = COALESCE(?, name),"
        " updated_at = ? WHERE id = ?",
        (bsuid, parent, wa_id, username, name, now, cid),
    )
    return cid

def change_identity(db, portfolio, system, old_wa_id=None):
    """Apply user_changed_number or user_changed_user_id to the existing row."""
    new, prev = system.get("user_id"), system.get("previous_user_id")
    new_wa_id, parent = phone(system.get("wa_id")), system.get("parent_user_id")
    cid = resolve(
        db, portfolio,
        ("bsuid", new), ("bsuid", prev), ("old_bsuid", prev),
        ("wa_id", phone(old_wa_id)), ("wa_id", new_wa_id),
    )
    if cid is None:
        cid = upsert(db, portfolio, bsuid=new, wa_id=new_wa_id, parent=parent)
    else:
        current = db.execute("SELECT bsuid FROM contacts WHERE id = ?", (cid,)).fetchone()[0]
        if current and new and current != new:
            remember_old(db, portfolio, current, cid)
        db.execute(
            "UPDATE contacts SET bsuid = COALESCE(?, bsuid), parent_bsuid = COALESCE(?, parent_bsuid),"
            " wa_id = COALESCE(?, wa_id), updated_at = ? WHERE id = ?",
            (new, parent, new_wa_id, int(time.time()), cid),
        )
    if cid is not None and prev and prev != new:
        remember_old(db, portfolio, prev, cid)
    return cid

def handle_webhook(db, payload):
    with db:  # one transaction per webhook
        for entry in payload.get("entry", []):
            portfolio = PORTFOLIO_BY_ACCOUNT[entry["id"]]
            for change in entry.get("changes", []):
                if change.get("field") != "messages":
                    continue
                value = change.get("value", {})
                for c in value.get("contacts", []):
                    profile = c.get("profile", {})
                    upsert(db, portfolio, bsuid=c.get("user_id"), wa_id=c.get("wa_id"),
                           parent=c.get("parent_user_id"),
                           username=profile.get("username"), name=profile.get("name"))
                for m in value.get("messages", []):
                    system = m.get("system", {})
                    if system.get("type") in ("user_changed_number", "user_changed_user_id"):
                        change_identity(db, portfolio, system, old_wa_id=m.get("from"))
                    else:
                        upsert(db, portfolio, bsuid=m.get("from_user_id"), wa_id=m.get("from"),
                               parent=m.get("from_parent_user_id"))
                for s in value.get("statuses", []):  # failed statuses carry no contacts block
                    upsert(db, portfolio, bsuid=s.get("recipient_user_id"),
                           wa_id=s.get("recipient_id"), parent=s.get("recipient_parent_user_id"))

def recipient_fields(db, contact_id, auth_button=None):
    """Phone when known (Meta's recommendation), BSUID otherwise."""
    wa_id, bsuid = db.execute("SELECT wa_id, bsuid FROM contacts WHERE id = ?", (contact_id,)).fetchone()
    if wa_id:
        return {"to": wa_id}
    if auth_button in PHONE_ONLY_AUTH:
        raise LookupError("one-tap, zero-tap and copy code templates need a phone number (131062)")
    if bsuid:
        return {"recipient": bsuid}
    raise LookupError("contact has no identifier")

# Meta's samples, whitespace compacted.
INBOUND_PHONE_WITHHELD = json.loads("""
{"object": "whatsapp_business_account", "entry": [{"id": "102290129340398", "changes": [{"value": {
 "messaging_product": "whatsapp",
 "metadata": {"display_phone_number": "15550783881", "phone_number_id": "106540352242922"},
 "contacts": [{"profile": {"name": "Sheena Nelson", "username": "realsheenanelson"},
  "user_id": "US.13491208655302741918", "parent_user_id": "US.ENT.11815799212886844830"}],
 "messages": [{"from_user_id": "US.13491208655302741918", "from_parent_user_id": "US.ENT.11815799212886844830",
  "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=", "timestamp": "1749416383",
  "type": "text", "text": {"body": "Does it come in another color?"}}]},
 "field": "messages"}]}]}
""")

STATUS_BOTH_IDS = json.loads("""
{"object": "whatsapp_business_account", "entry": [{"id": "102290129340398", "changes": [{"value": {
 "messaging_product": "whatsapp",
 "metadata": {"display_phone_number": "15550783881", "phone_number_id": "106540352242922"},
 "contacts": [{"profile": {"name": "Pablo M.", "username": "pablomorales"}, "wa_id": "16505551234",
  "user_id": "US.13491208655302741918", "parent_user_id": "US.ENT.11815799212886844830"}],
 "statuses": [{"id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQUFERjg0NDEzNDdFODU3MUMxMAA=",
  "status": "delivered", "timestamp": "1750030073", "recipient_id": "16505551234",
  "recipient_user_id": "US.13491208655302741918", "recipient_parent_user_id": "US.ENT.11815799212886844830",
  "pricing": {"billable": true, "pricing_model": "PMP", "type": "regular", "category": "marketing"}}]},
 "field": "messages"}]}]}
""")

USER_CHANGED_NUMBER = json.loads("""
{"object": "whatsapp_business_account", "entry": [{"id": "102290129340398", "changes": [{"value": {
 "messaging_product": "whatsapp",
 "metadata": {"display_phone_number": "15550783881", "phone_number_id": "106540352242922"},
 "messages": [{"from": "16505551234", "id": "wamid.HBgLMTk4MzU1NTE5NzQVAgASGAoxMTgyMDg2MjY3AA==",
  "timestamp": "1750269342",
  "system": {"body": "User Sheena Nelson changed from 16505551234 to 12195555358", "wa_id": "12195555358",
   "type": "user_changed_number", "user_id": "US.13491208655302741918",
   "parent_user_id": "US.ENT.506847293015824", "previous_user_id": "US.10230984751029384756",
   "previous_parent_user_id": "US.ENT.918273645500112"},
  "type": "system"}]},
 "field": "messages"}]}]}
""")

USER_CHANGED_USER_ID = json.loads("""
{"object": "whatsapp_business_account", "entry": [{"id": "102290129340398", "changes": [{"value": {
 "messaging_product": "whatsapp",
 "metadata": {"display_phone_number": "15550783881", "phone_number_id": "106540352242922"},
 "messages": [{"id": "wamid.HBgLMTk4MzU1NTE5NzQVAgASGAoxMTgyMDg2MjY3AA==", "timestamp": "1750269342",
  "system": {"body": "User changed from US.10230984751029384756 to US.13491208655302741918",
   "type": "user_changed_user_id", "user_id": "US.13491208655302741918",
   "parent_user_id": "US.ENT.506847293015824", "previous_user_id": "US.10230984751029384756",
   "previous_parent_user_id": "US.ENT.918273645500112"},
  "type": "system"}]},
 "field": "messages"}]}]}
""")

def new_db():
    db = sqlite3.connect(":memory:")
    db.executescript(SCHEMA)
    return db

def seed_legacy(db, wa_id, bsuid=None):
    """A row from before the migration, with the opt-in it was created with."""
    with db:
        cid = db.execute(
            "INSERT INTO contacts (portfolio_id, bsuid, wa_id, name, updated_at) VALUES (?, ?, ?, ?, 0)",
            ("PORTFOLIO_ID", bsuid, wa_id, "Legacy row"),
        ).lastrowid
        db.execute(
            "INSERT INTO opt_ins (contact_id, phone, source, captured_at) VALUES (?, ?, 'checkout form', 0)",
            (cid, wa_id),
        )

def show(db, label):
    print(label)
    for row in db.execute(f"SELECT id, {FIELDS} FROM contacts ORDER BY id"):
        print("  contact", row)
    for row in db.execute("SELECT contact_id, phone FROM opt_ins"):
        print("  opt-in ", row)
    for row in db.execute("SELECT bsuid, contact_id FROM bsuid_history"):
        print("  retired", row)

if __name__ == "__main__":
    # Meta's samples reuse the same IDs across pages, so each scenario starts empty.
    db = new_db()
    seed_legacy(db, "16505551234")
    handle_webhook(db, INBOUND_PHONE_WITHHELD)
    show(db, "1. Phone withheld: a second row appears, keyed on the BSUID")
    bsuid_row = find(db, "PORTFOLIO_ID", "bsuid", "US.13491208655302741918")
    print("  send fields:", recipient_fields(db, bsuid_row))
    try:
        recipient_fields(db, bsuid_row, auth_button="copy_code")
    except LookupError as err:
        print("  copy code template:", err)
    handle_webhook(db, STATUS_BOTH_IDS)
    show(db, "2. Status with both IDs: the two rows merge")
    print("  send fields:", recipient_fields(db, bsuid_row))

    db = new_db()
    seed_legacy(db, "16505551234", bsuid="US.10230984751029384756")
    handle_webhook(db, USER_CHANGED_NUMBER)
    handle_webhook(db, USER_CHANGED_USER_ID)  # already applied: changes nothing
    show(db, "3. Number change: new BSUID and phone, old BSUID retired")
```

First scenario: Meta's withheld-phone sample adds a BSUID-only row beside the legacy phone row, and a copy code send raises before it can hit 131062. The status sample carries both IDs, so the rows merge, the opt-in moves across and sends switch to `to`. Second scenario: the old BSUID is retired, and the replayed `user_changed_user_id` changes nothing.

Meta's samples reuse one BSUID under two names, so the demo overwrites the username and name each time.

If your CRM spans several portfolios, the same person has one row per portfolio, each with its own BSUID. Meta's checklist suggests "central CRM access across multiple portfolios". The phone joins those rows when you have it. Meta's page doesn't say what the parent BSUID links, so ask your Meta point of contact before joining on it. The [conversation storage schema](/academy/articles/whatsapp-conversation-storage-database-schema/) shows where messages attach to these rows, and [the idempotency pattern](/academy/articles/n8n-duplicate-webhooks-idempotency/) covers duplicate deliveries of the same event.

*Z-API Omni team*
