卓望的短信發送。PHP格式。都要不習慣用xml傳輸數據格式了
標簽: <無>
1. [代碼][PHP]代碼
<?php class Sms { private $userId = 'XXXXX'; private $password = 'XXXXXX'; private $templateId = 'XXXXXX'; /** * @var string 短信服務器地址 */ private $server_uri = 'XXXXXX'; private $port = 'XXXXXX'; /** * 發送短信 * @param $message 信息內容 * @param $mobile 手機號碼 * @param string $signature 簽名 * @return bool 成功返回true, 網絡請求失敗返回false, 其他返回失敗編碼 */ public function sendOneMsg($message, $mobile, $signature='demo') { $xml_content = $this->createXmlContent($message, $mobile, $signature); $xml = $this->sendHttpRequest(trim($xml_content)); if(! $xml) { return false; // 網絡請求失敗 } // 解析返回的編碼 $res = simplexml_load_string($xml); if($res->retCode == 1000) { return true; } return $res->retCode; } /** * 創建 xml內容 * @param $message 信息 * @param $mobile 要發送的手機號碼 * @param $signature 簽名 * @return string */ private function createXmlContent($message, $mobile, $signature) { $data = array( 'userId' => $this->userId, // 賬號 'password' => $this->password, // 小寫的md5後的用戶密碼 'templateId' => $this->templateId, // 模板id 'phone' => $mobile, 'port' => $this->port, 'data' => $message, 'signature' => $signature, ); // 設置xml版本和編碼 $dom = new \DOMDocument('1.0', 'UTF-8'); // 創建根節點 $request = $dom->createElement('request'); $dom->appendChild($request); foreach($data as $key => $val) { // 創建元素 $key = $dom->createElement($key); $request->appendChild($key); // 創建元素值 $text = $dom->createTextNode($val); $key->appendChild($text); } return $dom->saveXML(); } /** * 發送http請求 * @param $xml_content * @return mixed */ private function sendHttpRequest($xml_content) { $now = time(); $headers[] = 'Content-Type:text/xml'; $headers[] = 'Content-Length:' . strlen($xml_content); $headers[] = 'Cmd:mt'; $headers[] = 'TS:'. $now; $headers[] = 'Authorization:' . strtoupper(md5($xml_content. $now . $this->password)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->server_uri); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_content); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $res = curl_exec($ch); curl_close($ch); //header('Content-Type:text/html; charset=utf-8'); return $res; } }
以上所述就是本文的全部內容了,希望大家能夠喜歡。