[{"data":1,"prerenderedAt":2051},["ShallowReactive",2],{"\u002Farticles\u002Fmessenger-one-click-auth":3},{"id":4,"title":5,"body":6,"date":2035,"description":2036,"extension":2037,"head":2038,"image":2039,"meta":2040,"navigation":2041,"ogImage":2038,"path":2042,"rating":188,"readingTime":2043,"robots":2038,"schemaOrg":2038,"seo":2044,"sitemap":2045,"stem":2046,"tags":2047,"__hash__":2050},"articles_en\u002Farticles\u002Fmessenger-one-click-auth.md","One Click to Connect Messenger: 6 Engineering Decisions Behind Facebook One-Click Authorization",{"type":7,"value":8,"toc":2018},"minimark",[9,13,16,33,38,49,138,144,148,151,406,409,592,596,617,626,632,635,816,834,838,841,906,911,917,1001,1004,1075,1079,1090,1132,1135,1220,1230,1234,1252,1255,1355,1391,1395,1400,1407,1456,1463,1467,1477,1481,1547,1551,1568,1608,1619,1698,1720,1760,1764,1767,1904,1915,1919,1960,1964,2014],[10,11,12],"p",{},"Before this change, a merchant who wanted to connect their Facebook Page to our Messenger AI assistant had to wait for someone on the ops side to fetch the credentials and configure them by hand, once per merchant. I wanted to turn that into a single button the merchant clicks in the admin console.",[10,14,15],{},"The button is the easy part. The hard part is the trade-offs in the chain behind it. This post walks through the 6 decisions I had to make.",[17,18,19,30],"tip",{},[10,20,21,25,26,29],{},[22,23,24],"strong",{},"In one sentence",": a merchant clicks \"Connect Facebook\" once in the admin console and their Facebook Page is connected to the Messenger AI assistant, replacing the old process where ops wrote Page credentials in by hand. The frontend only produces a ",[27,28,27],"code",{},"; exchanging the token, validating permissions, fetching Pages, subscribing to the webhook and storing the encrypted credential all happen on the server in one pass. This post breaks down the 6 places in that chain where a real trade-off was needed. The last one is the single-callback webhook problem caused by test and production sharing one Meta App.",[10,31,32],{},"Product names, configuration IDs, API paths and config keys have been generalized. The code shown is an excerpt of the core logic.",[34,35,37],"h2",{"id":36},"_1-background-from-ops-edits-the-database-to-the-merchant-clicks-once","1. Background: from \"ops edits the database\" to \"the merchant clicks once\"",[10,39,40,41,44,45,48],{},"The platform is a multi-channel conversational AI assistant (Python FastAPI). The Messenger channel had been running in production for a while: after verifying the webhook signature, it looks up the merchant table by the ",[27,42,43],{},"entry.id"," in the envelope (the Page ID) to get credentials, then drives the AI reply. Tenant credentials are cached for 24 hours. The problem was ",[22,46,47],{},"how merchants got connected",": the Page ID, Page token and authorizer columns in the merchant table were all written by ops, by hand.",[50,51,52,68],"table",{},[53,54,55],"thead",{},[56,57,58,62,65],"tr",{},[59,60,61],"th",{},"Gap",[59,63,64],{},"Impact",[59,66,67],{},"What this work does",[69,70,71,83,94,105,116,127],"tbody",{},[56,72,73,77,80],{},[74,75,76],"td",{},"No self-service authorization for merchants",[74,78,79],{},"Ops has to fetch and configure a Page token by hand for every merchant",[74,81,82],{},"One-click authorization in the admin console, with automatic subscription and persistence on the server",[56,84,85,88,91],{},[74,86,87],{},"Credential storage needs to follow one security baseline",[74,89,90],{},"All channel credentials should share the same key management",[74,92,93],{},"Encrypted storage, ciphertext with a version prefix, older format still readable",[56,95,96,99,102],{},[74,97,98],{},"No Page name, no connection time",[74,100,101],{},"The admin console cannot show what is connected",[74,103,104],{},"Two new columns, returned by the status endpoint",[56,106,107,110,113],{},[74,108,109],{},"No way to unbind",[74,111,112],{},"Changing or disabling a Page needs ops",[74,114,115],{},"An unbind endpoint: best-effort unsubscribe, clear the columns, clear the cache",[56,117,118,121,124],{},[74,119,120],{},"Messenger and WhatsApp lived in two Meta Apps",[74,122,123],{},"Two SDK initializations conflict on the same page",[74,125,126],{},"Consolidate into one App; the frontend reuses one SDK instance",[56,128,129,132,135],{},[74,130,131],{},"The Page webhook is a single app-level callback URL",[74,133,134],{},"When test and production share an App, only one environment receives messages",[74,136,137],{},"Forward the whole webhook payload across environments",[10,139,140,141,143],{},"The constraints were clear too. Multi-tenant routing stays the same and still looks up by ",[27,142,43],{},", so the existing Messenger consumer path can use the new credentials with zero changes. The Java business backend also needs zero changes, because channel credentials have nothing to do with login identity and the agent service already reads and writes the merchant table directly.",[34,145,147],{"id":146},"_2-the-big-picture-the-chain-in-one-diagram","2. The big picture: the chain in one diagram",[10,149,150],{},"Blue is new in this work, yellow is modified, everything else already existed.",[152,153,158],"pre",{"className":154,"code":155,"language":156,"meta":157,"style":157},"language-mermaid shiki shiki-themes github-light github-dark github-dark","flowchart LR\n  subgraph Admin[\"Merchant admin console · Vue 3\"]\n    FC[\"Facebook channel card\u003Cbr>Disconnected · Page select · Connected\"]\n    HL[\"Login hook\u003Cbr>Meta JS SDK · FB.login\"]\n    HB[\"Binding hook\u003Cbr>status · connect · select · unbind\"]\n  end\n  subgraph Meta[\"Meta platform · one App\"]\n    SDK[\"Authorization dialog\u003Cbr>Facebook Login for Business · config_id\"]\n    GRAPH[\"Graph API\u003Cbr>oauth\u002Faccess_token · debug_token\u003Cbr>\u002FPAGE_ID · subscribed_apps\"]\n    WH[\"Page Webhook\u003Cbr>messages · messaging_postbacks\"]\n  end\n  subgraph Core[\"Agent service · Python FastAPI\"]\n    PA[\"Channel auth endpoints\u003Cbr>Session auth · IP rate limit · error mapping\"]\n    PS[\"Auth orchestration service\u003Cbr>Exchange · validate · fetch Pages · subscribe · persist\"]\n    MC[\"Webhook controller\u003Cbr>HMAC verify · ACK first · cross-env forward\"]\n    FM[\"Messenger message service\u003Cbr>Tenant lookup by page_id · AI reply\"]\n  end\n  DB[(\"MySQL merchant table\u003Cbr>five messenger columns\")]\n  RD[(\"Redis\u003Cbr>Selection stash · tenant cache · merchant lock\")]\n  PEER[\"Peer environment\u003Cbr>Webhook controller\"]\n  FC --> HL\n  HL \u003C--> SDK\n  HL -->|code| HB\n  HB -->|session token and code| PA\n  PA --> PS\n  PS \u003C--> GRAPH\n  PS --> DB\n  PS --> RD\n  WH --> MC\n  MC --> FM\n  FM --> DB\n  FM --> RD\n  MC -.->|forward whole payload for unknown Pages| PEER\n  style FC fill:#dbeafe,stroke:#155dfc\n  style HL fill:#dbeafe,stroke:#155dfc\n  style HB fill:#dbeafe,stroke:#155dfc\n  style PA fill:#dbeafe,stroke:#155dfc\n  style PS fill:#dbeafe,stroke:#155dfc\n  style MC fill:#fef3c7,stroke:#d97706\n  style FM fill:#fef3c7,stroke:#d97706\n  style DB fill:#fef3c7,stroke:#d97706\n","mermaid","",[27,159,160,168,174,180,186,192,198,204,210,216,222,227,233,239,245,251,257,262,268,274,280,286,292,298,304,310,316,322,328,334,340,346,352,358,364,370,376,382,388,394,400],{"__ignoreMap":157},[161,162,165],"span",{"class":163,"line":164},"line",1,[161,166,167],{},"flowchart LR\n",[161,169,171],{"class":163,"line":170},2,[161,172,173],{},"  subgraph Admin[\"Merchant admin console · Vue 3\"]\n",[161,175,177],{"class":163,"line":176},3,[161,178,179],{},"    FC[\"Facebook channel card\u003Cbr>Disconnected · Page select · Connected\"]\n",[161,181,183],{"class":163,"line":182},4,[161,184,185],{},"    HL[\"Login hook\u003Cbr>Meta JS SDK · FB.login\"]\n",[161,187,189],{"class":163,"line":188},5,[161,190,191],{},"    HB[\"Binding hook\u003Cbr>status · connect · select · unbind\"]\n",[161,193,195],{"class":163,"line":194},6,[161,196,197],{},"  end\n",[161,199,201],{"class":163,"line":200},7,[161,202,203],{},"  subgraph Meta[\"Meta platform · one App\"]\n",[161,205,207],{"class":163,"line":206},8,[161,208,209],{},"    SDK[\"Authorization dialog\u003Cbr>Facebook Login for Business · config_id\"]\n",[161,211,213],{"class":163,"line":212},9,[161,214,215],{},"    GRAPH[\"Graph API\u003Cbr>oauth\u002Faccess_token · debug_token\u003Cbr>\u002FPAGE_ID · subscribed_apps\"]\n",[161,217,219],{"class":163,"line":218},10,[161,220,221],{},"    WH[\"Page Webhook\u003Cbr>messages · messaging_postbacks\"]\n",[161,223,225],{"class":163,"line":224},11,[161,226,197],{},[161,228,230],{"class":163,"line":229},12,[161,231,232],{},"  subgraph Core[\"Agent service · Python FastAPI\"]\n",[161,234,236],{"class":163,"line":235},13,[161,237,238],{},"    PA[\"Channel auth endpoints\u003Cbr>Session auth · IP rate limit · error mapping\"]\n",[161,240,242],{"class":163,"line":241},14,[161,243,244],{},"    PS[\"Auth orchestration service\u003Cbr>Exchange · validate · fetch Pages · subscribe · persist\"]\n",[161,246,248],{"class":163,"line":247},15,[161,249,250],{},"    MC[\"Webhook controller\u003Cbr>HMAC verify · ACK first · cross-env forward\"]\n",[161,252,254],{"class":163,"line":253},16,[161,255,256],{},"    FM[\"Messenger message service\u003Cbr>Tenant lookup by page_id · AI reply\"]\n",[161,258,260],{"class":163,"line":259},17,[161,261,197],{},[161,263,265],{"class":163,"line":264},18,[161,266,267],{},"  DB[(\"MySQL merchant table\u003Cbr>five messenger columns\")]\n",[161,269,271],{"class":163,"line":270},19,[161,272,273],{},"  RD[(\"Redis\u003Cbr>Selection stash · tenant cache · merchant lock\")]\n",[161,275,277],{"class":163,"line":276},20,[161,278,279],{},"  PEER[\"Peer environment\u003Cbr>Webhook controller\"]\n",[161,281,283],{"class":163,"line":282},21,[161,284,285],{},"  FC --> HL\n",[161,287,289],{"class":163,"line":288},22,[161,290,291],{},"  HL \u003C--> SDK\n",[161,293,295],{"class":163,"line":294},23,[161,296,297],{},"  HL -->|code| HB\n",[161,299,301],{"class":163,"line":300},24,[161,302,303],{},"  HB -->|session token and code| PA\n",[161,305,307],{"class":163,"line":306},25,[161,308,309],{},"  PA --> PS\n",[161,311,313],{"class":163,"line":312},26,[161,314,315],{},"  PS \u003C--> GRAPH\n",[161,317,319],{"class":163,"line":318},27,[161,320,321],{},"  PS --> DB\n",[161,323,325],{"class":163,"line":324},28,[161,326,327],{},"  PS --> RD\n",[161,329,331],{"class":163,"line":330},29,[161,332,333],{},"  WH --> MC\n",[161,335,337],{"class":163,"line":336},30,[161,338,339],{},"  MC --> FM\n",[161,341,343],{"class":163,"line":342},31,[161,344,345],{},"  FM --> DB\n",[161,347,349],{"class":163,"line":348},32,[161,350,351],{},"  FM --> RD\n",[161,353,355],{"class":163,"line":354},33,[161,356,357],{},"  MC -.->|forward whole payload for unknown Pages| PEER\n",[161,359,361],{"class":163,"line":360},34,[161,362,363],{},"  style FC fill:#dbeafe,stroke:#155dfc\n",[161,365,367],{"class":163,"line":366},35,[161,368,369],{},"  style HL fill:#dbeafe,stroke:#155dfc\n",[161,371,373],{"class":163,"line":372},36,[161,374,375],{},"  style HB fill:#dbeafe,stroke:#155dfc\n",[161,377,379],{"class":163,"line":378},37,[161,380,381],{},"  style PA fill:#dbeafe,stroke:#155dfc\n",[161,383,385],{"class":163,"line":384},38,[161,386,387],{},"  style PS fill:#dbeafe,stroke:#155dfc\n",[161,389,391],{"class":163,"line":390},39,[161,392,393],{},"  style MC fill:#fef3c7,stroke:#d97706\n",[161,395,397],{"class":163,"line":396},40,[161,398,399],{},"  style FM fill:#fef3c7,stroke:#d97706\n",[161,401,403],{"class":163,"line":402},41,[161,404,405],{},"  style DB fill:#fef3c7,stroke:#d97706\n",[10,407,408],{},"The main authorization sequence (the exactly-one-Page branch and the multi-Page branch):",[152,410,412],{"className":154,"code":411,"language":156,"meta":157,"style":157},"sequenceDiagram\n  autonumber\n  participant M as Merchant\n  participant A as Admin console\n  participant F as Meta auth dialog\n  participant C as Auth orchestration service\n  participant G as Meta Graph API\n  participant D as MySQL merchant table\n  participant R as Redis\n  M->>A: Click Connect Facebook\n  A->>F: FB.login with config_id, response_type code\n  F-->>M: Pick business portfolio and Pages, then authorize\n  F-->>A: authResponse.code\n  A->>C: POST connect with code\n  C->>G: oauth\u002Faccess_token to exchange the token\n  C->>G: debug_token to check app_id and scopes\n  Note over C: Skip long-lived exchange if expires_at is 0 or at least 1 day remains\n  C->>G: Fetch Page name and Page token one by one from granular_scopes\n  alt Exactly 1 Page\n    C->>G: POST subscribed_apps for messages and messaging_postbacks\n    C->>D: Single UPDATE writes five columns, token stored encrypted\n    C->>R: Clear tenant cache for old and new Page\n    C-->>A: connected\n  else Multiple Pages\n    C->>R: Stash encrypted Page list with a short TTL\n    C-->>A: page_select_required with pages and selection_token\n    M->>A: Pick a Page in the card\n    A->>C: POST select\n    C->>G: POST subscribed_apps\n    C->>D: Persist and clear cache\n    C-->>A: connected\n  else 0 Pages\n    C-->>A: 403 no_page\n  end\n  A->>C: GET status\n  C-->>A: connected with page_id and page_name\n",[27,413,414,419,424,429,434,439,444,449,454,459,464,469,474,479,484,489,494,499,504,509,514,519,524,529,534,539,544,549,554,559,564,568,573,578,582,587],{"__ignoreMap":157},[161,415,416],{"class":163,"line":164},[161,417,418],{},"sequenceDiagram\n",[161,420,421],{"class":163,"line":170},[161,422,423],{},"  autonumber\n",[161,425,426],{"class":163,"line":176},[161,427,428],{},"  participant M as Merchant\n",[161,430,431],{"class":163,"line":182},[161,432,433],{},"  participant A as Admin console\n",[161,435,436],{"class":163,"line":188},[161,437,438],{},"  participant F as Meta auth dialog\n",[161,440,441],{"class":163,"line":194},[161,442,443],{},"  participant C as Auth orchestration service\n",[161,445,446],{"class":163,"line":200},[161,447,448],{},"  participant G as Meta Graph API\n",[161,450,451],{"class":163,"line":206},[161,452,453],{},"  participant D as MySQL merchant table\n",[161,455,456],{"class":163,"line":212},[161,457,458],{},"  participant R as Redis\n",[161,460,461],{"class":163,"line":218},[161,462,463],{},"  M->>A: Click Connect Facebook\n",[161,465,466],{"class":163,"line":224},[161,467,468],{},"  A->>F: FB.login with config_id, response_type code\n",[161,470,471],{"class":163,"line":229},[161,472,473],{},"  F-->>M: Pick business portfolio and Pages, then authorize\n",[161,475,476],{"class":163,"line":235},[161,477,478],{},"  F-->>A: authResponse.code\n",[161,480,481],{"class":163,"line":241},[161,482,483],{},"  A->>C: POST connect with code\n",[161,485,486],{"class":163,"line":247},[161,487,488],{},"  C->>G: oauth\u002Faccess_token to exchange the token\n",[161,490,491],{"class":163,"line":253},[161,492,493],{},"  C->>G: debug_token to check app_id and scopes\n",[161,495,496],{"class":163,"line":259},[161,497,498],{},"  Note over C: Skip long-lived exchange if expires_at is 0 or at least 1 day remains\n",[161,500,501],{"class":163,"line":264},[161,502,503],{},"  C->>G: Fetch Page name and Page token one by one from granular_scopes\n",[161,505,506],{"class":163,"line":270},[161,507,508],{},"  alt Exactly 1 Page\n",[161,510,511],{"class":163,"line":276},[161,512,513],{},"    C->>G: POST subscribed_apps for messages and messaging_postbacks\n",[161,515,516],{"class":163,"line":282},[161,517,518],{},"    C->>D: Single UPDATE writes five columns, token stored encrypted\n",[161,520,521],{"class":163,"line":288},[161,522,523],{},"    C->>R: Clear tenant cache for old and new Page\n",[161,525,526],{"class":163,"line":294},[161,527,528],{},"    C-->>A: connected\n",[161,530,531],{"class":163,"line":300},[161,532,533],{},"  else Multiple Pages\n",[161,535,536],{"class":163,"line":306},[161,537,538],{},"    C->>R: Stash encrypted Page list with a short TTL\n",[161,540,541],{"class":163,"line":312},[161,542,543],{},"    C-->>A: page_select_required with pages and selection_token\n",[161,545,546],{"class":163,"line":318},[161,547,548],{},"    M->>A: Pick a Page in the card\n",[161,550,551],{"class":163,"line":324},[161,552,553],{},"    A->>C: POST select\n",[161,555,556],{"class":163,"line":330},[161,557,558],{},"    C->>G: POST subscribed_apps\n",[161,560,561],{"class":163,"line":336},[161,562,563],{},"    C->>D: Persist and clear cache\n",[161,565,566],{"class":163,"line":342},[161,567,528],{},[161,569,570],{"class":163,"line":348},[161,571,572],{},"  else 0 Pages\n",[161,574,575],{"class":163,"line":354},[161,576,577],{},"    C-->>A: 403 no_page\n",[161,579,580],{"class":163,"line":360},[161,581,197],{},[161,583,584],{"class":163,"line":366},[161,585,586],{},"  A->>C: GET status\n",[161,588,589],{"class":163,"line":372},[161,590,591],{},"  C-->>A: connected with page_id and page_name\n",[34,593,595],{"id":594},"_3-decision-1-the-authorization-entry-point-where-the-frontend-only-produces-a-code","3. Decision 1: the authorization entry point, where the frontend only produces a code",[10,597,598,601,602,605,606,609,610,613,614,616],{},[22,599,600],{},"Chosen",": reuse ",[27,603,604],{},"FB.login"," from the Meta JS SDK with a Facebook Login for Business configuration (",[27,607,608],{},"config_id","), with ",[27,611,612],{},"response_type"," set to ",[27,615,27],{},".",[10,618,619,622,623,625],{},[22,620,621],{},"Why",": once Messenger and WhatsApp Embedded Signup share one Meta App, the page needs only one SDK instance. The ",[27,624,27],{}," comes straight back in the callback, so there is no callback page, no redirect URI allowlist, no state check and no popup lifecycle to manage.",[10,627,628,631],{},[22,629,630],{},"Rejected",": building our own OAuth redirect and callback page.",[10,633,634],{},"The frontend hook is deliberately small. Its only job is to get hold of the code:",[152,636,640],{"className":637,"code":638,"language":639,"meta":157,"style":157},"language-ts shiki shiki-themes github-light github-dark github-dark","window.FB.login(\n  response => {\n    if (disposed || settledRound) return;   \u002F\u002F once guard: consume the callback once per round, never after unmount\n    settledRound = true;\n    const code = response.authResponse?.code;\n    if (!code) { options.onCancel?.(); return; }   \u002F\u002F dialog closed or authorization denied: empty authResponse means cancel\n    options.onCode(code).catch(() => options.onError?.(\"submit_failed\"));\n  },\n  { config_id: configId, response_type: \"code\", override_default_response_type: true }\n);\n","ts",[27,641,642,661,674,698,712,726,753,789,794,811],{"__ignoreMap":157},[161,643,644,648,652,654,658],{"class":163,"line":164},[161,645,647],{"class":646},"slsVL","window.",[161,649,651],{"class":650},"suiK_","FB",[161,653,616],{"class":646},[161,655,657],{"class":656},"shcOC","login",[161,659,660],{"class":646},"(\n",[161,662,663,667,671],{"class":163,"line":170},[161,664,666],{"class":665},"sQHwn","  response",[161,668,670],{"class":669},"so5gQ"," =>",[161,672,673],{"class":646}," {\n",[161,675,676,679,682,685,688,691,694],{"class":163,"line":176},[161,677,678],{"class":669},"    if",[161,680,681],{"class":646}," (disposed ",[161,683,684],{"class":669},"||",[161,686,687],{"class":646}," settledRound) ",[161,689,690],{"class":669},"return",[161,692,693],{"class":646},";   ",[161,695,697],{"class":696},"sCsY4","\u002F\u002F once guard: consume the callback once per round, never after unmount\n",[161,699,700,703,706,709],{"class":163,"line":182},[161,701,702],{"class":646},"    settledRound ",[161,704,705],{"class":669},"=",[161,707,708],{"class":650}," true",[161,710,711],{"class":646},";\n",[161,713,714,717,720,723],{"class":163,"line":188},[161,715,716],{"class":669},"    const",[161,718,719],{"class":650}," code",[161,721,722],{"class":669}," =",[161,724,725],{"class":646}," response.authResponse?.code;\n",[161,727,728,730,733,736,739,742,745,747,750],{"class":163,"line":194},[161,729,678],{"class":669},[161,731,732],{"class":646}," (",[161,734,735],{"class":669},"!",[161,737,738],{"class":646},"code) { options.",[161,740,741],{"class":656},"onCancel",[161,743,744],{"class":646},"?.(); ",[161,746,690],{"class":669},[161,748,749],{"class":646},"; }   ",[161,751,752],{"class":696},"\u002F\u002F dialog closed or authorization denied: empty authResponse means cancel\n",[161,754,755,758,761,764,767,770,773,776,779,782,786],{"class":163,"line":200},[161,756,757],{"class":646},"    options.",[161,759,760],{"class":656},"onCode",[161,762,763],{"class":646},"(code).",[161,765,766],{"class":656},"catch",[161,768,769],{"class":646},"(() ",[161,771,772],{"class":669},"=>",[161,774,775],{"class":646}," options.",[161,777,778],{"class":656},"onError",[161,780,781],{"class":646},"?.(",[161,783,785],{"class":784},"sfrk1","\"submit_failed\"",[161,787,788],{"class":646},"));\n",[161,790,791],{"class":163,"line":206},[161,792,793],{"class":646},"  },\n",[161,795,796,799,802,805,808],{"class":163,"line":212},[161,797,798],{"class":646},"  { config_id: configId, response_type: ",[161,800,801],{"class":784},"\"code\"",[161,803,804],{"class":646},", override_default_response_type: ",[161,806,807],{"class":650},"true",[161,809,810],{"class":646}," }\n",[161,812,813],{"class":163,"line":218},[161,814,815],{"class":646},");\n",[10,817,818,819,822,823,826,827,829,830,833],{},"A few edges that are easy to miss. If the SDK has already been loaded by the WhatsApp card, the hook reuses ",[27,820,821],{},"window.FB"," and does not set ",[27,824,825],{},"fbAsyncInit",", so it cannot overwrite an initialization callback that the other side still has in flight. SDK loading has a timeout. If ",[27,828,608],{}," is not configured, the hook says \"not configured in this environment\" and never loads the SDK. When the server exchanges the code for a token it sends no ",[27,831,832],{},"redirect_uri",", the same as Embedded Signup.",[34,835,837],{"id":836},"_4-decision-2-token-type-pick-the-system-user-token-but-keep-the-code-indifferent-to-token-type","4. Decision 2: token type. Pick the system user token, but keep the code indifferent to token type",[10,839,840],{},"The Facebook Login for Business configuration decides which kind of token you get after authorization, and the two differ quite a bit:",[50,842,843,856],{},[53,844,845],{},[56,846,847,850,853],{},[59,848,849],{},"Dimension",[59,851,852],{},"User access token",[59,854,855],{},"System user access token",[69,857,858,869,884,895],{},[56,859,860,863,866],{},[74,861,862],{},"Owner",[74,864,865],{},"The personal account of the employee who authorized",[74,867,868],{},"The merchant's business; Meta creates a system user under it automatically",[56,870,871,874,877],{},[74,872,873],{},"Lifetime",[74,875,876],{},"About 1 hour at first, must be exchanged for a 60-day long-lived token",[74,878,879,880,883],{},"Can be set to never expire, ",[27,881,882],{},"expires_at"," is 0",[56,885,886,889,892],{},[74,887,888],{},"What invalidates it",[74,890,891],{},"Password change, the employee leaving, account security checks",[74,893,894],{},"Business-level events, unlikely",[56,896,897,900,903],{},[74,898,899],{},"Prerequisite",[74,901,902],{},"Low",[74,904,905],{},"The merchant needs a business portfolio with the Page added to it",[10,907,908,910],{},[22,909,600],{},": a system user token that never expires. The connection belongs to the merchant's business, not to one employee's account. WhatsApp onboarding already requires a business portfolio, so this adds no new prerequisite.",[10,912,913,916],{},[22,914,915],{},"The orchestration still works with both token types",", so switching the configuration in the Meta dashboard later needs no code change. The only difference is whether to do the long-lived exchange. Everything else is shared:",[918,919,920,960,969,993],"ol",{},[921,922,923,926,927,930,931,934,935,938,939,942,943,946,947,950,951,942,953,946,956,959],"li",{},[27,924,925],{},"debug_token"," validation: ",[27,928,929],{},"is_valid"," is true, ",[27,932,933],{},"app_id"," matches our App, and ",[27,936,937],{},"scopes"," includes ",[27,940,941],{},"pages_show_list",", ",[27,944,945],{},"pages_messaging"," and ",[27,948,949],{},"pages_manage_metadata",". Any one missing means rejection. The same call also returns the ",[27,952,882],{},[27,954,955],{},"user_id",[27,957,958],{},"granular_scopes"," needed later, so one call serves three purposes.",[921,961,962,963,965,966,968],{},"The long-lived decision looks only at ",[27,964,882],{}," from ",[27,967,925],{},". It is a pure function, which makes it easy to unit test (code below).",[921,970,971,972,975,976,978,979,981,982,984,985,988,989,992],{},"The Page list comes first from the ",[27,973,974],{},"target_ids"," that ",[27,977,945],{}," was explicitly granted in ",[27,980,958],{},". Each Page is fetched with its own GET to get the name and Page token, and one failure is skipped instead of rejecting the whole round. Only when ",[27,983,974],{}," is empty (a user token where \"all Pages\" was ticked) does it fall back to ",[27,986,987],{},"\u002Fme\u002Faccounts",", with a cap on pagination. Pages whose ",[27,990,991],{},"tasks"," exists but contains none of MANAGE, MODERATE or MESSAGING are dropped, because binding them would not let us send messages anyway.",[921,994,995,996,965,998,1000],{},"The authorizer identifier is the ",[27,997,955],{},[27,999,925],{},". With a system user token that is the id of the system user Meta generated.",[10,1002,1003],{},"The long-lived decision function from step 2:",[152,1005,1009],{"className":1006,"code":1007,"language":1008,"meta":157,"style":157},"language-py shiki shiki-themes github-light github-dark github-dark","def _needs_long_lived_exchange(expires_at) -> bool:\n    \"\"\"0 = never expires (long-term system user token), no exchange; at least 1 day remaining, no exchange;\n    anything else (short-lived user token) must be exchanged, or the derived Page token is short-lived too;\n    a missing or invalid field is treated as short-lived (better one exchange too many)\"\"\"\n    if expires_at is None:\n        return True\n    try:\n        exp = int(expires_at)\n    except (TypeError, ValueError):\n        return True\n    if exp == 0:\n        return False\n    return exp - time.time() \u003C 24 * 3600\n","py",[27,1010,1011,1016,1021,1026,1031,1036,1041,1046,1051,1056,1060,1065,1070],{"__ignoreMap":157},[161,1012,1013],{"class":163,"line":164},[161,1014,1015],{},"def _needs_long_lived_exchange(expires_at) -> bool:\n",[161,1017,1018],{"class":163,"line":170},[161,1019,1020],{},"    \"\"\"0 = never expires (long-term system user token), no exchange; at least 1 day remaining, no exchange;\n",[161,1022,1023],{"class":163,"line":176},[161,1024,1025],{},"    anything else (short-lived user token) must be exchanged, or the derived Page token is short-lived too;\n",[161,1027,1028],{"class":163,"line":182},[161,1029,1030],{},"    a missing or invalid field is treated as short-lived (better one exchange too many)\"\"\"\n",[161,1032,1033],{"class":163,"line":188},[161,1034,1035],{},"    if expires_at is None:\n",[161,1037,1038],{"class":163,"line":194},[161,1039,1040],{},"        return True\n",[161,1042,1043],{"class":163,"line":200},[161,1044,1045],{},"    try:\n",[161,1047,1048],{"class":163,"line":206},[161,1049,1050],{},"        exp = int(expires_at)\n",[161,1052,1053],{"class":163,"line":212},[161,1054,1055],{},"    except (TypeError, ValueError):\n",[161,1057,1058],{"class":163,"line":218},[161,1059,1040],{},[161,1061,1062],{"class":163,"line":224},[161,1063,1064],{},"    if exp == 0:\n",[161,1066,1067],{"class":163,"line":229},[161,1068,1069],{},"        return False\n",[161,1071,1072],{"class":163,"line":235},[161,1073,1074],{},"    return exp - time.time() \u003C 24 * 3600\n",[34,1076,1078],{"id":1077},"_5-decision-3-meta-tells-you-which-pages-you-can-access-not-which-one-the-merchant-wants-to-bind","5. Decision 3: Meta tells you which Pages you can access, not which one the merchant wants to bind",[10,1080,1081,1082,946,1084,1086,1087],{},"This is the least intuitive point in the whole chain. The Page checkboxes in the authorization dialog are multi-select and remembered, and both ",[27,1083,958],{},[27,1085,987],{}," return a set. The product rule, however, is one Page per merchant. ",[22,1088,1089],{},"Which one to bind has to be decided on our side.",[1091,1092,1093,1096,1103,1126],"ul",{},[921,1094,1095],{},"Exactly 1 in the set: bind it directly.",[921,1097,1098,1099,1102],{},"Empty set: 403 ",[27,1100,1101],{},"no_page",". The frontend explains that a business portfolio admin is required and the Page must be in the portfolio.",[921,1104,1105,1106,1109,1110,1113,1114,1117,1118,1121,1122,1125],{},"More than 1 in the set: return ",[27,1107,1108],{},"page_select_required"," with ",[27,1111,1112],{},"pages"," (id and name only, no tokens) and a ",[27,1115,1116],{},"selection_token",". The full list including Page tokens is encrypted and stashed in Redis with a short TTL, under a key built from the merchant id plus a high-entropy random string, so it cannot be used across merchants. After the merchant picks one in the card, the frontend calls ",[27,1119,1120],{},"select",". The server checks that the stash exists, that it decrypts, and that the chosen ",[27,1123,1124],{},"page_id"," is in the list, then deletes the stash once the bind succeeds.",[921,1127,1128,1131],{},[22,1129,1130],{},"Rejected: refusing outright when there are multiple Pages."," Because the authorization is remembered, the checkbox screen does not appear again on retry, and the merchant would be stuck at the authorization step.",[10,1133,1134],{},"So the frontend card has three states, and \"Page select\" is purely local:",[152,1136,1138],{"className":154,"code":1137,"language":156,"meta":157,"style":157},"stateDiagram-v2\n  [*] --> disconnected: Fetch status on mount\n  disconnected --> authorizing: Click Connect Facebook\n  authorizing --> disconnected: Dialog closed or denied, SDK load failed, config_id missing\n  authorizing --> connected: connect returns connected, exactly 1 Page granted\n  authorizing --> pageSelect: connect returns page_select_required, more than 1 Page\n  authorizing --> disconnected: connect returns disconnected, or 403 and 409 rejection\n  pageSelect --> connected: select returns connected\n  pageSelect --> pageSelect: select 409 ownership conflict, keep list and pick again\n  pageSelect --> disconnected: Cancel, stash expired or other failure\n  connected --> disconnected: unbind after Disconnect is confirmed\n  note right of pageSelect\n    Local frontend state, lost on refresh.\n    Meta only returns the set of Pages the App can access,\n    so choosing among several is up to us\n  end note\n",[27,1139,1140,1145,1150,1155,1160,1165,1170,1175,1180,1185,1190,1195,1200,1205,1210,1215],{"__ignoreMap":157},[161,1141,1142],{"class":163,"line":164},[161,1143,1144],{},"stateDiagram-v2\n",[161,1146,1147],{"class":163,"line":170},[161,1148,1149],{},"  [*] --> disconnected: Fetch status on mount\n",[161,1151,1152],{"class":163,"line":176},[161,1153,1154],{},"  disconnected --> authorizing: Click Connect Facebook\n",[161,1156,1157],{"class":163,"line":182},[161,1158,1159],{},"  authorizing --> disconnected: Dialog closed or denied, SDK load failed, config_id missing\n",[161,1161,1162],{"class":163,"line":188},[161,1163,1164],{},"  authorizing --> connected: connect returns connected, exactly 1 Page granted\n",[161,1166,1167],{"class":163,"line":194},[161,1168,1169],{},"  authorizing --> pageSelect: connect returns page_select_required, more than 1 Page\n",[161,1171,1172],{"class":163,"line":200},[161,1173,1174],{},"  authorizing --> disconnected: connect returns disconnected, or 403 and 409 rejection\n",[161,1176,1177],{"class":163,"line":206},[161,1178,1179],{},"  pageSelect --> connected: select returns connected\n",[161,1181,1182],{"class":163,"line":212},[161,1183,1184],{},"  pageSelect --> pageSelect: select 409 ownership conflict, keep list and pick again\n",[161,1186,1187],{"class":163,"line":218},[161,1188,1189],{},"  pageSelect --> disconnected: Cancel, stash expired or other failure\n",[161,1191,1192],{"class":163,"line":224},[161,1193,1194],{},"  connected --> disconnected: unbind after Disconnect is confirmed\n",[161,1196,1197],{"class":163,"line":229},[161,1198,1199],{},"  note right of pageSelect\n",[161,1201,1202],{"class":163,"line":235},[161,1203,1204],{},"    Local frontend state, lost on refresh.\n",[161,1206,1207],{"class":163,"line":241},[161,1208,1209],{},"    Meta only returns the set of Pages the App can access,\n",[161,1211,1212],{"class":163,"line":247},[161,1213,1214],{},"    so choosing among several is up to us\n",[161,1216,1217],{"class":163,"line":253},[161,1218,1219],{},"  end note\n",[10,1221,1222,1223,1226,1227,1229],{},"The ",[27,1224,1225],{},"status"," endpoint returns only connected and disconnected. The \"Page select\" state is lost on refresh; once the stash expires, ",[27,1228,1120],{}," is rejected and the card goes back to disconnected, and the merchant simply authorizes again.",[34,1231,1233],{"id":1232},"_6-decision-4-subscribe-to-the-webhook-first-then-persist","6. Decision 4: subscribe to the webhook first, then persist",[10,1235,1236,1237,1240,1241,946,1244,1247,1248,1251],{},"Binding means POST to that Page's ",[27,1238,1239],{},"subscribed_apps"," (subscribing to ",[27,1242,1243],{},"messages",[27,1245,1246],{},"messaging_postbacks","), then persist, then clear the routing cache. ",[22,1249,1250],{},"The order is subscribe first, persist second."," If the subscription fails, nothing is written, and the merchant clicks Connect again to retry the whole thing (Meta remembers the authorization, so the second time is very fast). The state needs only connected and disconnected, with no partial state and completion flow like WhatsApp has. What I rejected is persisting first and subscribing second.",[10,1253,1254],{},"The part that took real thought is the failure paths:",[152,1256,1258],{"className":154,"code":1257,"language":156,"meta":157,"style":157},"flowchart TD\n  S[\"Start binding the target Page\"] --> O{\"Page already owned by another merchant?\"}\n  O -->|Yes| C1[\"409 ownership conflict\"]\n  O -->|No| SUB[\"POST subscribed_apps to subscribe\"]\n  SUB -->|Failed| D1[\"Return disconnected\u003Cbr>Nothing written, whole flow retryable\"]\n  SUB -->|OK| W[\"Single UPDATE writes all five columns\u003Cbr>token encrypted\"]\n  W -->|Unique key violation| C2[\"409 ownership conflict\u003Cbr>No unsubscribe, the subscription belongs to the other merchant\"]\n  W -->|Other failure| COMP[\"Compensate: unsubscribe the new Page just subscribed\u003Cbr>Old binding left untouched\"]\n  COMP --> D2[\"Return disconnected\"]\n  W -->|OK| OLD{\"Same merchant switched Page?\"}\n  OLD -->|Yes| UNSUB[\"Best-effort unsubscribe of the old Page\"]\n  UNSUB --> OK[\"connected\"]\n  OLD -->|No| OK\n  W -.->|finally: always clear tenant cache for old and new Page| CC[\"Redis tenant cache\"]\n  style C1 fill:#fee2e2,stroke:#dc2626\n  style C2 fill:#fee2e2,stroke:#dc2626\n  style D1 fill:#fef3c7,stroke:#d97706\n  style D2 fill:#fef3c7,stroke:#d97706\n  style OK fill:#dcfce7,stroke:#16a34a\n",[27,1259,1260,1265,1270,1275,1280,1285,1290,1295,1300,1305,1310,1315,1320,1325,1330,1335,1340,1345,1350],{"__ignoreMap":157},[161,1261,1262],{"class":163,"line":164},[161,1263,1264],{},"flowchart TD\n",[161,1266,1267],{"class":163,"line":170},[161,1268,1269],{},"  S[\"Start binding the target Page\"] --> O{\"Page already owned by another merchant?\"}\n",[161,1271,1272],{"class":163,"line":176},[161,1273,1274],{},"  O -->|Yes| C1[\"409 ownership conflict\"]\n",[161,1276,1277],{"class":163,"line":182},[161,1278,1279],{},"  O -->|No| SUB[\"POST subscribed_apps to subscribe\"]\n",[161,1281,1282],{"class":163,"line":188},[161,1283,1284],{},"  SUB -->|Failed| D1[\"Return disconnected\u003Cbr>Nothing written, whole flow retryable\"]\n",[161,1286,1287],{"class":163,"line":194},[161,1288,1289],{},"  SUB -->|OK| W[\"Single UPDATE writes all five columns\u003Cbr>token encrypted\"]\n",[161,1291,1292],{"class":163,"line":200},[161,1293,1294],{},"  W -->|Unique key violation| C2[\"409 ownership conflict\u003Cbr>No unsubscribe, the subscription belongs to the other merchant\"]\n",[161,1296,1297],{"class":163,"line":206},[161,1298,1299],{},"  W -->|Other failure| COMP[\"Compensate: unsubscribe the new Page just subscribed\u003Cbr>Old binding left untouched\"]\n",[161,1301,1302],{"class":163,"line":212},[161,1303,1304],{},"  COMP --> D2[\"Return disconnected\"]\n",[161,1306,1307],{"class":163,"line":218},[161,1308,1309],{},"  W -->|OK| OLD{\"Same merchant switched Page?\"}\n",[161,1311,1312],{"class":163,"line":224},[161,1313,1314],{},"  OLD -->|Yes| UNSUB[\"Best-effort unsubscribe of the old Page\"]\n",[161,1316,1317],{"class":163,"line":229},[161,1318,1319],{},"  UNSUB --> OK[\"connected\"]\n",[161,1321,1322],{"class":163,"line":235},[161,1323,1324],{},"  OLD -->|No| OK\n",[161,1326,1327],{"class":163,"line":241},[161,1328,1329],{},"  W -.->|finally: always clear tenant cache for old and new Page| CC[\"Redis tenant cache\"]\n",[161,1331,1332],{"class":163,"line":247},[161,1333,1334],{},"  style C1 fill:#fee2e2,stroke:#dc2626\n",[161,1336,1337],{"class":163,"line":253},[161,1338,1339],{},"  style C2 fill:#fee2e2,stroke:#dc2626\n",[161,1341,1342],{"class":163,"line":259},[161,1343,1344],{},"  style D1 fill:#fef3c7,stroke:#d97706\n",[161,1346,1347],{"class":163,"line":264},[161,1348,1349],{},"  style D2 fill:#fef3c7,stroke:#d97706\n",[161,1351,1352],{"class":163,"line":270},[161,1353,1354],{},"  style OK fill:#dcfce7,stroke:#16a34a\n",[1091,1356,1357,1363,1373,1379],{},[921,1358,1359,1362],{},[22,1360,1361],{},"Persistence fails",": compensate by unsubscribing the new Page that was just subscribed, so Meta does not keep pushing events nobody owns. The old binding is left as it was and keeps serving. Rebinding the same Page does not unsubscribe, because the subscription still belongs to this merchant's existing binding.",[921,1364,1365,1368,1369,1372],{},[22,1366,1367],{},"Persistence hits the unique key",": treat it as a 409 ownership conflict and do ",[22,1370,1371],{},"not"," compensate with an unsubscribe. That Page's subscription belongs to the other merchant.",[921,1374,1375,1378],{},[22,1376,1377],{},"Same merchant switches Page",": unsubscribe the old Page, best-effort, only after persistence succeeds. The order cannot be reversed. Unsubscribe first, and a failed write leaves the old Page without service while the database still points at it. If the old token fails to decrypt, the unsubscribe is just skipped, and the leftover subscription on Meta's side is covered by the token becoming invalid.",[921,1380,1381,1387,1388,1390],{},[22,1382,1383,1384],{},"Cache clearing runs unconditionally in ",[27,1385,1386],{},"finally",", for both the old and the new ",[27,1389,1124],{},". The new Page may still have a cache entry from before another merchant unbound it, and the old Page's cache no longer matches the database. Without clearing, the old credential keeps routing until the cache entry expires.",[34,1392,1394],{"id":1393},"_7-decision-5-credential-encryption-page-ownership-and-concurrency","7. Decision 5: credential encryption, Page ownership and concurrency",[1396,1397,1399],"h3",{"id":1398},"_71-versioned-ciphertext-prefix-older-format-still-readable","7.1 Versioned ciphertext prefix, older format still readable",[10,1401,1402,1403,1406],{},"The Page token is encrypted with Fernet before it is stored, and the ciphertext carries an ",[27,1404,1405],{},"enc:v1:"," prefix. The key falls under the same key management as the other channel credentials. The read side has only two rules:",[152,1408,1410],{"className":1006,"code":1409,"language":1008,"meta":157,"style":157},"def decrypt_value(stored: str, key: str) -> str:\n    if not stored:\n        return stored or \"\"\n    if not stored.startswith(\"enc:v1:\"):\n        return stored                       # no version prefix: read as the older format for compatibility\n    try:\n        return Fernet(key.encode()).decrypt(stored[len(\"enc:v1:\"):].encode(\"ascii\")).decode(\"utf-8\")\n    except (InvalidToken, ValueError) as e:\n        raise CryptoError(\"凭据解密失败\") from e   # prefixed but undecryptable must raise (fail closed); never send ciphertext out as if it were plaintext\n",[27,1411,1412,1417,1422,1427,1432,1437,1441,1446,1451],{"__ignoreMap":157},[161,1413,1414],{"class":163,"line":164},[161,1415,1416],{},"def decrypt_value(stored: str, key: str) -> str:\n",[161,1418,1419],{"class":163,"line":170},[161,1420,1421],{},"    if not stored:\n",[161,1423,1424],{"class":163,"line":176},[161,1425,1426],{},"        return stored or \"\"\n",[161,1428,1429],{"class":163,"line":182},[161,1430,1431],{},"    if not stored.startswith(\"enc:v1:\"):\n",[161,1433,1434],{"class":163,"line":188},[161,1435,1436],{},"        return stored                       # no version prefix: read as the older format for compatibility\n",[161,1438,1439],{"class":163,"line":194},[161,1440,1045],{},[161,1442,1443],{"class":163,"line":200},[161,1444,1445],{},"        return Fernet(key.encode()).decrypt(stored[len(\"enc:v1:\"):].encode(\"ascii\")).decode(\"utf-8\")\n",[161,1447,1448],{"class":163,"line":206},[161,1449,1450],{},"    except (InvalidToken, ValueError) as e:\n",[161,1452,1453],{"class":163,"line":212},[161,1454,1455],{},"        raise CryptoError(\"凭据解密失败\") from e   # prefixed but undecryptable must raise (fail closed); never send ciphertext out as if it were plaintext\n",[10,1457,1458,1459,1462],{},"A version number in the prefix helps in both directions: data in the older format does not need a one-off migration, and a future algorithm change can move over smoothly with ",[27,1460,1461],{},"enc:v2",". Fernet ciphertext is longer than the plaintext, so the column has to be widened at the same time. When the Messenger message service reads a token that fails to decrypt, it treats the Page as not connected.",[1396,1464,1466],{"id":1465},"_72-page-ownership-check-before-write-with-a-unique-key-as-the-backstop","7.2 Page ownership: check before write, with a unique key as the backstop",[10,1468,1469,1470,1472,1473,1476],{},"A Page belongs to exactly one merchant, guaranteed by a unique key on the Page ID column of the merchant table. Before binding, the service looks up ownership by ",[27,1471,1124],{}," and returns 409 straight away if another merchant has it. If someone else grabs the Page in the window between the check and the write, the ",[27,1474,1475],{},"IntegrityError"," raised by the unique key maps to the same conflict code. In the \"Page select\" state the frontend keeps the list on a 409 so the merchant can pick another; any other error clears it and returns to disconnected.",[1396,1478,1480],{"id":1479},"_73-concurrency-merchant-lock-atomic-write-of-the-whole-group-conditional-unbind","7.3 Concurrency: merchant lock, atomic write of the whole group, conditional unbind",[50,1482,1483,1496],{},[53,1484,1485],{},[56,1486,1487,1490,1493],{},[59,1488,1489],{},"Measure",[59,1491,1492],{},"Problem it solves",[59,1494,1495],{},"Implementation",[69,1497,1498,1509,1533],{},[56,1499,1500,1503,1506],{},[74,1501,1502],{},"Per-merchant serial lock",[74,1504,1505],{},"Two concurrent binds for one merchant can put A's token and B's Page in the same row; an unbind can wipe a new binding that is in progress",[74,1507,1508],{},"Redis SET NX with a short TTL that covers the worst-case duration of one bind. While held, return 409 \"binding in progress\". When the Redis behind the lock is unavailable there is a choice between fail open and fail closed. I chose availability and log an error, so a cache outage does not block merchant onboarding, and the two rows below protect data correctness",[56,1510,1511,1514,1517],{},[74,1512,1513],{},"Single UPDATE writing all five columns",[74,1515,1516],{},"The ORM pattern of loading an object, changing attributes and committing only updates dirty columns, so concurrency can produce a mixed row of \"Page B + token A\". A unique index cannot catch a mismatch inside one row",[74,1518,1519,1520,942,1522,1525,1526,1529,1530,1532],{},"The repository layer explicitly writes ",[27,1521,1124],{},[27,1523,1524],{},"page_name",", token, owner and ",[27,1527,1528],{},"connected_at"," as one atomic overwrite, with ",[27,1531,1528],{}," taken from the database's current time",[56,1534,1535,1538,1541],{},[74,1536,1537],{},"Conditional update on unbind",[74,1539,1540],{},"A concurrent rebind between the read and the clear means an unconditional clear wipes the binding someone else just wrote",[74,1542,1543,1544,1546],{},"The WHERE clause includes the ",[27,1545,1124],{}," that was read, as a version condition. Zero rows matched returns a failure that is handled as safe to retry. The five columns are set to NULL, not empty strings: a unique index allows many NULL rows, and empty strings would collide",[34,1548,1550],{"id":1549},"_8-decision-6-one-meta-app-has-only-one-page-webhook-callback-url","8. Decision 6: one Meta App has only one Page webhook callback URL",[10,1552,1553,1554,1557,1558,1560,1561,1563,1564,1567],{},"After consolidating into one Meta App, a new problem showed up: ",[22,1555,1556],{},"the Page webhook is a single callback URL at the app level",". WhatsApp lets you override the callback URL per WABA when calling ",[27,1559,1239],{},". Messenger's ",[27,1562,1239],{}," accepts only ",[27,1565,1566],{},"subscribed_fields"," and has no such option. With test and production sharing one App, only one environment can receive messages.",[50,1569,1570,1580],{},[53,1571,1572],{},[56,1573,1574,1577],{},[59,1575,1576],{},"Option",[59,1578,1579],{},"Problem",[69,1581,1582,1590,1598],{},[56,1583,1584,1587],{},[74,1585,1586],{},"Switch the callback URL between the two environments by hand",[74,1588,1589],{},"Only one environment works at any given time",[56,1591,1592,1595],{},[74,1593,1594],{},"Keep the old App for the test environment",[74,1596,1597],{},"The frontend has to maintain two App IDs, which brings back the SDK initialization conflict",[56,1599,1600,1605],{},[74,1601,1602],{},[22,1603,1604],{},"Point the callback at production permanently, and have production forward events for Pages it cannot find to test, unchanged",[74,1606,1607],{},"Both environments work at once; with no forward URL configured, behavior is unchanged",[10,1609,1610,1611,1614,1615,1618],{},"The key constraint: ",[27,1612,1613],{},"X-Hub-Signature-256"," covers the entire request body, so the body cannot be split or rewritten. The design is therefore \"",[22,1616,1617],{},"forward the whole payload, and each environment only handles the Pages in its own database","\":",[152,1620,1622],{"className":154,"code":1621,"language":156,"meta":157,"style":157},"flowchart TD\n  W[\"Meta Page webhook\u003Cbr>POST to production\"] --> S{\"X-Hub-Signature-256\u003Cbr>HMAC-SHA256 verification\"}\n  S -->|Fails| X[\"Drop, return 200\"]\n  S -->|Passes| ACK[\"Parse payload, return 200 immediately\u003Cbr>Everything after runs as a background task\"]\n  ACK --> P{\"Forward URL configured\u003Cbr>and no forwarded-marker header?\"}\n  P -->|No| L[\"Handle every entry locally\u003Cbr>Same behavior as before\"]\n  P -->|Yes| T[\"Look up this environment's tenant by entry.id\u003Cbr>Cache first, merchant table on miss\"]\n  T --> K[\"Connected entries\u003Cbr>Deduplicate, then dispatch AI reply\"]\n  T --> U{\"Any entry not connected here?\"}\n  U -->|No| E[\"Done\"]\n  U -->|Yes| FWD[\"Original body, original signature header, plus marker header\u003Cbr>Forward to peer asynchronously with a timeout, failures only logged\"]\n  FWD --> PEER[\"Peer verifies with the same app_secret\u003Cbr>Handles only its own Pages, never forwards again\"]\n  style ACK fill:#dbeafe,stroke:#155dfc\n  style FWD fill:#fef3c7,stroke:#d97706\n  style PEER fill:#fef3c7,stroke:#d97706\n",[27,1623,1624,1628,1633,1638,1643,1648,1653,1658,1663,1668,1673,1678,1683,1688,1693],{"__ignoreMap":157},[161,1625,1626],{"class":163,"line":164},[161,1627,1264],{},[161,1629,1630],{"class":163,"line":170},[161,1631,1632],{},"  W[\"Meta Page webhook\u003Cbr>POST to production\"] --> S{\"X-Hub-Signature-256\u003Cbr>HMAC-SHA256 verification\"}\n",[161,1634,1635],{"class":163,"line":176},[161,1636,1637],{},"  S -->|Fails| X[\"Drop, return 200\"]\n",[161,1639,1640],{"class":163,"line":182},[161,1641,1642],{},"  S -->|Passes| ACK[\"Parse payload, return 200 immediately\u003Cbr>Everything after runs as a background task\"]\n",[161,1644,1645],{"class":163,"line":188},[161,1646,1647],{},"  ACK --> P{\"Forward URL configured\u003Cbr>and no forwarded-marker header?\"}\n",[161,1649,1650],{"class":163,"line":194},[161,1651,1652],{},"  P -->|No| L[\"Handle every entry locally\u003Cbr>Same behavior as before\"]\n",[161,1654,1655],{"class":163,"line":200},[161,1656,1657],{},"  P -->|Yes| T[\"Look up this environment's tenant by entry.id\u003Cbr>Cache first, merchant table on miss\"]\n",[161,1659,1660],{"class":163,"line":206},[161,1661,1662],{},"  T --> K[\"Connected entries\u003Cbr>Deduplicate, then dispatch AI reply\"]\n",[161,1664,1665],{"class":163,"line":212},[161,1666,1667],{},"  T --> U{\"Any entry not connected here?\"}\n",[161,1669,1670],{"class":163,"line":218},[161,1671,1672],{},"  U -->|No| E[\"Done\"]\n",[161,1674,1675],{"class":163,"line":224},[161,1676,1677],{},"  U -->|Yes| FWD[\"Original body, original signature header, plus marker header\u003Cbr>Forward to peer asynchronously with a timeout, failures only logged\"]\n",[161,1679,1680],{"class":163,"line":229},[161,1681,1682],{},"  FWD --> PEER[\"Peer verifies with the same app_secret\u003Cbr>Handles only its own Pages, never forwards again\"]\n",[161,1684,1685],{"class":163,"line":235},[161,1686,1687],{},"  style ACK fill:#dbeafe,stroke:#155dfc\n",[161,1689,1690],{"class":163,"line":241},[161,1691,1692],{},"  style FWD fill:#fef3c7,stroke:#d97706\n",[161,1694,1695],{"class":163,"line":247},[161,1696,1697],{},"  style PEER fill:#fef3c7,stroke:#d97706\n",[1091,1699,1700,1707,1710,1713],{},[921,1701,1702,1703,1706],{},"The forwarded request carries the original body and the original signature header, plus one marker header. The peer verifies the signature with the same App's ",[27,1704,1705],{},"app_secret"," and handles only the Pages in its own database. A request with the marker header is never forwarded again, which prevents loops.",[921,1708,1709],{},"Forwarding has a timeout, and a failure is only logged. It does not affect this environment returning 200 to Meta.",[921,1711,1712],{},"The tenant pre-check uses the cache and only queries the database on a miss. A Page that is not connected here is not logged as an error, because a Page from the other environment is expected to be missing from this database.",[921,1714,1715,1716,1719],{},"Meta requires the webhook to return 200 quickly and retries on timeout as a failure, so the team designed for a 5-second budget: ACK right after signature verification and parsing, and run tenant splitting, forwarding, message deduplication (",[27,1717,1718],{},"mid"," SET NX with a short TTL) and dispatch as a background task. Neither a cold cache nor a slow query can hold up the response.",[152,1721,1723],{"className":1006,"code":1722,"language":1008,"meta":157,"style":157},"headers = {\n    \"Content-Type\": \"application\u002Fjson\",\n    \"X-Hub-Signature-256\": signature,   # pass the original signature header through unchanged\n    \"X-Peer-Forwarded\": \"1\",            # marker header (illustrative name): the peer never forwards again when it sees this\n}\nasync with httpx.AsyncClient(timeout=5) as client:\n    resp = await client.post(forward_url, content=body, headers=headers)   # not one byte of the body may change\n",[27,1724,1725,1730,1735,1740,1745,1750,1755],{"__ignoreMap":157},[161,1726,1727],{"class":163,"line":164},[161,1728,1729],{},"headers = {\n",[161,1731,1732],{"class":163,"line":170},[161,1733,1734],{},"    \"Content-Type\": \"application\u002Fjson\",\n",[161,1736,1737],{"class":163,"line":176},[161,1738,1739],{},"    \"X-Hub-Signature-256\": signature,   # pass the original signature header through unchanged\n",[161,1741,1742],{"class":163,"line":182},[161,1743,1744],{},"    \"X-Peer-Forwarded\": \"1\",            # marker header (illustrative name): the peer never forwards again when it sees this\n",[161,1746,1747],{"class":163,"line":188},[161,1748,1749],{},"}\n",[161,1751,1752],{"class":163,"line":194},[161,1753,1754],{},"async with httpx.AsyncClient(timeout=5) as client:\n",[161,1756,1757],{"class":163,"line":200},[161,1758,1759],{},"    resp = await client.post(forward_url, content=body, headers=headers)   # not one byte of the body may change\n",[34,1761,1763],{"id":1762},"_9-layered-error-semantics-let-the-frontend-act-on-meaning-not-on-status-codes","9. Layered error semantics: let the frontend act on meaning, not on status codes",[10,1765,1766],{},"For the connect, select and unbind endpoints the frontend turns off the global error toast, and the binding hook maps keywords in the response message to localized copy. Only status keeps the global interceptor. The mapping from server exceptions to response codes:",[50,1768,1769,1784],{},[53,1770,1771],{},[56,1772,1773,1775,1778,1781],{},[59,1774,27],{},[59,1776,1777],{},"message",[59,1779,1780],{},"When it happens",[59,1782,1783],{},"Frontend handling",[69,1785,1786,1808,1822,1835,1848,1862,1876,1890],{},[56,1787,1788,1791,1794,1800],{},[74,1789,1790],{},"403",[74,1792,1793],{},"connect rejected: reason",[74,1795,1796,1797,1799],{},"Authorization validation failed or the assets do not qualify: code exchange failed, ",[27,1798,925],{}," invalid, scopes missing, no Page, stash expired, chosen Page not in the list",[74,1801,1802,946,1804,1807],{},[27,1803,1101],{},[27,1805,1806],{},"scopes_missing"," have dedicated copy; selection-related reasons return to disconnected; everything else uses the generic failure copy",[56,1809,1810,1813,1816,1819],{},[74,1811,1812],{},"409",[74,1814,1815],{},"page bound to another shop",[74,1817,1818],{},"The Page already belongs to another merchant",[74,1820,1821],{},"Say it is connected to another account; in the Page select state keep the list so another can be picked",[56,1823,1824,1826,1829,1832],{},[74,1825,1812],{},[74,1827,1828],{},"binding in progress, retry later",[74,1830,1831],{},"Another connect or disconnect for the same merchant is in progress",[74,1833,1834],{},"Ask to retry shortly",[56,1836,1837,1839,1842,1845],{},[74,1838,1812],{},[74,1840,1841],{},"unbind rejected: not_bound",[74,1843,1844],{},"Nothing is bound when unbind is called",[74,1846,1847],{},"Treat as already disconnected and refresh status",[56,1849,1850,1853,1856,1859],{},[74,1851,1852],{},"429",[74,1854,1855],{},"too many requests",[74,1857,1858],{},"The per-IP fixed-window rate limit was hit",[74,1860,1861],{},"Generic failure copy",[56,1863,1864,1867,1870,1873],{},[74,1865,1866],{},"502",[74,1868,1869],{},"meta service unavailable, safe to retry",[74,1871,1872],{},"Meta network error, or writing the Redis stash failed",[74,1874,1875],{},"Generic failure copy, retryable",[56,1877,1878,1881,1884,1887],{},[74,1879,1880],{},"503",[74,1882,1883],{},"messenger app not configured",[74,1885,1886],{},"App ID or App Secret is not configured on the server",[74,1888,1889],{},"Say the environment is not configured; retrying is pointless, so it must be distinct from 502",[56,1891,1892,1895,1898,1901],{},[74,1893,1894],{},"500",[74,1896,1897],{},"unbind failed, safe to retry",[74,1899,1900],{},"Clearing the columns locally failed during unbind, including a conditional update that matched nothing",[74,1902,1903],{},"Ask to retry",[10,1905,1906,1907,1910,1911,1914],{},"The 503 was added during development. With the configuration missing, calling Meta with an empty ",[27,1908,1909],{},"client_id"," only gives back a vague ",[27,1912,1913],{},"code_exchange_failed",". The merchant sees \"authorization rejected\", and so does ops. Separating \"needs configuration\" from \"retryable\" and \"rejected\" cuts the debugging cost by an order of magnitude.",[34,1916,1918],{"id":1917},"_10-rollout-order-and-compatibility-with-existing-data","10. Rollout order and compatibility with existing data",[1091,1920,1921,1927,1942,1948,1954],{},[921,1922,1923,1926],{},[22,1924,1925],{},"DDL goes out before the service."," The new ORM model includes the two new columns, and if the database lacks them every ORM query on the merchant table fails, which also breaks tenant lookup for WhatsApp and Instagram. The DDL itself is nullable columns and a widened column, has no effect on the old code, and can be run ahead of time. Order: DDL, then the agent service, then the admin console, then point the Page webhook at production in the Meta dashboard.",[921,1928,1929,1932,1933,1935,1936,1938,1939,1941],{},[22,1930,1931],{},"Compatibility for existing bindings",": credentials in the older format stay readable, so no one-off migration is needed. ",[27,1934,1225],{}," reports connected when both ",[27,1937,1124],{}," and the token are non-empty. When ",[27,1940,1524],{}," is empty the frontend falls back to showing the Page ID.",[921,1943,1944,1947],{},[22,1945,1946],{},"The cost of switching Meta Apps",": existing Pages attached to the old App stop receiving messages because the signing secret changes. The merchant has to authorize once more on the settings page, which stores the credential under the new scheme and subscribes the Page to the new App. Existing bindings are inventoried before launch and handled in the same window as the switch.",[921,1949,1950,1953],{},[22,1951,1952],{},"The three permissions on the production App need Advanced Access."," Otherwise only users with a role on the App can authorize successfully. This is the blocker most easily overlooked before launch.",[921,1955,1956,1959],{},[22,1957,1958],{},"Verification",": the test environment ran the full loop of authorize, connected card, visitor message, AI reply. On the server, three new unit test suites (auth orchestration, endpoint layer, webhook forwarding) pass along with the existing WhatsApp tests. The frontend login hook tests cover SDK loading, cancel, the once guard, missing configuration, timeout, and no callback after unmount.",[34,1961,1963],{"id":1962},"_11-lessons-worth-reusing","11. Lessons worth reusing",[1091,1965,1966,1972,1978,1984,1990,1996,2002,2008],{},[921,1967,1968,1971],{},[22,1969,1970],{},"In a third-party authorization chain, the frontend only fetches the credential."," Token exchange, validation and persistence all happen on the server. The credential never passes through the frontend, the logic lives in one place, and switching token type needs no frontend change.",[921,1973,1974,1977],{},[22,1975,1976],{},"When the platform returns a set, you need a selection state on your side",", and you have to account for the platform remembering the authorization. Refusing outright leaves the user stuck.",[921,1979,1980,1983],{},[22,1981,1982],{},"For multi-step operations with external side effects, put the step that needs no cleanup on failure first."," Subscribe then persist, and the failure path converges on \"nothing was written\", with compensation needed in only one place.",[921,1985,1986,1989],{},[22,1987,1988],{},"Use a versioned prefix for encrypted storage."," Data in the older format needs no one-off migration, and a future algorithm change is smooth. Prefixed but undecryptable must fail closed.",[921,1991,1992,1995],{},[22,1993,1994],{},"Write a group of fields concurrently with a single UPDATE, and do not trust ORM dirty checking."," Use a conditional update as an optimistic lock for deletes. Set unique-key columns to NULL, not to an empty string.",[921,1997,1998,2001],{},[22,1999,2000],{},"Beyond the status code, keep stable keywords in the message"," so the frontend can map copy by meaning. \"Retryable\", \"rejected\" and \"needs configuration\" must be three separate things.",[921,2003,2004,2007],{},[22,2005,2006],{},"A webhook signature covers the whole body, so forwarding has to be the whole payload."," The response has a deadline, so ACK first and do the work after.",[921,2009,2010,2013],{},[22,2011,2012],{},"Find out the platform's constraints at the design stage."," A limit like \"one App has only one callback URL\" costs a full redesign if you discover it when the test environment stops receiving messages.",[2015,2016,2017],"style",{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .suiK_, html code.shiki .suiK_{--shiki-light:#005CC5;--shiki-default:#79B8FF;--shiki-dark:#79B8FF}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sQHwn, html code.shiki .sQHwn{--shiki-light:#E36209;--shiki-default:#FFAB70;--shiki-dark:#FFAB70}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}",{"title":157,"searchDepth":170,"depth":170,"links":2019},[2020,2021,2022,2023,2024,2025,2026,2031,2032,2033,2034],{"id":36,"depth":170,"text":37},{"id":146,"depth":170,"text":147},{"id":594,"depth":170,"text":595},{"id":836,"depth":170,"text":837},{"id":1077,"depth":170,"text":1078},{"id":1232,"depth":170,"text":1233},{"id":1393,"depth":170,"text":1394,"children":2027},[2028,2029,2030],{"id":1398,"depth":176,"text":1399},{"id":1465,"depth":176,"text":1466},{"id":1479,"depth":176,"text":1480},{"id":1549,"depth":170,"text":1550},{"id":1762,"depth":170,"text":1763},{"id":1917,"depth":170,"text":1918},{"id":1962,"depth":170,"text":1963},"2026-09-04","A merchant clicks Connect Facebook once in the admin console and their Page is live on our Messenger AI assistant. The frontend only produces a code; token exchange, validation, Page selection, webhook subscription and encrypted storage all happen on the server, plus a cross-environment fix for an app that has only one webhook callback URL.","md",null,"\u002Farticles\u002Fmessenger-one-click-auth.svg",{},true,"\u002Farticles\u002Fmessenger-one-click-auth","17",{"title":5,"description":2036},{"loc":2042},"articles\u002Fmessenger-one-click-auth",[2048,2049],"Full-Stack","Backend","cp2eFt0Sfa6kgLB4hLUjWMIMMsIACPK-YAxhN01setg",1795761651384]