[原创]记录7天微信开发+源码分享(上海森思信息公众号)

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: [原创]记录7天微信开发+源码分享(上海森思信息公众号)

此篇博客记录下本人一周微信开发的重点过程,不是手把手教程,做此博客仅为回头查阅之用。

先展示下实现的效果:

MediaLib_Screenshots_wp_ss_20150125_0003MediaLib_Screenshots_wp_ss_20150125_0004MediaLib_Screenshots_wp_ss_20150125_0005MediaLib_Screenshots_wp_ss_20150125_0006

1:熟悉微信开发的流程,注册微信开发公众号;

这个过程可以在微信公众开发(地址:https://mp.weixin.qq.com)的平台自己独立完成一系列的注册之类的,注册之后需要审核,因为我注册的是公众号,所以耐心等待了将近一个礼拜才审核通过。只有审核通过后,才可以打开“开发者中心”菜单,不然在刚刚注册后,开发者中心是没有权限进去的。

 

image

2:审核通过之后,打开开发者中心,便可以看到开发者的文档之类的,经过一番搜索思考后,我采用的平台是:SAE(http://sae.sina.com.cn/平台,反正也是免费的,稳定靠谱就ok,具体在SAE如何上传代码什么之类的,不做叙述,问度娘;

image

3:微信开发之需求

在这个开发中,我需要完成的功能不复杂,主要有如下:

  • 用户关注后立马推送自助菜单
  • 自助菜单主要是以数字来引导操作,例如:1:xx产品使用手册;2:联系我们;3:提供反馈…
  • 增加微信菜单(用户可以点击菜单进行对应的查询或者网页的显示)

具体的需求就上面所叙述的,不复杂,所以做起来也比较的快。

4:微信开发之编码(源码)

创建菜单的过程是这样的:

  • 将菜单的json字符串准备好,具体菜单的json如何构成的,参考微信开发者文档里介绍;
{
    "button": [
        {
			"type": "view", 
			"name": "公司首页", 
			"url": "http://www.sensikeji.com/"
        }, 
        {
            "name": "产品帮助", 
            "sub_button": [
                {
                    "type": "click", 
                    "name": "常见问题", 
                    "key": "常见问题"
                }, 
                {
                    "type": "click", 
                    "name": "遥控灯头", 
                    "key": "遥控灯头"
                }
            ]
        }, 
        {
            "type": "view", 
            "name": "联系我们", 
            "url": "http://www.sensikeji.com/connect/connect/"
        }
    ]
}
  • 通过微信提供的调试接口(http://mp.weixin.qq.com/debug)直接输入json字符串,点击检测问题即可创建好微信的菜单,如下图所示:

image

其中access_token的获取也是在这个接口调试这里获得的:

image

只需要提供开发者的appid以及appSecret即可获得access_token字段值。

  • 开发微信逻辑代码,如下,也就是所有的源码了,源码可以自行修改,源码不是最终版本,仅仅是测试版本,不过相当有参考价值。

<?php
//
// 上海森思信息科技微信源码
// 开发人员:原鹏飞
// Email:ypf1990@foxmail.com
//

define("TOKEN", "sensi");

traceHttp();

$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);
        $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)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            //用户发送的消息类型判断
            switch ($RX_TYPE)
            {
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
   
    private function receiveText($object)
    {
        $keyword = trim($object->Content);

        if($keyword == "文本"){
            //回复文本消息
            $content = "这是个文本消息";
            $result = $this->transmitText($object, $content);
        }
        else if($keyword == "图文" || $keyword == "单图文"){
            //回复单图文消息
            $content = array();
            $content[] = array("Title"=>"单图文标题",
                                "Description"=>"单图文内容",
                                "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",
                                "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $result = $this->transmitNews($object, $content);
        }
        else if($keyword == "多图文"){
            //回复多图文消息
            $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");
            $result = $this->transmitNews($object, $content);
          
        }
        else if($keyword == "音乐"){
            //回复音乐消息
            $content = array("Title"=>"最炫民族风",
            "Description"=>"歌手:凤凰传奇",
            "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3",
            "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
            $result = $this->transmitMusic($object, $content);
        }
        else if ($keyword == "1") {
            $content = "遥控产品常见问题如下所示:";
            $result = $this->transmitText($object, $content);
        }
        else if ($keyword == "2") {
            $content = "遥控灯头使用说明如下所示:";
            $result = $this->transmitText($object, $content);
        }
        else if ($keyword == "3") {
            $content = "关于我们:";
            $result = $this->transmitText($object, $content);
        }
        else if ($keyword == "4") {
            $content = "联系我们:";
            $result = $this->transmitText($object, $content);
        }
        else {
            //回复用户自助菜单
            $content = "请输入数字以进行自助查询:\n[1]遥控产品常见问题\n[2]遥控灯头使用说明\n[3]关于我们\n[4]联系我们";
            $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 receiveVoice($object)
    {
        //回复语音消息
        $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 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]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
   
    /*
     * 回复图文消息
     */
    private function transmitNews($object, $arr_item)
    {
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item 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($arr_item));
        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;
    }
}

function traceHttp()
{
    $content = date('Y-m-d H:i:s')."\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"]."\nQUERY_STRING:".$_SERVER["QUERY_STRING"]."\n\n";
   
    if (isset($_SERVER['HTTP_APPNAME'])){   //SAE
        sae_set_display_errors(false);
        sae_debug(trim($content));
        sae_set_display_errors(true);
    }else {
        $max_size = 100000;
        $log_filename = "log.txt";
        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
        file_put_contents($log_filename, $content, FILE_APPEND);
    }
}

?>

 

5:微信开发中的一些小技巧

  • 微信中的换行符也是”\n”
  • 微信单图文图片尺寸推荐:360*240;多图文模式中小图尺寸为200*200

上述便是本人一周内的微信开发一些总结,总体感觉如果你有php开发基础,微信开发一点都不难。后续还有一些想起来的会补充进来,欢迎看到此文的各位不吝指教,谢谢!

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: [原创]记录7天微信开发+源码分享(上海森思信息公众号)

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: