|
1 | 1 | # @team-plain/typescript-sdk |
2 | 2 |
|
3 | | -[Changelog]('./CHANGELOG.md') |
| 3 | +[Changelog](./CHANGELOG.md) |
4 | 4 |
|
5 | 5 | ## Plain Client |
6 | 6 |
|
@@ -104,16 +104,40 @@ Fallback error type when something unexpected happens. |
104 | 104 |
|
105 | 105 | ## Webhooks |
106 | 106 |
|
107 | | -This package also provides functionality to validate our [Webhook payloads](https://www.plain.com/docs/api-reference/webhooks). |
| 107 | +Plain signs the [webhooks](https://www.plain.com/docs/api-reference/webhooks) it sends to your endpoint, |
| 108 | +allowing you to validate that they were not sent by a third-party. You can read more about it [here](https://www.plain.com/docs/api-reference/request-signing). |
| 109 | +The SDK provides a convenient helper function to verify the signature, prevent replay attacks, and parse the payload to a typed object. |
108 | 110 |
|
109 | 111 | ```ts |
110 | | -import { parsePlainWebhook } from '@team-plain/typescript-sdk'; |
111 | | - |
112 | | -const payload = { ... }; |
113 | | - |
114 | | -if(parsePlainWebhook(payload)) { |
115 | | - // payload is now typed! |
116 | | - doYourThing(payload); |
| 112 | +import { |
| 113 | + PlainWebhookSignatureVerificationError, |
| 114 | + PlainWebhookVersionMismatchError, |
| 115 | + verifyPlainWebhook, |
| 116 | +} from '@team-plain/typescript-sdk'; |
| 117 | + |
| 118 | +// You must pass the raw request body, exactly as received from Plain, |
| 119 | +// this will not work with a parsed (i.e., JSON) request body. |
| 120 | +const payload = '...'; |
| 121 | + |
| 122 | +// The value of the `Plain-Request-Signature` header from the webhook request. |
| 123 | +const signature = '...'; |
| 124 | + |
| 125 | +// Plain Request Signature Secret. You can find this in Plain's settings. |
| 126 | +const secret = '...'; |
| 127 | + |
| 128 | +const webhookResult = verifyPlainWebhook(payload, signature, secret); |
| 129 | +if (webhookResult.error instanceof PlainWebhookSignatureVerificationError) { |
| 130 | + // Signature verification failed. |
| 131 | +} else if (webhookResult.error instanceof PlainWebhookVersionMismatchError) { |
| 132 | + // The SDK is not compatible with the received webhook version. |
| 133 | + // Consider updating the SDK and the webhook target to the latest version. |
| 134 | + // Consult the changelog or https://plain.com/docs/api-reference/webhooks/versions for more information. |
| 135 | +} else if (webhookResult.error) { |
| 136 | + // Unexpected error. Most likely due to an error in Plain's webhook server or a bug in the SDK. |
| 137 | + // Treat this as a 500 response from Plain. |
| 138 | + // We also recommend logging the error and sharing it with Plain's support team. |
| 139 | +} else { |
| 140 | + // webhookResult.data is now a typed object. |
117 | 141 | } |
118 | 142 | ``` |
119 | 143 |
|
|
0 commit comments