微信公账号后台开发

参考手册和网上资料,自己捣鼓了一个后台,实现关键字回复功能。

目前微信开放给个人订阅号的权限只有被动回复,也无法创建自定义菜单,其他功能需要跳转到自己的网页,并嵌入微信的js-sdk,使用微信的其他接口,具体参考手册:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

 

<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/wx/checksignature.php');

$wechatObj = new wechatCallbackapi();
//$wechatObj->valid();//接口验证
$wechatObj->responseMsg();//调用回复消息方法
class wechatCallbackapi
{
	public function valid()
	{
			$echoStr = $_GET["echostr"];

			//valid signature , option
			if(checksignature()){
					echo $echoStr;
					exit;
			}
	}

	public function responseMsg()
	{
		//get post data, May be due to the different environments
	   // $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		$postStr = file_get_contents("php://input");
		log($postStr);
		//extract post data
		if (!empty($postStr)){
			/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
			the best way is to check the validity of xml by yourself */
			libxml_disable_entity_loader(true);
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$time = time();
			$msgType = $postObj->MsgType;//消息类型
			$event = $postObj->Event;//时间类型,subscribe(订阅)、unsubscribe(取消订阅)
			$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>";
			$pictureTpl = "<xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[fromUser] ]></FromUserName><CreateTime>12345678</CreateTime>
			<MsgType>< ![CDATA[image] ]></MsgType><Image><MediaId>< ![CDATA[media_id] ]></MediaId></Image></xml>";

			switch($msgType){
				case "event":
					if($event=="subscribe"){
						$contentStr = "Hi,你来啦![]~( ̄▽ ̄)~* \n"."跳转http://t.cn/E49UnrA"."\n"."回复数字'1'->了解我们是谁"."\n"."回复数字'2'->了解我们干嘛";
						$msgType= 'text';
					}
					break;
				case "text":
					switch($keyword){
						case "1":
							$contentStr = "我们是程序员http://t.cn/E49UnrA";
							break;
						case "2":
							$contentStr = "我们帮人办网站";
							break;
						default:
							$contentStr = "对不起,你的内容我会稍后回复";
					}
					break;
				case "image":
					$contentStr = "收到图片";
					break;
			}

			$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
			echo $resultStr;
		}else {
			echo "";
			exit;
		}
	}
}

注意:收到订阅事件时,一定要将回复的事件类型改为text ($msgType= 'text';),否则用户将收不到消息。 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值