- 确保你已经有一个在Sendgrid注册的邮箱账号
- 在Sendgrid中启用事件Webhook,它将发送通知到你网站的URL
- 登陆Sendgrid并创建API Key,用于向Sendgrid发送API请求
- 生成RSA密钥,用于OAuth 2的验证流程
- 在你的应用程序中,用你的OAuth 2凭证(如Access Token)向Sendgrid API发送验证请求。发送成功后,将接口的Response Body的JWT(JSON Web Token)拿出来存储在你的应用程序中作为验证凭证。
- 下面是一个使用Node.js的代码示例:
const jwkToPem = require('jwk-to-pem');
const jwt = require('jsonwebtoken');
const fetch = require('node-fetch');
// 你的Sendgrid API Key
const apiKey = 'YOUR-API-KEY-HERE';
// 从Sendgrid中获取JWK,用于生成RSA秘钥
fetch('https://api.sendgrid.com/v3/user/webhooks/event/settings')
.then((res) => res.json())
.then((data) => {
const jwks = data.jwks;
// 从JWK中生成RSA密钥
const rsaKey = jwkToPem(jwks.keys[0]);
// 构建JWT的Payload
const payload = {
iss: 'sendgrid',
sub: 'test@example.com',
exp: Math.floor(Date.now() / 1000) + 60 * 10,
iat: Math.floor(Date.now() / 1000),
};
// 生成JWT
const token = jwt.sign(payload, rsaKey, { algorithm: 'RS256' });
// 发送验证请求
fetch('https://api.sendgrid.com/v3/user/webhooks/event/settings/test', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});
});