在開發(fā)網(wǎng)站、app等項(xiàng)目中,經(jīng)常需要接入短信接口來實(shí)現(xiàn)各種短信發(fā)送功能,常見的應(yīng)用場景如用戶注冊登錄短信驗(yàn)證、會(huì)員通知提醒等,一般短信接口對接到項(xiàng)目中的流程如下:
下面是php開發(fā)語言短信接口接入到項(xiàng)目中的demo示例:
<?php
// ① 該代碼僅供接入動(dòng)力思維樂信短信接口參考使用,客戶可根據(jù)實(shí)際需要自行編寫;
// ② 支持發(fā)送驗(yàn)證碼短信、觸發(fā)通知短信等;
// ③ 測試驗(yàn)證碼短信、通知短信,請用默認(rèn)的測試模板,默認(rèn)模板詳見接口文檔。
class SendUtility {
private $_config = array();
/**
* 獲取相關(guān)配置
* Config.php文件中的樂信用戶名、密碼、簽名
*/
public __construct($config) {
$this->_config = $config;
}
/**
* 拼接請求參數(shù)
*/
function BuildContent($AimMobiles, $Content) {
$str = "accName=" . urlencode($this->_config["UserName"]);
$str .= "&accPwd=" . urlencode(strtoupper(md5($this->_config["Password"])));
$str .= "&aimcodes=" . urlencode($AimMobiles);
$str .= "&content=" . urlencode($Content . $this->_config["Signature"]);
return $str;
}
/**
* 短信發(fā)送
* @param $AimMobiles 下行手機(jī)號
* @param $Content 短信內(nèi)容
*/
function Send($AimMobiles, $Content) {
$content = $this->BuildContent($AimMobiles, $Content);
$counter = 0;
while ($counter < count($this->_config["Addresses"])) {
$opts = array('http' => array("method" => "POST", "timeout" => $this->_config["HttpTimeout"],
"header" => "Content-type: application/x-www-form-urlencoded", "content" => $content));
$message = file_get_contents($this->_config["Addresses"][$counter] . "/send", false,
stream_context_create($opts));
if ($message == false) $counter++;
else break;
}
if ($message == false) return "發(fā)送失敗";
$RtnString = explode(";", $message);
if ($RtnString[0] != "1") return $RtnString[1];
return $RtnString[0];
}
/**
* 余額查詢
* @param $accName 用戶名
* @param $accPwd 密碼
*/
function Query() {
$content = "accName=" . urlencode($this->_config["UserName"]);
$content .= "&accPwd=" . urlencode(strtoupper(md5($this->_config["Password"])));
$opts = array('http' => array("method" => "POST",
"header" => "Content-type: application/x-www-form-urlencoded",
"content" => $content));
$message = file_get_contents($this->_config["Addresses"][0] . "/qryBalance", false,
stream_context_create($opts));
if ($message == false) return "查詢失敗";
$RtnString = explode(";", $message);
if ($RtnString[0] != "1") return $RtnString[1];
return $RtnString[2];
}
}
php>