<?php
namespace app\components;
use Yii;
class SmsSender {
private $username = 'zyd'; // API 帳號
private $password = '123456'; // API 密碼
private $gateway = 'https://sms.zyd.com/msgsend.ashx'; // 簡訊閘道
/**
* 發送簡訊
* @param string $mobile 手機號碼
* @param string $message 簡訊內容
* @return string|false 閘道回傳原始結果
*/
public function send($mobile, $message) {
// 內容編碼:UTF-8 → GB2312 → URLEncode
$encodedMessage = urlencode(mb_convert_encoding($message, 'gb2312', 'utf-8'));
$url = "{$this->gateway}?USERNAME={$this->username}"
. "&PASSWORD={$this->password}"
. "&MOBILE={$mobile}"
. "&CONTENT={$encodedMessage}"
. "&SEQ=1000";
$result = @file_get_contents($url);
if ($result === false) {
Yii::error("簡訊發送失敗: {$mobile}", __METHOD__);
return false;
}
Yii::info("簡訊發送結果: {$result}", __METHOD__);
return $result;
}
}
?>
<?php
// 方式一:直接實例化
$sms = new \app\components\SmsSender();
$result = $sms->send('0912345678', '您的驗證碼:123456,5分鐘內有效。');
// 方式二:註冊為 Application Component (config/web.php)
/*
'components' => [
'sms' => [
'class' => 'app\components\SmsSender',
'username' => 'your_api_user',
'password' => 'your_api_pass',
],
],
*/
// 然後任處使用:Yii::$app->sms->send($mobile, $message);
?>
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文變亂碼 | 閘道要求 GB2312/Big5,PHP 內部 UTF-8 | `mb_convert_encoding($msg, 'gb2312', 'utf-8')` |
| 特殊字元截斷 | URL 參數未編碼 | `urlencode()` 完整編碼 |
| 長簡訊分段 | 超過 70 字 (中文) 自動分段計費 | 預估長度、提醒用戶、記錄分段數 |
⚠️ 範例中帳號密碼寫死於程式碼,**生產環境務必存於環境變數或加密設定檔** (如 `params-local.php` 不納入版控),並限制 API 呼叫 IP 白名單。