<?php
if(!defined('IS_INITPHP')) exit('Access Denied!');
/**
* 微信API封装类
* @author lxm
* @time 2013-06-03
* @version
*/
class weixin
{
public $token;
public $msgType;
public $msg;
public function __construct(){
$this -> token = '';
$this -> msgType = 'text';
$this -> msg = array();
}
public function __destruct(){
unset($this -> token);
unset($this -> msgType);
unset($this -> msg);
}
/**
* @param
*/
public function setToken($token){
$this -> token = $token;
}
/**
* 获取用户通过微信发送过来的信息
*/
public function getMsg(){
//get post data, May be due to the different environments
$postData = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data
if (!empty($postData)){
$this -> msg = (array)simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
$this -> msgtype = strtolower($this->msg['MsgType']);
}
}
/**
* 回复文本消息
*/
public function makeText($text){
$createTime = InitPHP::getTime();
$FuncFlag = $this->setFlag ? 1 : 0;
$textTpl = "<xml>
<ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
<CreateTime>{$createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%s</FuncFlag>
</xml>";
return sprintf($textTpl,$text,$FuncFlag);
}
/**
* 回复图文消息
*/
public function makeNewsPic($data=array()){
$createTime = InitPHP::getTime();
$FuncFlag = $this->setFlag ? 1 : 0;
$newTplHeader = "<xml>
<ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
<CreateTime>{$createTime}</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>";
$newTplItem = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
$newTplFoot = "</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";
$Content = '';
$itemsCount = count($data['items']);
$itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条
if ($itemsCount) {
foreach ($data['items'] as $key => $item) {
if ($key<=9) {
$Content .= sprintf($newTplItem,$item['title'],$item['description'],$item['picurl'],$item['url']);
}
}
}
$header = sprintf($newTplHeader,$itemsCount);
$footer = sprintf($newTplFoot,$FuncFlag);
return $header . $Content . $footer;
}
public function valid(){
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()===true){
return $echoStr;
}else{
return false;
}
}
private function checkSignature(){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = $this->token;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
//$d= $token.'----'.$signature.'::'.$timestamp.'::'.$nonce.'~~~~'.$tmpStr;
//file_put_contents(CAR_PATH."test/test.txt",$d);测试
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}