> ## 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

> Gửi email giao dịch dựa trên các sự kiện Dodo Payments bằng cách sử dụng API Gửi Mail của SendGrid.

## Giới thiệu

Tự động gửi email giao dịch cho xác nhận thanh toán, cập nhật đăng ký và thông báo quan trọng bằng cách sử dụng SendGrid. Kích hoạt email cá nhân hóa dựa trên các sự kiện thanh toán với nội dung động và mẫu chuyên nghiệp.

<Info>
  Việc tích hợp này yêu cầu một SendGrid API Key với quyền gửi mail (Mail Send).
</Info>

## Bắt đầu

<Steps>
  <Step title="Open the Webhook Section">
    Trong bảng điều khiển Dodo Payments của bạn, điều hướng đến <b>Webhooks → + Thêm Endpoint</b> và mở rộng danh sách tích hợp.

    <Frame>
      <img src="https://mintcdn.com/dodopayments/slbAEdrLLwKHfaRf/images/integrations/sendgrid.png?fit=max&auto=format&n=slbAEdrLLwKHfaRf&q=85&s=bb13e15660cf9765d6501190d738525d" alt="Thêm Endpoint và danh sách tích hợp" style={{ maxHeight: '500px', width: 'auto' }} width="1682" height="944" data-path="images/integrations/sendgrid.png" />
    </Frame>
  </Step>

  <Step title="Select SendGrid">
    Chọn thẻ tích hợp <b>SendGrid</b>.
  </Step>

  <Step title="Enter API Key">
    Cung cấp SendGrid API Key trong phần cấu hình.
  </Step>

  <Step title="Configure Transformation">
    Chỉnh sửa mã chuyển đổi để định dạng email phù hợp với SendGrid Mail Send API.
  </Step>

  <Step title="Test & Create">
    Kiểm tra bằng các payload mẫu và nhấp <b>Create</b> để kích hoạt việc gửi email.
  </Step>

  <Step title="Done!">
    🎉 Các sự kiện thanh toán giờ sẽ tự động kích hoạt các email giao dịch thông qua SendGrid.
  </Step>
</Steps>

## Ví dụ Mã Biến đổi

### Email Xác nhận Thanh toán

```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;
}
```

### Email Chào mừng Đăng ký

```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;
}
```

### Thông báo Thất bại Thanh toán

```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;
}
```

## Mẹo

* Sử dụng mẫu động của SendGrid cho nội dung cá nhân hóa
* Bao gồm dữ liệu thanh toán liên quan trong các biến mẫu
* Đặt địa chỉ gửi và tên người gửi phù hợp
* Sử dụng ID mẫu để định dạng email nhất quán
* Bao gồm liên kết hủy đăng ký để tuân thủ

## Khắc phục sự cố

<AccordionGroup>
  <Accordion title="Emails not being sent">
    * Xác minh API Key có quyền Mail Send
    * Kiểm tra xem các ID mẫu có hợp lệ và đang hoạt động không
    * Đảm bảo địa chỉ email người nhận hợp lệ
    * Xem lại giới hạn và hạn ngạch gửi của SendGrid
  </Accordion>

  <Accordion title="Transformation errors">
    * Xác thực cấu trúc JSON phù hợp với định dạng API của SendGrid
    * Kiểm tra tất cả các trường bắt buộc đều có mặt
    * Đảm bảo các biến dữ liệu mẫu được định dạng đúng
    * Xác minh địa chỉ email người gửi đã được SendGrid xác thực
  </Accordion>
</AccordionGroup>
