动态

详情 返回 返回

PHP實現國際短信驗證碼發送接口的完整指南 - 动态 详情

PHP 快速接入國際短信 API 接口:實現國際驗證碼短信發送

本文將詳細介紹如何使用 PHP 語言快速接入國際短信 API 接口,實現國際驗證碼短信的發送功能,拿來就能用,10 分鐘就能完成接入

一、主要提供兩大功能

  • 單條短信發送(支持黑名單等攔截錯誤實時返回)
  • 獲取狀態報告(每條短信狀態僅可獲取一次)

二、環境要求

  • PHP 5.6 或更高版本
  • 開啓 cURL 擴展
  • 有效的 SP_ID 和密鑰(開發者中心查看)

三、完整 PHP 代碼實現

以下是完整的 PHP 示例代碼,只需替換配置參數即可使用:

<?php
/**
 * 國際短信接口Demo
 * 適用於3yit.com的短信API
 * 只需替換下面的配置參數即可使用
 */
 
class InternationalSMS {
    // ==================== 配置區域 ====================
    private $sp_id = '908452'; // 替換為您的SP_ID
    private $raw_password = 'your_raw_password'; // 替換為您的原始密碼
    private $api_send_url = 'https://api.3yit.com/api/send-sms-single';
    private $api_report_url = 'https://api.3yit.com/api/report';
    // ==================== 配置結束 ====================
    
    private $password;
    
    public function __construct() {
        // 自動將密碼轉換為MD5格式
        $this->password = md5($this->raw_password);
    }
    
    /**
     * 發送單條國際驗證碼短信
     * @param string $mobile 國際手機號(格式:國家代碼+號碼,如639257890123)
     * @param string $message 短信內容
     * @param string $ext 擴展號(可選)
     * @return array 返回結果
     */
    public function sendVerificationCode($mobile, $message, $ext = '') {
        // 準備請求參數
        $params = [
            'sp_id' => $this->sp_id,
            'mobile' => $mobile,
            'content' => $message,
            'password' => $this->password,
            'ext' => $ext
        ];
        
        // 發送POST請求
        $result = $this->httpPost($this->api_send_url, $params);
        
        // 解析返回的JSON
        $response = json_decode($result, true);
        
        if (!$response) {
            return [
                'success' => false,
                'message' => 'API響應解析失敗',
                'raw_response' => $result
            ];
        }
        
        // 判斷是否發送成功
        if ($response['code'] == 0) {
            return [
                'success' => true,
                'message' => '短信發送成功',
                'msg_id' => $response['msg_id'],
                'response' => $response
            ];
        } else {
            return [
                'success' => false,
                'message' => $this->getErrorMessage($response['code'], isset($response['data']) ? $response['data'] : ''),
                'error_code' => $response['code'],
                'response' => $response
            ];
        }
    }
    
    /**
     * 獲取狀態報告
     * @return array 返回狀態報告數據
     */
    public function getReport() {
        // 準備請求參數
        $params = [
            'sp_id' => $this->sp_id,
            'password' => $this->password
        ];
        
        // 構建查詢字符串
        $queryString = http_build_query($params);
        $url = $this->api_report_url . '?' . $queryString;
        
        // 發送GET請求
        $result = $this->httpGet($url);
        
        // 解析返回的JSON
        $response = json_decode($result, true);
        
        if (!$response) {
            return [
                'success' => false,
                'message' => 'API響應解析失敗',
                'raw_response' => $result
            ];
        }
        
        // 判斷是否獲取成功
        if ($response['code'] == 0) {
            $reports = [];
            if (!empty($response['data'])) {
                // 解析多條報告數據
                $reportList = explode('|', $response['data']);
                foreach ($reportList as $report) {
                    $fields = explode(',', $report);
                    if (count($fields) >= 5) {
                        $reports[] = [
                            'ext' => $fields[0],
                            'msg_id' => $fields[1],
                            'mobile' => $fields[2],
                            'status' => $fields[3],
                            'time' => $fields[4],
                            'price' => isset($fields[5]) ? $fields[5] : ''
                        ];
                    }
                }
            }
            
            return [
                'success' => true,
                'message' => '獲取狀態報告成功',
                'reports' => $reports,
                'response' => $response
            ];
        } else {
            return [
                'success' => false,
                'message' => $this->getErrorMessage($response['code']),
                'error_code' => $response['code'],
                'response' => $response
            ];
        }
    }
    
