微信公众平台初始用

发布时间:2015年1月22日 作者:未知 查看次数:1621

微信公众平台初始用


今天测试微信php自动回复功能,从微信开发者文档下载的wx_sample.php修改后却始终不能成功执行,代码如下:
----------------------------------------------------

<?php

/**

  * wechat php test

  */

 

//define your token

define("TOKEN", "weixin2015");

$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()

    {

  //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>

 

    if(!empty( $keyword ))

                {

                $msgType = "text";

                 $contentStr = "Welcome to wechat world!";

                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

                 echo $resultStr;

          exit;

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

  }

 }

}

 

?>

----------------------------------------------------
后在百度搜索找到一段代码终于成功得到回复。代码如下(修改):

----------------------------------------------------
<?php
/**
  * wechat php test
  */
//define your token
define("TOKEN", "weixin2015");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();

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 = file_get_contents("php://input");
          //extract post data
        if (!empty($postStr)){
               
                  $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = $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 = "欢迎访问!你的id是" . $toUsername;
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }else{
                    echo "Input something...";
                }

        }else {
            echo "";
            exit;
        }
    }
       
    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;
        }
    }
}

?>
----------------------------------------------------

可发现回复的中文却是乱码。
搜索查找原因才知要保存的php文件为utf-8编码(php好像没要求是utf-8编码,非utf-8编码也正常)。用系统自带记事本转换上传后,终于正确了。

file_get_contents("php://input")和$GLOBALS["HTTP_RAW_POST_DATA"]的区别吗?

----------------------------------------------------

http://blog.csdn.net/molaifeng/article/details/40107813

最近在开发微信接口,又学到了一些新的技术点,今天就把学到的关于接收数据的技术点给简单的罗列下。

  1. public function __construct($token$wxuser = ''){  
  2.         $this -> auth($token$wxuser) || exit;  
  3.         if(IS_GET){  
  4.             echo($_GET['echostr']);  
  5.             exit;  
  6.         }else{  
  7.             $xml = file_get_contents("php://input");  
  8.             $xml = new SimpleXMLElement($xml);  
  9.             $xml || exit;  
  10.             foreach ($xml as $key => $value){  
  11.                 $this -> data[$key] = strval($value);  
  12.             }  
  13.         }  
  14.     }  


 

述代码是截取的一个片段,意思为把接收到的微信传过来的xml解析为数组。其中有一处file_get_contents('php://input'),后经查证,微信给开发者账号填写的url发送的是xml数据,但PHP默认只识别application/x-www.form-urlencoded标准的数据类型,对text/xml的内容无法解析为$_POST数组,因此会保留原型,可以交给file_get_contents(‘php://input’)接收,也可以用$GLOBALS['HTTP_RAW_POST_DATA']。


如,传过来的xml为

  1. <xml>  
  2. <ToUserName><![CDATA[ebyben1413005325]]></ToUserName>  
  3. <FromUserName><![CDATA[ga_6281708af4c6]]></FromUserName>  
  4. <CreateTime>1413341614</CreateTime>  
  5. <MsgType><![CDATA[text]]></MsgType>  
  6. <Content><![CDATA[首页]]></Content>  
  7. <MsgId>1234567890123456</MsgId>  


解析过后为

  1. Array  
  2. (  
  3.     [ToUserName] => ebyben1413005325  
  4.     [FromUserName] => ga_6281708af4c6  
  5.     [CreateTime] => 1413341614  
  6.     [MsgType] => text  
  7.     [Content] => 首页  
  8.     [MsgId] => 1234567890123456  
  9. )  


 

php://input 允许读取 POST 的原始数据。和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。同时两者皆不能用于接收enctype="multipart/form-data"形式的数据。


最后再说下$_SERVER['REQUEST_METHOD']这个变量,用过ThinkPHP的朋友应该在代码中使用类似IS_GET、IS_AJAX这种代码吧,追溯下源码,就可以看到

  1. define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);  
  2. define('IS_GET',        REQUEST_METHOD =='GET' ? true : false);  
  3. define('IS_POST',       REQUEST_METHOD =='POST' ? true : false);  
  4. define('IS_PUT',        REQUEST_METHOD =='PUT' ? true : false);  
  5. define('IS_DELETE',     REQUEST_METHOD =='DELETE' ? true : false);  
  6. define('IS_AJAX',       ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) ? true : false);  


原来仅仅就用了这个变量,就达到效果。

 



版权所有!www.sieye.cn
E.Mail:sieye@sohu.com QQ:66697110