php版微信公众平台开发之如何实现验证

发布时间:2021-08-31 14:28:28 作者:小新
来源:亿速云 阅读:113

这篇文章将为大家详细讲解有关php版微信公众平台开发之如何实现验证,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

下载好后代码如下:

<?php
/**
 * wechat php test
 * update time: 20141008
 */
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$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 (!emptyempty($postStr)){
    $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(!emptyempty( $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;
  }
 }
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;
}
}
}
?>

其中:TOKEN 修改为你自己想要的 然后在 开发者中心也要写一样的,在验证的过程中 $wechatObj->valid(); 这段代码不能去除这个是验证,验证成功后 我们就可以把 这段 $wechatObj->valid(); 这个注释掉了,然后使用 $wechatObj->responseMsg(); 来进行测试

注意:在开发的时候需要把 $wechatObj->valid(); 给注释掉,不然在手机测试的时候 会没有显示什么.

关于“php版微信公众平台开发之如何实现验证”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. php如何实现微信公众平台开发之验证的示例分析
  2. 微信公众平台开发之.Net如何实现发送图文消息

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:LINQ查询操作分析

下一篇:C#线程控制介绍

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》