微信开发学习笔记(第一步:)基本配置

来源:互联网 发布:nginx 无法访问端口 编辑:程序博客网 时间:2024/06/06 19:51

首先感谢陈锋陈老板为我申请好了微信开发帐号,感激啊!

打开https://mp.weixin.qq.com,登录帐号,选择左侧菜单项的:开发-〉基本配置。

首先测试下安装的HTTP服务器(apache+php+mysql)和微信服务器接口。

URL填写脚本对应的URL如:http://xx.xx.xx.xx/weixinTest/wechat.php  (xx部分为可访问的公网ip)

Token(令牌)和wechat.php文件里的define("TOKEN", "weixin")保持一致;

用官网给的示例稍加修改就可以

wechat.php的内容如下:

<?php
/**
  * wechat php test
  */
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//echo $_GET["echostr"];  //如果担心算法有问题,可直接返回,暴力吧!
$wechatObj->valid();   //验证Token时调用。
//$wechatObj->responseMsg();    //处理在手机微信打开公众平台时输入字符串的应答


class wechatCallbackapiTest
{
public function valid()
    {

//验证时只需要通过echo返回计算的结果
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
        echo $echoStr;
        exit;
        }
    }


    public function responseMsg()

//响应消息时需要返加XML格式的消息
    {
//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 = "欢迎光临!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
                }else{
                echo "Input something...";
                }


        }else {
        echo "";
        exit;
        }
    }

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


?>


发现在echo前不能有任何其它的输出,包括代码中不小心敲的空格哦,不然会导致无休止的验证失败,小伙伴们当心了!

  

0 0