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

# Gửi lại

> Gửi email giao dịch qua Resend khi các sự kiện Dodo Payments xảy ra, chẳng hạn như xác nhận thanh toán, chào mừng người đăng ký và thông báo thanh toán thất bại.

## Giới thiệu

Tích hợp Resend gửi email giao dịch qua Resend khi một sự kiện Dodo Payments xảy ra. Sử dụng tích hợp này để xác nhận thanh toán, chào mừng người đăng ký mới và thông báo cho khách hàng khi thanh toán thất bại, từ tên miền gửi email của riêng bạn.

<Info>
  Tích hợp này yêu cầu API key Resend có **Sending access** và một tên miền gửi email đã được xác minh trong Resend. Bạn cũng cần quyền truy cập vào **Developer → Webhooks** trong dashboard Dodo Payments.
</Info>

## Bắt đầu

<Steps>
  <Step title="Open the Webhook Section">
    Trong bảng điều khiển Dodo Payments, hãy đi tới **Developer → Webhooks** và nhấp vào **Add endpoint**.

    <Frame>
      <img src="https://mintcdn.com/dodopayments/DL_ADtkdH7ph5YST/images/integrations/resend.png?fit=max&auto=format&n=DL_ADtkdH7ph5YST&q=85&s=9968c4c48dca69a0eeffeffa0040b61d" alt="Add endpoint dialog with Resend selected in the Integration dropdown and the How to connect Resend steps" style={{ maxHeight: '500px', width: 'auto' }} width="1536" height="1428" data-path="images/integrations/resend.png" />
    </Frame>
  </Step>

  <Step title="Select Resend">
    Trong **Integration**, chọn **Resend**. Dashboard sẽ điền **Endpoint URL** và mã chuyển đổi cho Resend, đồng thời bảng **How to connect Resend** sẽ hiển thị các bước thiết lập.
  </Step>

  <Step title="Enter API Key">
    Trong Resend, mở [API Keys](https://resend.com/api-keys), nhấp vào **Create API Key** và cấp cho key quyền **Sending access**. Resend chỉ hiển thị key bắt đầu bằng `re_` một lần. Dán key đó vào **API key**. Dodo Payments gửi key này dưới dạng bearer token trong header `Authorization` của mọi request đến Resend.
  </Step>

  <Step title="Select Events">
    Trong **Subscribed events**, chỉ chọn các sự kiện mà mã chuyển đổi của bạn xử lý. Một sự kiện không được mã chuyển đổi thay đổi sẽ đến Resend theo định dạng Dodo Payments và bị Resend từ chối.
  </Step>

  <Step title="Configure Transformation">
    Trong **Transformation code**, chỉnh sửa handler để mỗi sự kiện đã đăng ký trở thành một email Resend. Bắt đầu với [các ví dụ](#transformation-code-examples).
  </Step>

  <Step title="Test & Create">
    Trong **Test this code**, chọn một loại sự kiện và nhấp vào **Simulate** để xem trước request gửi đến Resend. Sau đó nhấp vào **Create endpoint**.
  </Step>

  <Step title="Done">
    Dodo Payments giờ đây sẽ gửi email qua Resend cho mỗi sự kiện đã đăng ký. Để xem từng lần gửi và phản hồi của Resend, mở tab **Logs** trong **Developer → Webhooks**.
  </Step>
</Steps>

## Ví dụ về mã chuyển đổi

Mỗi handler đặt `webhook.url` thành endpoint gửi email của Resend và thay `webhook.payload` bằng email. Số tiền của Dodo Payments được tính theo đơn vị tiền tệ nhỏ nhất, vì vậy các ví dụ chia cho 100 và hiển thị mã tiền tệ. Đối với các loại tiền tệ không có chữ số thập phân như JPY và KRW, hãy sử dụng nguyên giá trị số tiền.

### Email xác nhận thanh toán

Gửi biên lai khi thanh toán thành công (`payment.succeeded`):

```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.resend.com/emails";
    webhook.payload = {
      from: "payments@yourdomain.com",
      to: [p.customer.email],
      subject: "Payment Confirmation - " + (p.total_amount / 100).toFixed(2) + " " + p.currency,
      html: `
        <h2>Payment Successful!</h2>
        <p>Hi ${p.customer.name},</p>
        <p>Your payment of ${(p.total_amount / 100).toFixed(2)} ${p.currency} has been processed successfully.</p>
        <ul>
          <li><strong>Payment ID:</strong> ${p.payment_id}</li>
          <li><strong>Amount:</strong> ${(p.total_amount / 100).toFixed(2)} ${p.currency}</li>
          <li><strong>Date:</strong> ${new Date(webhook.payload.timestamp).toLocaleDateString()}</li>
          <li><strong>Method:</strong> ${p.payment_method || "Unknown"}</li>
        </ul>
        <p>Thank you for your business!</p>
      `,
      text: `Payment Successful! Your payment of ${(p.total_amount / 100).toFixed(2)} ${p.currency} has been processed. Payment ID: ${p.payment_id}`
    };
  }
  return webhook;
}
```

### Email chào mừng người đăng ký

Chào mừng khách hàng khi gói đăng ký chuyển sang trạng thái hoạt động (`subscription.active`):

```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.resend.com/emails";
    webhook.payload = {
      from: "welcome@yourdomain.com",
      to: [s.customer.email],
      subject: "Welcome to Your Subscription!",
      html: `
        <h2>Welcome to Your Subscription!</h2>
        <p>Hi ${s.customer.name},</p>
        <p>Your subscription has been activated successfully.</p>
        <ul>
          <li><strong>Subscription ID:</strong> ${s.subscription_id}</li>
          <li><strong>Product:</strong> ${s.product_id}</li>
          <li><strong>Amount:</strong> ${(s.recurring_pre_tax_amount / 100).toFixed(2)} ${s.currency}/${s.payment_frequency_interval}</li>
          <li><strong>Next Billing:</strong> ${new Date(s.next_billing_date).toLocaleDateString()}</li>
        </ul>
        <p>You can manage your subscription anytime from your account dashboard.</p>
      `,
      text: `Welcome! Your subscription is now active. Amount: ${(s.recurring_pre_tax_amount / 100).toFixed(2)} ${s.currency}/${s.payment_frequency_interval}`
    };
  }
  return webhook;
}
```

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

Yêu cầu khách hàng cập nhật phương thức thanh toán khi thanh toán thất bại (`payment.failed`):

```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.resend.com/emails";
    webhook.payload = {
      from: "support@yourdomain.com",
      to: [p.customer.email],
      subject: "Payment Failed - Action Required",
      html: `
        <h2>Payment Failed</h2>
        <p>Hi ${p.customer.name},</p>
        <p>We were unable to process your payment of ${(p.total_amount / 100).toFixed(2)} ${p.currency}.</p>
        <ul>
          <li><strong>Payment ID:</strong> ${p.payment_id}</li>
          <li><strong>Amount:</strong> ${(p.total_amount / 100).toFixed(2)} ${p.currency}</li>
          <li><strong>Error:</strong> ${p.error_message || "Payment processing failed"}</li>
        </ul>
        <p>Please update your payment method or contact support for assistance.</p>
        <a href="https://yourdomain.com/update-payment">Update Payment Method</a>
      `,
      text: `Payment Failed: We couldn't process your ${(p.total_amount / 100).toFixed(2)} ${p.currency} payment. Please update your payment method.`
    };
  }
  return webhook;
}
```

## Mẹo

* Gửi email từ tên miền bạn đã xác minh trong Resend để cải thiện khả năng gửi email thành công.
* Bao gồm cả phiên bản `html` và `text` của mỗi email.
* Cá nhân hóa nội dung bằng dữ liệu khách hàng từ payload, chẳng hạn như `customer.name`.
* Viết tiêu đề email nêu rõ kết quả hoặc hành động cần thực hiện.
* Bao gồm liên kết hủy đăng ký trong mọi email có nội dung tiếp thị.
* Xem trước từng template bằng **Simulate** trước khi tạo endpoint.
* Để bỏ qua một sự kiện trong code, đặt `webhook.cancel = true` trước khi trả về webhook. Logs ghi nhận lần gửi bị bỏ qua là thành công.

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

<AccordionGroup>
  <Accordion title="Emails Not Being Sent">
    * Kiểm tra API key có chính xác, đang hoạt động và có quyền **Sending access** hay không. Để thay thế key, chỉnh sửa endpoint và dán key mới vào **API key**.
    * Kiểm tra tên miền người gửi đã được xác minh trong Resend.
    * Kiểm tra địa chỉ email người nhận có hợp lệ hay không.
    * Kiểm tra giới hạn và hạn ngạch gửi email của Resend đối với gói của bạn.
    * Mở tab **Logs** trong **Developer → Webhooks** và đọc phản hồi của Resend đối với lần gửi thất bại.
  </Accordion>

  <Accordion title="Transformation Errors">
    * Kiểm tra payload có khớp với định dạng send-email của Resend hay không. Resend yêu cầu `from`, `to` và `subject`.
    * Kiểm tra mọi sự kiện mà code của bạn xử lý đều đặt tất cả các trường bắt buộc.
    * Kiểm tra giá trị `html` có phải là HTML đúng định dạng hay không.
    * Kiểm tra địa chỉ `from` sử dụng tên miền đã được xác minh trong Resend.
  </Accordion>
</AccordionGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.