> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SendGrid

> 使用 SendGrid 的邮件发送 API 根据 Dodo Payments 事件发送事务性电子邮件。

## 介绍

使用 SendGrid 自动发送支付确认、订阅更新和重要通知的事务性电子邮件。根据支付事件触发个性化电子邮件，使用动态内容和专业模板。

<Info>
  此集成需要具有 Mail Send 权限的 SendGrid API 密钥。
</Info>

## 开始使用

<Steps>
  <Step title="Open the Webhook Section">
    在你的 Dodo Payments 仪表盘中，导航到 <b>Webhooks → + 添加端点</b> 并展开集成下拉菜单。

    <Frame>
      <img src="https://mintcdn.com/dodopayments/slbAEdrLLwKHfaRf/images/integrations/sendgrid.png?fit=max&auto=format&n=slbAEdrLLwKHfaRf&q=85&s=bb13e15660cf9765d6501190d738525d" alt="添加端点和集成下拉菜单" style={{ maxHeight: '500px', width: 'auto' }} width="1682" height="944" data-path="images/integrations/sendgrid.png" />
    </Frame>
  </Step>

  <Step title="Select SendGrid">
    选择 <b>SendGrid</b> 集成卡片。
  </Step>

  <Step title="Enter API Key">
    在配置中提供你的 SendGrid API 密钥。
  </Step>

  <Step title="Configure Transformation">
    编辑转换代码以将电子邮件格式化为 SendGrid 的 Mail Send API 所需的格式。
  </Step>

  <Step title="Test & Create">
    使用示例负载进行测试，然后点击 <b>Create</b> 激活电子邮件发送。
  </Step>

  <Step title="Done!">
    🎉 付款事件现在将自动通过 SendGrid 触发事务性电子邮件。
  </Step>
</Steps>

## 转换代码示例

### 付款确认电子邮件

```javascript payment_confirmation.js icon="js" expandable theme={null}
function handler(webhook) {
  if (webhook.eventType === "payment.succeeded") {
    const p = webhook.payload.data;
    webhook.url = "https://api.sendgrid.com/v3/mail/send";
    webhook.payload = {
      personalizations: [
        {
          to: [{ email: p.customer.email }],
          dynamic_template_data: {
            customer_name: p.customer.name,
            payment_amount: (p.total_amount / 100).toFixed(2),
            payment_id: p.payment_id,
            payment_date: new Date(webhook.payload.timestamp).toLocaleDateString(),
            currency: p.currency || "USD"
          }
        }
      ],
      from: {
        email: "payments@yourdomain.com",
        name: "Your Company"
      },
      template_id: "d-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    };
  }
  return webhook;
}
```

### 订阅欢迎电子邮件

```javascript subscription_welcome.js icon="js" expandable theme={null}
function handler(webhook) {
  if (webhook.eventType === "subscription.active") {
    const s = webhook.payload.data;
    webhook.url = "https://api.sendgrid.com/v3/mail/send";
    webhook.payload = {
      personalizations: [
        {
          to: [{ email: s.customer.email }],
          dynamic_template_data: {
            customer_name: s.customer.name,
            subscription_id: s.subscription_id,
            product_name: s.product_id,
            amount: (s.recurring_pre_tax_amount / 100).toFixed(2),
            frequency: s.payment_frequency_interval,
            next_billing: new Date(s.next_billing_date).toLocaleDateString()
          }
        }
      ],
      from: {
        email: "welcome@yourdomain.com",
        name: "Your Company"
      },
      template_id: "d-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    };
  }
  return webhook;
}
```

### 付款失败通知

```javascript payment_failure.js icon="js" expandable theme={null}
function handler(webhook) {
  if (webhook.eventType === "payment.failed") {
    const p = webhook.payload.data;
    webhook.url = "https://api.sendgrid.com/v3/mail/send";
    webhook.payload = {
      personalizations: [
        {
          to: [{ email: p.customer.email }],
          dynamic_template_data: {
            customer_name: p.customer.name,
            payment_amount: (p.total_amount / 100).toFixed(2),
            error_message: p.error_message || "Payment processing failed",
            payment_id: p.payment_id,
            retry_link: `https://yourdomain.com/retry-payment/${p.payment_id}`
          }
        }
      ],
      from: {
        email: "support@yourdomain.com",
        name: "Your Company Support"
      },
      template_id: "d-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    };
  }
  return webhook;
}
```

## 提示

* 使用 SendGrid 动态模板以实现个性化内容
* 在模板变量中包含相关的支付数据
* 设置正确的发件地址和发件人名称
* 使用模板 ID 以保持电子邮件格式一致
* 包含退订链接以确保合规性

## 故障排除

<AccordionGroup>
  <Accordion title="Emails not being sent">
    * 验证 API 密钥是否具有 Mail Send 权限
    * 检查模板 ID 是否有效且处于启用状态
    * 确保收件人电子邮箱地址有效
    * 查看 SendGrid 的发送限制和配额
  </Accordion>

  <Accordion title="Transformation errors">
    * 验证 JSON 结构是否与 SendGrid API 格式一致
    * 检查所有必填字段是否存在
    * 确保模板数据变量格式正确
    * 确认发件人邮箱地址已在 SendGrid 中通过验证
  </Accordion>
</AccordionGroup>
