《糖果唱》-开发一个微信公共平台后台

开发一个公共账号的大体的开发思路是:

1用户关注,返回一条默认信息 “欢迎挑战糖果唱音乐机器人,来感受不一样的音乐吧,开始请按1~”
PS:此时用户不管按什么,除了1之外都返回该信息,按9看团队联系方式等


2用户按1,返回一条音频信息,同时创建一条用户信息,信息存储用户得分,用户openid,答对和打错的数目


3,用户看到一条音频信息,如 :“客官,俺已经为您准备好了一条上好的狼嚎,请您享用,猜一猜这首狼嚎的名字,1XXXX,2,XXX,3,XXXX4,XXX”,此处可准备多种这样的文字,可以编辑文字,如不输入1234则提示用户输入


4用户输入答案,此处判断答案是否正确,如正确则提示加分,也可输入0查询当前分值,输入9继续游戏


一、创建相应的数据表:

DROP TABLE IF EXISTS `wx_info`;
CREATE TABLE `wx_info` (
  `openid` varchar(64) NOT NULL,
  `point` int(11) unsigned zerofill DEFAULT NULL,
  `answer` int(11) DEFAULT NULL,
  `createtime` int(11) DEFAULT NULL,
  PRIMARY KEY (`openid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二、验证服务器TOKEN

详细的请参考 http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token

三、编写相应的逻辑代码:

<?php
/**
  * wechat php test
  */
define ( 'IN_PRG', '1' );

include_once ('../lib/init.inc.php');
require_once (ROOT_PATH . 'weixin/wx_common.php');

//define your token
define("TOKEN", "yourtoken");

$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();
class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
    	
    	$textTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[%s]]></MsgType>
    	<Content><![CDATA[%s]]></Content>
    	<FuncFlag>0</FuncFlag>
    	</xml>";
    	$newsTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[%s]]></MsgType>
    	<ArticleCount>%s</ArticleCount>
    	<Articles>
    	<item>
    	<Title><![CDATA[%s]]></Title>
    	<Description><![CDATA[%s]]></Description>
    	<PicUrl><![CDATA[%s]]></PicUrl>
    	<Url><![CDATA[%s]]></Url>
    	</item>
    	</Articles>
    	<FuncFlag>1</FuncFlag>
    	</xml> ";
    	$musicTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[%s]]></MsgType>
    	<Music>
    	<Title><![CDATA[%s]]></Title>
    	<Description><![CDATA[%s]]></Description>
    	<MusicUrl><![CDATA[%s]]></MusicUrl>
    	<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    	</Music>
    	<FuncFlag>0</FuncFlag>
    	</xml>";
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
              	//发送方ID
                $fromUsername = $postObj->FromUserName;
                //咱们的ID
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $game = new wx_common();
 				if (!empty($fromUsername)) {
  					$openid = $fromUsername;					
  					$gameUser=$game->isGameUser($openid);
 					if(!empty( $keyword ) )
 					{

						$lastanswer=$game->getUserAnswer($openid);
 						if($gameUser ==false && $keyword=="1"){
 							//这里是注册用户
 							$stauts=$game->createWxUser($openid);
 							if ($stauts){
 								$this->startGame($game, $openid, $fromUsername, $toUsername, $time,$musicTpl);
 							}else{
 								$msgType = "text";
 								$contentStr = "系统暂时出错,请稍后重试";
 								$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 								echo $resultStr;
 							}
 						}
 						else if($gameUser == true && $lastanswer !=""){
 								switch ($keyword) {
 									case "1":
 										$this->checkUserAnswerRight($game, $openid, $keyword, $fromUsername, $toUsername, $time, $textTpl);
 											
 										break;
 									case "2":
 										$this->checkUserAnswerRight($game, $openid, $keyword, $fromUsername, $toUsername, $time, $textTpl); 
 										break;
 									case "3":
 										$this->checkUserAnswerRight($game, $openid, $keyword, $fromUsername, $toUsername, $time, $textTpl);
 										break;
 									case "4":
 										$this->checkUserAnswerRight($game, $openid, $keyword, $fromUsername, $toUsername, $time, $textTpl);
 									 	break; 										
 									case "8":
 										$userPoint=$game->getWxUserPoint($openid);
 										$useRank = $game->getUserRank($openid);
 										if ($useRank<=10) {
 											$rank = rand(97,99);
 										}
 										else {
 											$rank = rand(80,97);
 										}
 										$msgType = "text";
 				 						
 										$contentStr = "亲爱的糖果唱糖果小喷油~\n你现在的积分是【".$userPoint."】分~\n你当前排名第".$useRank."名,打败了全国".$rank."%玩家,请继续努力吧~\n继续游戏请按9";
 										$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 										echo $resultStr;
 										break;
 									case "9":
 										$this->startGame($game, $openid, $fromUsername, $toUsername, $time,$musicTpl);
 										break;						
 									default:
 										$msgType = "text";
 										$contentStr = "请输入1-4猜答案~\n输入9重发一首您会的歌~\n输入8查看您的战绩~\n请iphone同学关注【糖果唱】~\nlolipop.cn";
 										$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 										echo $resultStr;;
 									break;
 								}
 								
 						}
 						else if($gameUser == true && $lastanswer ==""){
 							switch ($keyword) {
 								case "1":
 									$this->startGame($game, $openid, $fromUsername, $toUsername, $time,$musicTpl);
 									break;
 								case "8":
 									$userPoint=$game->getWxUserPoint($openid);
 									$useRank = $game->getUserRank($openid);
 									$msgType = "text";
 							 		if ($useRank<=10) {
 										$rank = rand(97,99);
 									}
 									else {
 										$rank = rand(80,97);
 									}
 									$contentStr = "亲爱的糖果唱糖果小喷油~\n你现在的积分是【".$userPoint."】分~\n你当前排名第".$useRank."名,打败了全国".$rank."%玩家[玫瑰]~\n继续游戏请按9";
 									$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 									echo $resultStr;
 									break;
 								case "9":
 									$this->startGame($game, $openid, $fromUsername, $toUsername, $time,$musicTpl);
 									break;
 								default:
 									$msgType = "text";
 									$contentStr = "输入9重发一首您会的歌~\n输入8查看您的战绩~\n请iphone同学关注【糖果唱】~\nlolipop.cn";
 									$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 									echo $resultStr;;
 									break;
 							}
 						}
 						else{
 							//这里写回复规则
 							$msgType = "text";
 							$contentStr = "挑战糖果唱音乐机器人\n来感受不一样的音乐吧\n开始请按1~[玫瑰]\n输入8查看您的战绩~\n请iphone同学关注【糖果唱】~\nlolipop.cn";
 							$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 							echo $resultStr;
 						}
 						 
 					}
 					else{
 						 	//这里写回复规则
 							$msgType = "text";
 							$contentStr = "挑战糖果唱音乐机器人![坏笑]\n来感受不一样的音乐吧~come on baby~你有信心超过第一名吗?\n开始请按1~[玫瑰]";
 							$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 							echo $resultStr;
 					}
 				}else{
                			//这里写回复规则
 							$msgType = "text";
 							$contentStr = "挑战糖果唱音乐机器人![坏笑]\n来感受不一样的音乐吧~come on baby~你有信心超过第一名吗?\n开始请按1~[玫瑰]";
 							$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 							echo $resultStr;
                }

        }else {
        	echo "";
        	exit;
        }
    }
	
	/**
	 * 开始游戏
	 * 
	 * @param unknown_type $game        	
	 * @param unknown_type $openid        	
	 * @param unknown_type $fromUsername        	
	 * @param unknown_type $toUsername        	
	 * @param unknown_type $time        	
	 */
	private function startGame($game, $openid, $fromUsername, $toUsername, $time,$musicTpl) {
		global $audiohost;
		// 生成一个新游戏
		// 得到被赞歌曲随机的一首歌
		$randomSong = $game->getRandomPraiseSong ();
		// 通过这首歌获取三个歌名
		$songArray = $game->getanswer ( $randomSong->song_name );
		$song_name_string = "";
		$answer = 0;
		foreach ( $songArray as $songs ) {
			$tmpnum = $answer + 1;
			// 把这首歌对应答案编号写入数据库
			if ($songs ["is_right"] == 1) {
				$game->updateAnswer ( $openid, $tmpnum );
			
			}
			$answer = $answer + 1;
		}
		$answer = 0;
		foreach ( $songArray as $songs ) {
			$tmpnum = $answer + 1;
			$song_name_string = $song_name_string . "【" . $tmpnum . "】" . $songs ["song_name"] . "\n";
			$answer = $answer + 1;
		}
		// 获取这首歌的URL
		$song_url = $audiohost . substr ( $randomSong->song_file_url, 6, str_len ( $randomSong->song_file_url ) );
		$mp3_song_url =$song_url."?avthumb/mp3";
		// 发送给用户
		$msgType = "music";
		$resultStr = sprintf ( $musicTpl, $fromUsername, $toUsername, $time, $msgType, $song_name_string, "快来猜猜这首【lang】嚎吧~", $song_url, $mp3_song_url );
		echo $resultStr;
	
	}
    /**
     * 检查用户是否答对
     * @param unknown_type $game
     * @param unknown_type $openid
     * @param unknown_type $keyword
     * @param unknown_type $fromUsername
     * @param unknown_type $toUsername
     * @param unknown_type $time
     */
	private function checkUserAnswerRight($game,$openid,$keyword,$fromUsername, $toUsername, $time,$textTpl){
		$answerright=$game->isAnswerRight($openid, $keyword);
		if ($answerright) {
			//执行加分
			$game->plusWxUserPoint($openid,100);
			$game->updateAnswer($openid,"");
			$msgType = "text";
			$contentStr = "恭喜你答对了!加100分[玫瑰]\n查看个人积分请按8\n继续游戏请按9\n若超时请重新输入[玫瑰]~";
			$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
			echo $resultStr;
		}
		else{
			$game->updateAnswer($openid,"");
			$msgType = "text";
			$contentStr = "[猪头]错了错了!再试试吧~小伙伴相信你[加油]\n查看个人积分请按8\n继续游戏请按9\n若超时请重新输入[玫瑰]~";
			$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
			echo $resultStr;
		}
	}	
	
	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;
		}
	}
}

?>

数据库相关的代码并没有给出,其实很简单的逻辑,大约用了一下午写完的,本来可以做的更加复杂的,为了快速实现就简化了,

可以关注微信公共账号《糖果唱》


以下是相关的一些截图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值