您的位置:首页 > 移动开发 > 微信开发

微信开发(PHP)初探-1

2015-11-27 21:21 477 查看
首先,要有一台自己能控制的服务器和域名,因本人用的PHP,以下都以PHP语言为例。

在正式开发之前,先申请测试号用来测试

进入微信文档首页:http://mp.weixin.qq.com/wiki/home/index.html

测试号申请|在线调试->接口测试号申请

会要求你输入你的URL和Token

URL是用来验证服务器地址的有效性

Token自己设定,必须与你的URL中设的Token值相同

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带四个参数

signature

timestamp

nonce

echostr

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。

参照给出的示例代码:

在服务器上新建index.php文件,确保通过域名http://www.xxx.com/index.php可以访问到,

index.php文件内容如下:

<?php
/**
* wechat php test
*/

//define your token
define("TOKEN", "srrx");
$wechatObj = new wechatCallbackapiTest();
if(!isset($_GET["echostr"])) {
if($wechatObj->checkSignature()) {
$wechatObj->responseMsg();
}
} else {
$wechatObj->valid();
}

class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];

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

public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

//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();
$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>";
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "Welcome to wechat world!!!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}

}else {
echo "";
exit;
}
}

public 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;
}
}
}

?>


然后在提交URL和Token的地方填上”http://www.xxx.com/index.php“和在php文件里设的Token值”keyunq”

提交后,通过验证会给出成功提示。

然后用自己的微信号关注该测试号,输入任何内容,测试号会回复“Welcome to wechat world!!!”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: