首页 > 代码库 > 微信公众平台开发(3)封装全部基础接口源码

微信公众平台开发(3)封装全部基础接口源码

<?php
define ( "TOKEN", "tony" );

if (! isset ( $_GET ["echostr"] )) {
	// 调用响应消息函数
	responseMsg ();
} else {
	// 实现网址接入,调用验证消息函数
	valid ();
}
/*
 * 验证消息函数
 */
function valid() {
	if (checkSignature ()) {
		$echoStr = $_GET ["echostr"];
		echo $echoStr;
		exit ();
	} else {
		echo "error";
		exit ();
	}
}

/*
 * 检查签名函数
 */
function checkSignature() {
	// you must define TOKEN by yourself
	if (! defined ( "TOKEN" )) {
		throw new Exception ( 'TOKEN is not defined!' );
	}
	
	$signature = $_GET ["signature"];
	$timestamp = $_GET ["timestamp"];
	$nonce = $_GET ["nonce"];
	
	$token = TOKEN;
	$tmpArr = array (
			$token,
			$timestamp,
			$nonce 
	);
	// use SORT_STRING rule
	sort ( $tmpArr, SORT_STRING );
	$tmpStr = implode ( $tmpArr );
	$tmpStr = sha1 ( $tmpStr );
	
	if ($tmpStr == $signature) {
		return true;
	} else {
		return false;
	}
}

/*
 * 响应消息函数
 */
function responseMsg() {
	
	// 根据用户传过来的消息类型进行不同的响应
	
	// 接受微信服务器POST过来的XML数据包
	$postData = http://www.mamicode.com/$GLOBALS ["HTTP_RAW_POST_DATA"];>

微信公众平台开发(3)封装全部基础接口源码