不知不覺轉到PHP開發這個行業一年多了,一路走來實屬不易,感慨一下,開始正題
短信接入SDK其實說難不難說,說簡單很簡單,只要你能喫的準他的套路就沒有問題了
第一步,找到第三方短信SDK找到客服,要測試的短信,一般情況下只會給到10條左右測試短信(不排除有200條不可變動短信)
第二步,找到官方文檔,看需要什麼參數,返回什麼參數等等
第三步,打開編輯器,廢話太多,直接上代碼了
SendSMS.php
<?php
/**
* Created by Zend studio.
* name: Poison
*/
$aa = include_once 'conf.php';
include_once 'Tools.php';
$randnum = rand(1000,9999);//這個可以自己確定,就是一個隨機數
$send_arr = array( //將需要的參數放入數組中
'account' =>$aa['SMS_ACCOUNT'] ,
'password' => $aa['SMS_PWD'],
'content' =>str_replace('$code$',$randnum,$aa['SMS_WORD']),
'mobile' =>'15609220575'
);
$returnStr = invoke_fraud_api($aa['SMS_URL'],$send_arr);//調用下面的方法,下面的方法不不要動,直接使用就好了
$ins = new Tools();//調用Tools
$ins -> decodeXml($returnStr);//此方法用來解析返回來的XML文件
$code = $ins -> getXmlData('code');//取出返回值
if($code === '2'){//這個短信返回2爲發送成功,返回給前端
echo json_encode(array('result' => 1));
}else{
echo json_encode(array('result' => 2,'reason' => $ins -> getXmlData('msg') ));
}
function invoke_fraud_api($url,array $params, $isPost = true,$timeout = 5000, $connection_timeout = 5000) {
$api_url = $url;
if($isPost){
$options['CURLOPT_POST'] = 1;
}
$options = array(
CURLOPT_URL => $api_url, // 請求URL
CURLOPT_RETURNTRANSFER => 1, // 獲取請求結果
// -----------請確保啓用以下兩行配置------------
CURLOPT_SSL_VERIFYPEER => 1, // 驗證證書
CURLOPT_SSL_VERIFYHOST => 2, // 驗證主機名
// -----------否則會存在被竊聽的風險------------
CURLOPT_POSTFIELDS => http_build_query($params) // 注入接口參數
);
if (defined("CURLOPT_TIMEOUT_MS")) {
$options[CURLOPT_NOSIGNAL] = 1;
$options[CURLOPT_TIMEOUT_MS] = $timeout;
} else {
$options[CURLOPT_TIMEOUT] = ceil($timeout / 1000);
}
if (defined("CURLOPT_CONNECTTIMEOUT_MS")) {
$options[CURLOPT_CONNECTTIMEOUT_MS] = $connection_timeout;
} else {
$options[CURLOPT_CONNECTTIMEOUT] = ceil($connection_timeout / 1000);
}
$ch = curl_init();
$cacert = getcwd() . '/ca-bundle.crt';
curl_setopt ($ch, CURLOPT_CAINFO, $cacert);
curl_setopt_array($ch, $options);
if(!($response = curl_exec($ch))) {
// 錯誤處理,按照同盾接口格式fake調用結果
return array(
"success" => "false",
"reason_code" => "000:調用API時發生錯誤[".curl_error($ch)."]"
);
}
curl_close($ch);
return $response;
}
Tools()//這個是用來json、xml發送和解析的工具類
public function decodeJson($str){
$this -> jsonResult = (array)json_decode($str);
}
public function getJsonData($key){
return $this -> jsonResult[$key];
}
public function encodeXml($parent,$arr){
$xml = new DOMDocument('1.0','utf-8');
$parentObj = $xml -> createElement($parent);
$xml -> appendChild($parentObj);
foreach($arr as $key => $val){
$obj = $xml -> createElement($key,$val);
$parentObj -> appendChild($obj);
}
$str = $xml -> saveXML();
if($parent === 'xml'){
$arr = explode('?>',$str);
return end($arr);
}else{
return $str;
}
}
public function decodeXml($str){
$xml = simplexml_load_string($str);
$this -> xmlResult = (array)$xml;
}
public function getXmlData($key){
return (string)$this -> xmlResult[$key];
}
}
最後放入一個最最關鍵的文件,ca-bundle.crt 放在更目錄下