Table of Contents
关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题,
您可能感兴趣的文章:
Home php教程 php手册 关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题,

关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题,

Jun 13, 2016 am 08:48 AM
token WeChat Subscription number

关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题,

相信很多人会跟我一样,token验证之后,发送消息给订阅号,没有消息返回。

以下,说一下我辛苦调试得到的解决办法:

首先,token验证:

自己写的token一直验证失败,找了好久,没有发现bug。实在没办法,就用了官方的示例代码。并且通过示例代码调试,发现了一个让我吐血的bug(也不算bug):

token验证貌似要求字符编码格式!!!!

官方的示例代码,直接上传到服务器,token直接过!

把官方示例代码改为UTF-8格式,再上传覆盖,token失败!失败!失败!

后来,把自己写的修改为ANSI格式还是token失败!醉了醉了!那只好用官方示例代码。在此,说下,token是一次握手验证,验证过一次就不用了。

下面,言归正传,貌似偏题了...orz

token验证之后,直接用官方示例代码,赶紧测试自己的订阅号,结果....发出去的消息就跟泼出去的水一样,什么鬼都没有返回...orz

又各种找bug,各种群问,各种搜索....历经本博主九九八十一的努力,终于找出了问题所在(这里是指我自己开发的,并不包括全部,如果你有不同的bug,欢迎交流):

1、最容易被忽视的一个bug,官方给的示例代码,压根就没调用写好的那个responseMsg()函数!

2、把之前的token代码注释,也就是$wechatObj->valid();这行代码。因为toke验证那段代码会有一个echo $echostr,会把responseMsg()函数里的echo $resultStr;(56行)xml格式混乱,输回给微信服务器就无法识别了(貌似只能识别xml格式,还有json格式)。(token验证是一次握手验证,验证开发者之后,就可以不用了,赶紧让它消失在我们整洁的代码orz...)

3、最恶心的一个bug,还是字符编码问题!orz...xml要求UTF-8编码,所以,把示例代码改回UTF-8编码!这个bug找的让我崩溃!!!

下面是我修改后的代码,能正常运行,无bug,需要的可以参考一下

<&#63;php
 /**
 * wechat php test
 */
 //define your token
 define("TOKEN", "codcodog");
 $wechatObj = new wechatCallbackapiTest();
 //$wechatObj->valid();
 $wechatObj->responseMsg();
 class wechatCallbackapiTest
 {
  public function valid()
  {
   $echoStr = $_GET["echostr"];
   //valid signature , option
   if($this->checkSignature()){
   header('content-type:text');
    echo $echoStr;
    exit;
   }
  }
  public function responseMsg()
  {
   //get post data, May be due to the different environments
   $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
   //$postStr = file_get_contents("php://input");
   file_put_contents("log.txt",$postStr,FILE_APPEND );
   //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></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;
   }
  }
  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 = sha( $tmpStr );
   if( $tmpStr == $signature ){
    return true;
   }else{
    return false;
   }
  }
 }
 &#63;>
Copy after login

以上所述是小编给大家分享的php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的解决方案,希望大家喜欢。

您可能感兴趣的文章:

  • PHP Token(令牌)设计
  • PHP令牌 Token改进版
  • 批处理delims=和tokens=星号 的使用差别
  • 批处理FOR 中的Delims和Tokens总结
  • 批处理 FOR参数/F之tokens详解
  • 微信access_token的获取开发示例
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

How to solve the problem of JS resource caching in enterprise WeChat? How to solve the problem of JS resource caching in enterprise WeChat? Apr 04, 2025 pm 05:06 PM

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

How to choose H5 and applets How to choose H5 and applets Apr 06, 2025 am 10:51 AM

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

Detailed tutorial on how to buy and sell Binance virtual currency Detailed tutorial on how to buy and sell Binance virtual currency Mar 18, 2025 pm 01:36 PM

This article provides a brief guide to buying and selling of Binance virtual currency updated in 2025, and explains in detail the operation steps of virtual currency transactions on the Binance platform. The guide covers fiat currency purchase USDT, currency transaction purchase of other currencies (such as BTC), and selling operations, including market trading and limit trading. In addition, the guide also specifically reminds key risks such as payment security and network selection for fiat currency transactions, helping users to conduct Binance transactions safely and efficiently. Through this article, you can quickly master the skills of buying and selling virtual currencies on the Binance platform and reduce transaction risks.

See all articles