    /**
     * 發送HTTP POST請求
     * @param string $url 請求地址
     * @param array $params 請求參數
     * @return string 響應內容
     */
    private function httpPost($url, $params) {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
    
    /**
     * 發送HTTP GET請求
     * @param string $url 請求地址
     * @return string 響應內容
     */
    private function httpGet($url) {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
    
    /**
     * 獲取錯誤信息
     * @param int $code 錯誤碼
     * @param string $data 錯誤數據
     * @return string 錯誤描述
     */
    private function getErrorMessage($code, $data = '') {
        $errorMessages = [
            10000 => '服務出錯,請稍後再試',
            10001 => '參數錯誤,請確認',
            10008 => '賬號被鎖定,請聯繫管理員確認',
            10011 => '餘額不足,請儘快充值',
            10100 => '簽名校驗失敗',
            10101 => '您的ip不在白名單內,請確認',
            10102 => '密碼錯誤,請確認',
            10200 => '產品sp_id必須填寫',
            10201 => '手機號必須填寫',
            10202 => '短信內容必須填寫',
            10203 => '發送時間格式必須為UNIX時間戳',
            10208 => '短信進攔截,具體原因參考data字段',
            10209 => '觸發防刷,請調整配置'
        ];
        
        $dataMessages = [
            'WL:MBLJ' => '短信內容匹配到了模板,並且此模板類型是攔截',
            'WL:MBSH' => '命中審核模板',
            'WL:NMLJ' => '短信內容沒有匹配到模板,並且用户的模板審核方式是未匹配到就進攔截',
            'WL:NMSH' => '短信內容沒有匹配到模板,並且用户的模板審核方式是未匹配到就進審核',
            'WL:KHLJ' => '命中空號,進攔截',
            'WL:QHLJ' => '命中用户簽名黑名單,進攔截',
            'WL:SHLJ' => '命中用户SPID黑名單,進攔截',
            'WL:CHLJ' => '命中系統產品黑名單,進攔截',
            'WL:CWHM' => '錯誤號碼',
            'WL:QWBB' => '簽名未報備,進攔截',
            'WL:MQM' => '需要簽名但沒有,進攔截',
            'WL:CS' => '超過限速了',
            'WL:ZJLJ' => '不匹配任何模板,直接攔截',
            'WL:CMT' => '產品未配置相應通道,進攔截',
            'WL:CDQC' => '通道不支持該地區發送,進攔截',
            'WL:CGMT' => '產品通道池中沒有相應通道,進攔截',
            'WL:CNH' => '所選的通道不健康,進攔截',
            'WL:TCLJ' => '不在發送時間段,進攔截',
            'WL:TCSH' => '不在發送時間段,進審核',
            'WL:CPL' => '超頻限制'
        ];
        
        $message = isset($errorMessages[$code]) ? $errorMessages[$code] : "未知錯誤 (代碼: {$code})";
        
        // 如果是攔截錯誤,添加詳細原因
        if ($code == 10208 && !empty($data) && isset($dataMessages[$data])) {
            $message .= ': ' . $dataMessages[$data];
        }
        
        return $message;
    }
}
 
// ==================== 使用示例 ====================
 
// 創建短信實例
$sms = new InternationalSMS();
 
// 示例1:發送驗證碼短信
$mobile = '639257890123'; // 國際手機號(菲律賓示例)
$verificationCode = rand(1000, 9999); // 生成隨機驗證碼
$message = "Your verification code is {$verificationCode}. Please use it within 10 minutes.";
 
$result = $sms->sendVerificationCode($mobile, $message);
 
if ($result['success']) {
    echo "短信發送成功!消息ID: " . $result['msg_id'] . "\n";
    // 這裏應該將msg_id保存到數據庫,與用户關聯
} else {
    echo "短信發送失敗: " . $result['message'] . "\n";
}
 
// 示例2:獲取狀態報告
// $reportResult = $sms->getReport();
// if ($reportResult['success']) {
//     echo "獲取到 " . count($reportResult['reports']) . " 條狀態報告\n";
//     foreach ($reportResult['reports'] as $report) {
//         echo "手機號: {$report['mobile']}, 狀態: {$report['status']}, 時間: {$report['time']}\n";
//     }
// } else {
//     echo "獲取狀態報告失敗: " . $reportResult['message'] . "\n";
// }
 
?>

879ed07f213c41f4b933b963d5cdd3bb

四、使用説明

  1. 配置參數
    • 將$sp_id替換為您的實際 SP_ID
    • 將$raw_password替換為您的原始密碼
  2. 發送短信
    • 調用sendVerificationCode方法,傳入國際手機號和短信內容
    • 國際手機號格式:國家代碼 + 號碼(如菲律賓:639257890123)
  3. 獲取狀態報告
    • 調用getReport方法獲取短信發送狀態
  4. 錯誤處理
    • 代碼已包含完整的錯誤碼解析功能
    • 發送失敗時會返回詳細的錯誤信息

五、注意事項

  • 確保服務器已開啓 cURL 擴展
  • 國際手機號不需要添加 "+" 前綴
  • 每條短信的狀態報告只能獲取一次,獲取後需要本地存儲

這個 Demo 提供了完整的功能實現和錯誤處理,下載後只需替換配置參數即可使用。

Add a new 评论

Some HTML is okay.