|
class Wechat {
/**
* 推送過來的資料或響應資料
* @var array
*/
private $data = array();
/**
* 構造方法,用於執行個體化SDK
* @param string $token 開放平台設定的TOKEN
*/
public function __construct($token) {
$this->auth($token) || exit;
if(!empty($_GET['echostr'])){
exit($_GET['echostr']);
} else {
try
{
$xml = file_get_contents("php://input");
$xml = new SimpleXMLElement($xml);
$xml || exit;
foreach ($xml as $key => $value) {
$this->data[$key] = strval($value);
}
}catch(Exception $e){
}
}
}
/**
* 擷取推送的資料
* @return array 轉換為數組後的資料
*/
public function request(){
return $this->data;
}
/**
* * 響應發送的資訊(自動回複)
* @param string $to 接收使用者名稱
* @param string $from 寄件者使用者名稱
* @param array $content 回複資訊,文本資訊為string類型
* @param string $type 訊息類型
* @param string $flag 是否新標剛接受到的資訊
* @return string XML字串
*/
public function response($content, $type = 'text', $flag = 0){
/* 基礎資料 */
$this->data = array(
'ToUserName' => $this->data['FromUserName'],
'FromUserName' => $this->data['ToUserName'],
'CreateTime' => time(),
'MsgType' => $type,
);
/* 添加類型資料 */
$this->$type($content);
/* 添加狀態 */
$this->data['FuncFlag'] = $flag;
/* 轉換資料為XML */
$xml = new SimpleXMLElement('');
$this->data2xml($xml, $this->data);
exit($xml->asXML());
}
/**
* 回複文本資訊
* @param string $content 要回複的資訊
*/
private function text($content){
$this->data['Content'] = $content;
}
/**
* 回複音樂資訊
* @param string $content 要回複的音樂
*/
private function music($music){
list(
$music['Title'],
$music['Description'],
$music['MusicUrl'],
$music['HQMusicUrl']
) = $music;
$this->data['Music'] = $music;
}
/**
* 回複圖文資訊
* @param string $news 要回複的圖文內容
*/
private function news($news){
$articles = array();
foreach ($news as $key => $value) {
list(
$articles[$key]['Title'],
$articles[$key]['Description'],
$articles[$key]['PicUrl'],
$articles[$key]['Url']
) = $value;
if($key >= 9) { break; } //最多隻允許10調新聞
}
$this->data['ArticleCount'] = count($articles);
$this->data['Articles'] = $articles;
}
/**
* 資料XML編碼
* @param object $xml XML對象
* @param mixed $data 資料
* @param string $item 數字索引時的節點名稱
* @return string
*/
private function data2xml($xml, $data, $item = 'item') {
foreach ($data as $key => $value) {
/* 指定預設的數字key */
is_numeric($key) && $key = $item;
/* 添加子項目 */
if(is_array($value) || is_object($value)){
$child = $xml->addChild($key);
$this->data2xml($child, $value, $item);
} else {
if(is_numeric($value)){
$child = $xml->addChild($key, $value);
} else {
$child = $xml->addChild($key);
$node = dom_import_simplexml($child);
$node->appendChild($node->ownerDocument->createCDATASection($value));
}
}
}
}
/**
* 對資料進行簽名認證,確保是發送的資料
* @param string $token 開放平台設定的TOKEN
* @return boolean true-簽名正確,false-簽名錯誤
*/
private function auth($token){
if(empty($_GET['signature'])) return;
/* 擷取資料 */
$data = array($_GET['timestamp'], $_GET['nonce'], $token);
$sign = $_GET['signature'];
/* 對資料進行字典排序 */
sort($data,SORT_STRING);
/* 產生簽名 */
$signature = sha1(implode($data));
return $signature === $sign;
}
}
|