Twilio Advanced Opt-Out 配置、自定义 STOP/START 回复内容,并实现 Webhook 处理逻辑

第一步:在 Twilio Console 中启用 Advanced Opt-Out

操作步骤:

  1. 登录 Twilio Console

  2. 左侧导航点击 Messaging > Services(前提是你使用 Messaging Service。若用单个号码,则点击 Phone Numbers)

  3. 选择你的 Messaging Service
    在这里插入图片描述

在这里插入图片描述

  1. 点击 “Opt-out Management” 或 “Compliance” 标签页

  2. 找到 Advanced Opt-Out 设置

  3. 启用它,填写以下内容:

自定义内容填写建议:

  1. Opt-out keywords: STOP, CANCEL, UNSUBSCRIBE, QUIT

  2. Opt-out message:

You have been unsubscribed from notifications. Reply START to re-subscribe.
  1. Re-subscribe keywords: START, UNSTOP

  2. Re-subscribe message:

You have been re-subscribed to notifications.
  1. 开启 “Forward opt-out and opt-in messages to your webhook”

  2. 然后保存设置 ✅

第二步:Webhook 服务端处理 STOP/START 消息

Twilio 会将短信内容(包括 STOP/START)发送到你配置的 Webhook URL。你可以根据关键词记录退订或重新订阅。

数据库设计(MySQL 示例)

CREATE TABLE sms_unsubscribe (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  phone_number VARCHAR(20) NOT NULL UNIQUE,
  unsubscribed BOOLEAN NOT NULL DEFAULT TRUE,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Java(Spring Boot)Webhook 示例代码

@PostMapping("/sms/webhook")
public ResponseEntity<String> receiveSms(@RequestParam("From") String from,
                                         @RequestParam("Body") String body) {
    String phone = from.trim();
    String content = body.trim().toUpperCase();

    if (List.of("STOP", "CANCEL", "UNSUBSCRIBE", "QUIT").contains(content)) {
        smsService.unsubscribe(phone);
    } else if (List.of("START", "UNSTOP").contains(content)) {
        smsService.resubscribe(phone);
    }

    // Twilio 需要返回 TwiML,即使什么也不发
    return ResponseEntity.ok("<Response></Response>");
}

Service 逻辑示例

@Service
public class SmsService {

    @Autowired
    private SmsUnsubscribeRepository repo;

    public void unsubscribe(String phone) {
        repo.save(new SmsUnsubscribe(phone, true));
    }

    public void resubscribe(String phone) {
        repo.save(new SmsUnsubscribe(phone, false));
    }

}

Postman 测试案例

URL: POST http://your-server.com/sms/webhook
Content-Type: application/x-www-form-urlencoded
Body 示例:

在这里插入图片描述

第三步(可选):阻止发送短信给退订用户

在你发短信前检查用户是否退订:

public boolean canSendMessage(String phone) {
    return !repo.findByPhoneNumber(phone)
                .map(SmsUnsubscribe::isUnsubscribed)
                .orElse(false);
}

总结

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值