爱玺玺

爱玺玺的生活日记本。wx:lb87626

微信公众号开发之//$wechat->valid();奇怪现象,一切都正常但是客户端收不到返回,注释掉valid()就可以了。

url调用的文件 Index.php

<?php 

define("APPID","wx4564ada184e726cf");

define("APPSECRET","93e822bf6bfc606c1a41a3fc96f46cd4");

define("TOKEN","libinailisha");


require("./wechat.inc.php");

$wechat = new WeChat(APPID,APPSECRET,TOKEN);

//$wechat->valid();//开始没写这个会报错,写了后运行收不到回复,注释掉就可以收到回复了。难道这个只需要运行一次?

$wechat->responseMsg();

?>



wechat.inc.php

<?php

/**

 * @Author: yousun

 * @Date:   2018-09-29 11:27:18

 * @Last Modified by:   yousun

 * @Last Modified time: 2018-09-29 15:00:59

 */

class WeChat{

private $_appid;

private $_secrect;

private $_token;

function _construnct($appid,$secrect,$token){

$this->_appid=$appid;

$this->_secrect=$secrect;

$this->_token=$token;

}

    /**

* 连接请求微信服务器

* @var $curl 连接的地址

* @var $https=true,是否支持https协议,默认支持

* @var $method="get" 默认请求方式 get

* @var $data 请求方发来的数据

*/

    private function _request($curl,$https=true,$method='get',$data=null){

$ch=curl_init();//初始化curl

curl_setopt($ch,CURLOPT_URL,$curl);//设置访问url,这里用https还不能访问

curl_setopt($ch,CURLOPT_HEADER,false);//设置不需要头信息

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//只返回页面内容,不执行

if ($https) {

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不做服务器认证

curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//不做客户端认证

}

if ($method=='post') {

curl_setopt($ch,CURLOPT_POST,true);//支持post请求方式

curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//post传来的数据

}

$str=curl_exec($ch);

curl_close($ch);

return $str;

}

private function _getAccessToken(){

$file='./accesstoken';

if (file_exists($file)) {

$content=file_get_contents($file);

$content=json_decode($content);

if (time()-filemtime($file)<$content->expires_in) {

return $content->access_token;

}

}

$content=$this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_secrect);

file_put_contents($file, $content);

$content=json_decode($content);

return $content->access_token;

}

/**

* 生成二维码ticket

* @param  integer $expires_seconds  二维有效期

* @param  string  $type             二维码类型临时还是永久

* @param  integer $scene            场景,不同的服务不同的编号 

* @return [type]                    json

*/

public function _getTicket($expires_seconds=604800,$type="temp",$scene=1){

if ($type=="temp") {//临时二维码

$data='{"expire_seconds": '.$expires_seconds.', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}';

return $this->_request('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->_getAccessToken(),true,"post",$data);

}else{//永久二维码

$data='{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}';

return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->_getAccessToken()); 

}

}

public function _getQRCode($expires_seconds,$type,$scene){

//获取票据json

$content=$this->_getTicket($expires_seconds,$type,$scene);

//json解码

$content=json_decode($content);

//获取ticket票据

$ticket=$content->ticket;

//获取二维码

return $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket);

}





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"];//获得用户发送信息//空间上关闭了

////always_populate_raw_post_data 使用 file_get_contents('php://input')

$postStr = file_get_contents('php://input');


      //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 = "欢迎光临青木树! 我".$fromUsername."接收". $toUsername;

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

                echo $resultStr;

                }else{

                echo "Input something...";

                }


        }else {

        echo "";

        exit;

        }

    }

private function _doEvent($postObj){ //事件处理

switch($postObj->Event){

case  'subscribe': //订阅

$this->_doSubscribe($postObj);

break;

case 'unsubscribe': //取消订阅

$this->_doUnsubscribe($postObj);

break;

default:;

}

}



private function checkSignature()

{

        $signature = $_GET["signature"];

        $timestamp = $_GET["timestamp"];

        $nonce = $_GET["nonce"];

$token = TOKEN;

$tmpArr = array($token, $timestamp, $nonce);

        sort($tmpArr, SORT_STRING);

$tmpStr = implode( $tmpArr );

$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){

return true;

}else{

return false;

}

}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5