You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Twilio发送短信前检测号码是否被拉黑?PHP开发疑问

检测号码是否因STOP退订无法接收Twilio短信的正确方法

Lookups API确实无法获取退订状态,因为退订是收件人针对特定Twilio发件号码/短代码的操作,不属于号码本身的基础属性,而是归属于Twilio消息服务的订阅管理范畴。

你需要使用Twilio的Opt-out管理API来查询该状态,以下是具体实现:

方法1:查询特定发件号码的退订记录(适配你当前的旧版SDK)

如果你的短信是通过单个Twilio号码发送的,可直接调用Twilio REST API的退订查询端点,用现有旧版SDK实现如下:

require('twilio-php-master/Services/Twilio.php');

global $twilio_account_sid;
global $twilio_auth_token;
$target_number = "+xxxxxxxxxxxxx"; // 待检测的收件号码
$sender_number = "+yyyyyyyyyyyyy"; // 你的Twilio发件号码

$client = new Services_Twilio($twilio_account_sid, $twilio_auth_token);

try {
    // 查询收件人针对当前发件号码的退订状态
    $opt_out = $client->account->messages->opt_outs->get($target_number, array(
        'Sender' => $sender_number
    ));
    echo "该号码已退订,无法接收来自{$sender_number}的短信";
} catch (Services_Twilio_RestException $e) {
    // 404错误代表未找到退订记录,即号码未退订
    if ($e->getCode() == 404) {
        echo "该号码未退订,可以接收短信";
    } else {
        echo "查询出错:" . $e->getMessage();
    }
}

方法2:通过Messaging Service管理退订(推荐方案)

如果使用Twilio Messaging Service发送短信,可通过服务对应的Opt-outs资源查询:

require('twilio-php-master/Services/Twilio.php');

global $twilio_account_sid;
global $twilio_auth_token;
$target_number = "+xxxxxxxxxxxxx";
$messaging_service_sid = "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 你的Messaging Service SID

$client = new Services_Twilio($twilio_account_sid, $twilio_auth_token);

try {
    $opt_out = $client->account->messaging_services->get($messaging_service_sid)->opt_outs->get($target_number);
    echo "该号码已退订,无法接收此Messaging Service的短信";
} catch (Services_Twilio_RestException $e) {
    if ($e->getCode() == 404) {
        echo "该号码未退订";
    } else {
        echo "查询出错:" . $e->getMessage();
    }
}

补充说明

  • 退订状态是**收件人+发件方(号码/服务)**的组合属性,同一个收件人针对不同Twilio号码的退订状态可能不同。
  • 若不想主动查询,也可在发送短信时捕获错误:当收件人已退订时,Twilio会返回错误码21610,可据此判断状态。

内容的提问来源于stack exchange,提问作者Rafael Anschau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:37:26