if((requestBody.hasOwnProperty('message'))&&(requestBody.message.hasOwnProperty('data'))){// Validate the received hash to ensure the message came from Google RBMletuserEventString=Buffer.from(requestBody.message.data,'base64');lethmac=crypto.createHmac('sha512',CLIENT_TOKEN);letdata=hmac.update(userEventString);letgenHash=data.digest('base64');letheaderHash=req.header('X-Goog-Signature');if(headerHash===genHash){letuserEvent=JSON.parse(userEventString);console.log('userEventString: '+userEventString);handleMessage(userEvent);}else{console.log('hash mismatch - ignoring message');}}res.sendStatus(200);
메시지 처리
webhook에서 200 OK 이외의 항목을 반환하면 전송 실패로 간주됩니다.
개발자는 메시지를 빠른 속도로 전송하면 webhook 알림이 빠른 속도로 생성된다는 점에 유의해야 하며 예상 속도로 알림을 사용할 수 있도록 코드를 설계해야 합니다. 개발자는 웹 컨테이너의 500 응답, 시간 초과 또는 업스트림 실패 등 실패 응답을 일으킬 수 있는 상황을 고려해야 합니다. 고려해야 할 사항은 다음과 같습니다.
예상되는 webhook 알림 비율을 처리하도록 DDoS 보호가 구성되어 있는지 확인합니다.
데이터베이스 연결 풀과 같은 리소스가 부족하여 시간 초과 또는 500 응답이 발생하지 않도록 합니다.
개발자는 RBM 이벤트 처리가 비동기식으로 실행되고 webhook이 200 OK를 반환하지 못하도록 방해하지 않도록 해야 합니다.
웹훅 자체 내에서 RBM 이벤트를 처리하지 않는 것이 중요합니다. 처리 중에 오류나 지연이 발생하면 webhook 반환 코드에 영향을 줄 수 있습니다.
전송 실패 시 동작
RBM은 웹훅 호출에서 200 OK이 아닌 응답을 수신하면 백오프 및 재시도 메커니즘을 사용합니다. RBM은 재시도 사이의 대기 시간을 최대 600초까지 늘립니다. 재시도는 7일 동안 계속되며 그 후에는 메시지가 삭제됩니다.
상담사 수준 웹훅의 의미
RBM은 파트너의 메시지를 하나의 큐에 큐에 추가합니다. 파트너가 상담사 수준 webhook을 사용하는 경우 하나의 webhook이 실패하면 다른 webhook에 대한 전송에 영향을 미친다는 점에 유의해야 합니다. 다른 상담사 소유의 웹훅은 메시지 실패의 백오프 기간 동안 호출됩니다.
하지만 실패한 메시지가 재시도를 위해 대기열에 추가되면 전반적인 전송 비율이 떨어지고 다른 상담사에게도 영향을 미칩니다.
개발자는 이 모델을 이해하고 그에 따라 코딩해야 합니다. 최대한 메시지를 수락하고 처리를 위해 메시지를 큐에 추가하여 실패를 반환할 가능성을 최소화해야 합니다.
[null,null,["최종 업데이트: 2025-04-03(UTC)"],[[["\u003cp\u003eA webhook is a URL where the RBM platform sends messages and events via HTTPS POST requests, serving as a secure endpoint for data delivery.\u003c/p\u003e\n"],["\u003cp\u003eYou can configure webhooks at either the partner level, affecting all agents, or at the individual agent level, allowing for distinct behaviors per agent, with agent-level webhooks taking priority.\u003c/p\u003e\n"],["\u003cp\u003eTo ensure message authenticity, it's essential to verify that incoming messages are from Google by comparing the \u003ccode\u003eX-Goog-Signature\u003c/code\u003e header with a generated hash using your webhook's client token.\u003c/p\u003e\n"],["\u003cp\u003eWebhooks should return a \u003ccode\u003e200 OK\u003c/code\u003e response to acknowledge receipt; any other response triggers a retry mechanism that increases the wait time up to 600 seconds and continues for 7 days before dropping the message.\u003c/p\u003e\n"],["\u003cp\u003eWhen implementing agent-level webhooks, be aware that the failure of one webhook can affect message delivery to other webhooks due to the backoff and retry mechanism, emphasizing the need to code for message acceptance and queuing.\u003c/p\u003e\n"]]],[],null,["# Webhooks\n\nA webhook is a partner-specified URL where the RBM platform posts\n[messages](/business-communications/rcs-business-messaging/guides/build/messages/receive)\nand [events](/business-communications/rcs-business-messaging/guides/build/events).\nThis URL acts as an endpoint that receives HTTPS POST requests containing data\nabout the events. This means that data is sent to your application securely over\nHTTPS.\n\nA webhook URL might look something like this:\n`https://[your company name].com/api/rbm-events`.\nOnce you configure your webhook, you can start receiving messages and events.\n\nPartner webhooks and agent webhooks\n-----------------------------------\n\nYou can configure your webhook either at the partner level or at the agent\nlevel.\n\n- Your partner webhook applies to every agent you maintain. If your agents have similar behavior, or if you only have one agent, use the [partner webhook](/business-communications/rcs-business-messaging/guides/get-started/partner-account#configure_your_partner_webhook).\n- Agent webhooks apply to individual agents. If you operate multiple agents with distinct behavior, you can [set a different webhook for each agent](/business-communications/rcs-business-messaging/guides/integrate/webhooks#configure_an_agent_webhook).\n\nIf you've configured both a partner webhook and an agent webhook, the agent\nwebhook takes precedence on its specific agent, while the partner webhook\napplies to any agents that don't have their own webhook.\n\nConfigure an agent webhook\n--------------------------\n\n| **Note:** To create a webhook integration using the RBM Management API, refer to the [Create a webhook integration](/business-communications/rcs-business-messaging/guides/management-api/webhooks#create_a_webhook_integration) documentation.\n\nYou receive messages sent to your agent at your partner webhook. If you want\nmessages for a specific agent to arrive at a different webhook instead, set an\nagent webhook.\n\n1. Open the [Business Communications Developer Console](https://business-communications.cloud.google.com/?utm_source=/business-communications/business-messages/guides/how-to/agents&utm_medium=devsite&utm_campaign=rcs-business-messaging) and sign in with your RBM partner Google Account.\n2. Click your agent.\n3. Click **Integrations**.\n4. For **Webhook** , click **Configure**.\n5. For **Webhook endpoint URL**, enter your webhook URL beginning with \"https://\".\n6. Note your `clientToken` value. You need it to [verify that messages you receive are coming from Google](/business-communications/rcs-business-messaging/guides/integrate/webhooks#verify_incoming_messages).\n7. Configure your webhook to accept a `POST` request with the specified\n `clientToken` parameter and send a `200 OK` response with the plain text value\n of the `secret` parameter as the response body.\n\n For example, if your webhook receives a `POST` request with the following\n body content \n\n {\n \"clientToken\":\"SJENCPGJESMGUFPY\",\n \"secret\":\"1234567890\"\n }\n\n then your webhook should confirm the `clientToken` value and, if\n `clientToken` is correct, return a `200 OK` response with `1234567890` as\n the response body: \n\n // clientToken from Configure\n const myClientToken = \"SJENCPGJESMGUFPY\";\n\n // Example endpoint\n app.post(\"/rbm-webhook\", (req, res) =\u003e {\n const msg = req.body;\n if (msg.clientToken === myClientToken) {\n res.status(200).send(msg.secret);\n return;\n }\n res.send(400);\n });\n\n8. In the Developer Console, click **Verify**. When RBM verifies your webhook,\n the dialog closes.\n\nVerify incoming messages\n------------------------\n\nBecause webhooks can receive messages from any senders, you should verify that\nGoogle sent incoming messages before processing message content.\n\nTo verify that Google sent a message you received, follow these steps:\n\n1. Extract the message's `X-Goog-Signature` header. This is a hashed, base64-encoded copy of the message body payload.\n2. Base-64-decode the RBM payload in the `message.body` element of the request.\n3. Using your webhook's client token (which you specified when you set up your webhook) as a key, create a SHA512 HMAC of the bytes of the base-64 decoded message payload and base64-encode the result.\n4. Compare the `X-Goog-Signature` hash with the hash you created.\n - If the hashes match, you've confirmed that Google sent the message.\n - If the hashes don't match, check your hashing process on a known-good\n message.\n\n If your hashing process is working correctly and you receive a\n message that you believe was fraudulently sent to you,\n [contact us](https://support.google.com/messages/contact/contact_us).\n\n### Node.js\n\n```javascript\n if ((requestBody.hasOwnProperty('message')) && (requestBody.message.hasOwnProperty('data'))) {\n // Validate the received hash to ensure the message came from Google RBM\n let userEventString = Buffer.from(requestBody.message.data, 'base64');\n let hmac = crypto.createHmac('sha512', CLIENT_TOKEN);\n let data = hmac.update(userEventString);\n let genHash = data.digest('base64');\n let headerHash = req.header('X-Goog-Signature');\n\n if (headerHash === genHash) {\n let userEvent = JSON.parse(userEventString);\n\n console.log('userEventString: ' + userEventString);\n handleMessage(userEvent);\n } else {\n console.log('hash mismatch - ignoring message');\n }\n }\n\n res.sendStatus(200);\n \n```\n\nMessage handling\n----------------\n\nReturning anything other than `200 OK` from a webhook is considered a delivery\nfailure.\n\nDevelopers must be mindful that sending messages at high rates will\ngenerate webhook notifications at high rates and must design their code to\nhandle notifications at the expected rate. It is important for developers to\nconsider situations that may cause failure responses - including `500` responses\nfrom their web container, timeouts, or upstream failures. Things to consider\ninclude:\n\n- Verify that your DDoS protections are configured to handle the expected rate of webhook notifications.\n- Confirm that resources such as database connection pools don't run out and produce timeouts or `500` responses.\n\nDevelopers should design their systems so the processing of RBM events occurs\nasynchronously and doesn't prevent the webhook from returning `200 OK`.\n\n\nIt is important to **not** process the RBM event within the webhook itself. Any\nerror or delay during processing may impact the webhook return code:\n\n\n### Behavior on delivery failure\n\nRBM uses a backoff and retry mechanism when it receives a response other than\n`200 OK` from a webhook call. RBM will increase the time it waits between\nretries up to a maximum of 600 seconds. Retries will continue for **7 days**,\nafter which the message will be dropped.\n\n### Implications of agent-level webhooks\n\nRBM queues messages for a partner on one queue. Where a partner is using\nagent-level webhooks, it is important to bear in mind that the failure of one\nwebhook will impact delivery to other webhooks. Webhooks belonging to other\nagents will be called during the backoff period of a failed message.\nHowever, as failed messages queue up for retry, overall delivery rates will fall\nand other agents will be impacted.\n\nIt is important that developers understand this model and code accordingly - as\nfar as possible, accepting messages and queueing them for processing to\nminimize the opportunity of returning a failure.\n\n### Next steps\n\nOnce you configure your webhook, your agent can\n[receive messages](/business-communications/rcs-business-messaging/guides/build/messages/receive)\nfrom your\n[test devices](/business-communications/rcs-business-messaging/guides/build/test).\n[Send a message](/business-communications/rcs-business-messaging/guides/build/messages/send)\nto validate your setup."]]