微信公众平台开发接口PHP SDK完整版

代码如下:

更新日志:

2013-01-01 版本1.0
2014-03-15 增加图片、视频、语音的内容回复
2014-04-09 增加菜单链接事件
2014-04-10 修改文本回复的判定方法

代码如下:

<?php
/*
    方倍工作室
    CopyRight 2014 All Rights Reserved
*/

define("TOKEN", "weixin");

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    //验证消息
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

//检查签名
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

//响应消息
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

//接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注方倍工作室 ";
                $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = "方倍工作室提供互联网相关产品与服务。";
                        break;
                    default:
                        $content = "点击菜单:".$object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

//接收文本消息
    private function receiveText($object)
    {
        switch ($object->Content)
        {
            case "文本":
                $content = "这是个文本消息";
                break;
            case "图文":
            case "单图文":
                $content = array();
                $content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                break;
            case "多图文":
                $content = array();
                $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                break;
            case "音乐":
                $content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
                break;
            default:
                $content = date("Y-m-d H:i:s",time());
                break;
        }
        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

private function receiveLocation($object)
    {
        $content = "你发送的是位置,纬度为:".$object->Location_X.";经度为:".$object->Location_Y.";缩放级别为:".$object->Scale.";位置为:".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是:".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }

return $result;
    }

private function receiveVideo($object)
    {
        $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }

private function receiveLink($object)
    {
        $content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";

$item_str = sprintf($itemTpl, $imageArray['MediaId']);

$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
    <MediaId><![CDATA[%s]]></MediaId>
</Voice>";

$item_str = sprintf($itemTpl, $voiceArray['MediaId']);

$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
    <MediaId><![CDATA[%s]]></MediaId>
    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
</Video>";

$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";

$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

$result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
}
?>

(0)

相关推荐

  • weiphp微信公众平台授权设置

    weiphp后台使用设置 实现在用户授权时候显示公众号的名字以及分享使用该服务号 使用步骤 1:在weiphp后台打开公众号管理-新增 2:输入公众号名字,原始ID,微信号 3:在这里公众号能查找到 4: 输入完成之后下一步,他会提供URL和token令牌.然后就要在微信公众号后台配置 6输入完成之后我,记录下key,appid和appSecret,输入在这里 7:按保存了之后, 在右上角选中你刚填写的服务号信息切换为当前公众号 8:打开基础插件-自定义菜单-新增 如果新增成功, 则保存成功,如

  • PHP对接微信公众平台消息接口开发流程教程

    一.写好接口程序 在你的服务器上上传好一个接口程序文件,如http://www.yourdomain.com/weixin.php  内容如下: 复制代码 代码如下: <?phpdefine("TOKEN", "weixin");//自己定义的token 就是个通信的私钥$wechatObj = new wechatCallbackapiTest();$wechatObj->valid();//$wechatObj->responseMsg();c

  • php微信公众平台开发之微信群发信息

    1.目的 完成在微信公众号中群发消息.这里只是完成简单的文字发送.也可以发送语音图片等,只是发送数据格式不同而已,下面有链接,可以查询数据类型的数据发送格式. 2.群发短信的流程 获取测试公众账号(有账号的可以不用测试账号,不过正式的账号限制比较多)用户关注上面的公众账号通过appid和appsecret获取我们的access_token通过access_token群发短信 3.获取测试公众账号 + 关注公众号 1).公众测试账号获取 访问上面的连接,选择"接口测试号申请"获得直接打开

  • PHP实现微信公众平台音乐点播

    1.构造微信提供的XML格式的音乐消息音乐的XML格式是这样的: 复制代码 代码如下: <xml>    <ToUserName><![CDATA[toUser]]></ToUserName>    <FromUserName><![CDATA[fromUser]]></FromUserName>    <CreateTime>12345678</CreateTime>    <MsgType

  • 使用PHP进行微信公众平台开发的示例

    1. SAE 数据库的连接. 需要主机名和端口,以后的使用是一样的. @ $db = new mysqli(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS,'你的应用名'); 2.XML 的处理. 微信发送的消息格式都是 XML 格式,你返回的消息也必须是 XML 格式.从 XML 里提取数据,用 SimpleXML,强大又容易使用.包装成 XML 消息呢?把消息模板保存为字符串,然后用 sprintf 进行格式

  • php实现基于微信公众平台开发SDK(demo)扩展的方法

    本文实例讲述了php实现基于微信公众平台开发SDK(demo)扩展的方法.分享给大家供大家参考.具体分析如下: 该扩展基于官方的微信公众平台SDK,这里只做了简单地封装,实现了一些基本的功能(如天气查询,翻译,自动聊天机器人,自定义菜单接口)仅供学习之用.代码如下: 复制代码 代码如下: define("TOKEN", "xingans"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->respo

  • php微信公众平台开发类实例

    本文实例讲述了php微信公众平台开发类.分享给大家供大家参考.具体分析如下: ThinkWechat.php类文件如下: <?php class Wechat { /** * 微信推送过来的数据或响应数据 * @var array */ private $data = array(); /** * 构造方法,用于实例化微信SDK * @param string $token 微信开放平台设置的TOKEN */ public function __construct($token) { $this

  • PHP memcache在微信公众平台的应用方法示例

    本文实例讲述了PHP memcache在微信公众平台的应用方法.分享给大家供大家参考,具体如下: 现在微信公众平台大多数互动都是用户发送信息->微信分析并返回结果,这种模式功能比较单一.这里介绍另一种互动模式:用户发送信息->微信分析信息并提示下一步操作->用户发送信息->.......->微信返回结果.本文介绍运用sae里的memcache实现以上模式. 思路: 1.用户发送消息,微信会记录用户唯一的openid,将它的值赋予$fromUsername. 2.用memcac

  • PHP中的Memcache详解

    一.Memcache简介 Memcache是danga.com的一个项目,最早是为 LiveJournal 服务的,目前全世界不少人使用这个缓存项目来构建自己大负载的网站,来分担数据库的压力.它可以应对任意多个连接,使用非阻塞的网络IO.由于它的工作机制是在内存中开辟一块空间,然后建立一个HashTable,Memcached管理这些HashTable,所以速度非常快. 二.Memcache和memcached的区别 为什么会有Memcache和memcached两种名称?其实Memcache是

  • php微信公众平台配置接口开发程序

    在阅读这篇文章之前你要做以下的准备: 1.注册一个订阅号(通过微信公众平台https://mp.weixin.qq.com/); 2.注册新浪云并实名认证http://sae.sina.com.cn/ 3.实名认证新浪云之后,创建一个云应用. 4.你需要知道php基础知识. 一:验证接口 1.登录我们的公众号.然后点击进入开发者工具,在登录之后页面的左下角. 2.点击进入开发者文档.之后点击开始开发,点击接入指南,我们会看到如下图. 图片上有说,接入微信公众平台开发,开发者需要按照如下步骤完成:

随机推荐