php微信平台开发

微信公众平台官方提供了部分的php源码,其实很多语言其实都可以实现微信平台的开发,柳峰的博客上面有很多java实现的代码,现在贴一点php的(声明:一部分来自网络,任何问题请联系作者,以尽快作出处理)。


<?php
/*
    这部分实现了几个功能:发语音回笑话、发地址会天气预报,点歌;结合下面的两个函数实现:自动聊天、lol战斗力和胜率查询
    CopyRight 2013 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);
        $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 "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                default:
                    $result = "";
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
	
	private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注小范来帮忙\n".
                "天气:请发送位置\n".
                "笑话:请对我说话\n".
                "点歌请发送:M@歌手名@歌曲名\n".
				"LOL查询请发送:L@区@召唤师名称\n".
				"如果你只想聊聊天,就随便输吧!";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            default:
                $content = "";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }
	
	private function receiveText($object)
    {
        $keyword = trim($object->Content);
        if (strpos($keyword, "@")){
            $music = explode("@",$keyword);
            if($music[0]=='M'){
                $url = "http://api100.duapp.com/music/?appkey=".$object->ToUserName."&singer=".urlencode($music[1])."&song=".urlencode($music[2]);
                $output = file_get_contents($url);
                $content = json_decode($output, true);
                $result = $this->transmitMusic($object, $content);
            }else if($music[0]=='L'){
                include('lolserch.php');
                $content = lolserch($music[1],$music[2]);
                $result = $this->transmitText($object, $content);
            }
			}else{
            include('simsimi.php');
			$content = SimSimi($keyword);
			$result = $this->transmitText($object, $content);
            //$content = date("Y-m-d H:i:s",time());;
            //$result = $this->transmitText($object, $content);
        }
        return $result;
    }
	
	private function receiveLocation($object)
    {
        $url = "http://api100.duapp.com/weather2/?appkey=".$object->ToUserName."&lat=".$object->Location_X."&lng=".$object->Location_Y;
        $output = file_get_contents($url);
        $content = json_decode($output, true);
        $result = $this->transmitNews($object, $content);
        return $result;
    }

    private function receiveVoice($object)
    {
        $url = "http://api100.duapp.com/joke/?appkey=".$object->ToUserName;
        $output = file_get_contents($url);
        $content = json_decode($output, true);
        $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 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;
    }
    
    private function logger($log_content)
    {
    }
}
?>
(这里部分代码取自方倍工作室)

下面一个函数实现聊天功能,主要原理是通过从小黄鸡网站上获取数据


<?php
function SimSimi($keyword) {

	//----------- 获取COOKIE ----------//
	$url = "http://www.simsimi.com/";
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER,1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$content = curl_exec($ch);
	list($header, $body) = explode("\r\n\r\n", $content);
	preg_match("/set\-cookie:([^\r\n]*);/iU", $header, $matches);
	$cookie = $matches[1];
	curl_close($ch);

	//----------- 抓 取 回 复 ----------//
	$url = "http://www.simsimi.com/func/req?lc=ch&msg=$keyword";
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_REFERER, "http://www.simsimi.com/talk.htm?lc=ch");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	$content = json_decode(curl_exec($ch),1);
	curl_close($ch);

	if($content['result']=='100') {
		$content['response'];
		return $content['response'];
	} else {
		return '我还没进化好...换个话题呗';
	}
}

?>

下面一个函数实现lol战力和胜率查询,主要原理是通过在盒子中截取数据


<?php
function lolserch($area,$user)
{
	$in='http://lolbox.duowan.com/playerDetail.php?serverName='.$area.'&playerName='.$user;
	$text=file_get_contents("http://lolbox.duowan.com/playerDetail.php?serverName=".$area."&playerName=".$user);
	$text=str_replace(array("\r","\n","\t","\s"), '', $text);

    preg_match('#(.*)(<em><span title=\'更新时间:)(.*?)(\'>)(.*?)(</span>)(.*)#', $text, $matches);
    preg_match('#(.*)(算法</a>)(.*?)(</p>)(.*)#', $text, $matches1);
    
    preg_match('#(.*)(人机对战</td>)(.*?)(<td>)(.*?)(</td>)(.*?)(<td>)(.*?)(</td>)(.*)#', $text, $matches2);
    preg_match('#(.*)(经典模式</td>)(.*?)(<td>)(.*?)(</td>)(.*?)(<td>)(.*?)(</td>)(.*)#', $text, $matches3);
    preg_match('#(.*)(ranked_league_points">-</td>)(.*?)(<td>)(.*?)(</td>)(.*?)(<td>)(.*?)(</td>)(.*?)<td>(.*?)(</td>)(.*?)<td>(.*?)(</td>)(.*)#', $text, $matches4);
	//preg_match('/<div[^>]*class="list1"[^>]*>(.*?) <\/div>/si',$text,$match);
	//preg_match('/<img[^>]*>/Ui', $text, $match);
	//echo $match;
	//print_r($matches[3]);
	$power=$matches[3]."\n==============\n战斗力:".$matches[5]."\n".$matches1[3]."\n========\n人机胜率".$matches2[9]."\n匹配胜率".$matches3[9]."\n排位胜率".$matches4[9];
	return $power;
}
?>

而且可以看得出来,我正则表达式不怎么会,写的特别笨,如有路过,请指点一二……


这是上面代码的测试账号:

ID:f_help

二维码:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值