


Simulation test of WeChat interface and WeChat development test code_PHP tutorial
To become a developer of a WeChat public account (subscription account or service account), you need to first verify the interface. This can be set after logging in to the WeChat https://mp.weixin.qq.com backend. But I found it troublesome, so I developed an interface class that included verification functions (as well as the function of replying to text messages and graphic messages). In fact, interface verification is useless after becoming a developer.
Upload the code, WeChat base class: weixin.class.php
class Weixin
{
public $token = '';//token
public $debug = false;//Whether the debug status is marked, so that we can record some intermediate data during debugging
public $setFlag = false;
public $msgtype = 'text'; //('text','image' ,'location')
public $msg = array();
public function __construct($token,$debug)
{
$this->token = $token;
$this ->debug = $debug;
}
//Get the message sent by the user (message content and message type)
public function getMsg()
{
$postStr = $GLOBALS[ "HTTP_RAW_POST_DATA"];
if ($this->debug)
{
$this->write_log($postStr);
}
if (!empty($postStr))
{
$this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->msgtype = strtolower($this->msg['MsgType']);
}
}
//Reply text message
public function makeText($text='')
{
$CreateTime = time();
$FuncFlag = $ this->setFlag ? 1 : 0;
$textTpl = "
return sprintf($textTpl,$text,$FuncFlag);
}
//Reply image and text based on array parameters Message
public function makeNews($newsData=array())
{
$CreateTime = time();
$FuncFlag = $this->setFlag ? 1 : 0;
$newTplHeader = "
%s";
$ newTplItem = "
$newTplFoot = "
$Content = '';
$itemsCount = count($newsData);
$itemsCount = $itemsCount if ($itemsCount)
{
foreach ($newsData as $key => $item)
{
if ($key {
$Content .= sprintf($newTplItem, $item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
}
}
}
$header = sprintf($newTplHeader,$newsData['content'],$itemsCount);
$footer = sprintf($newTplFoot,$FuncFlag);
return $header . $Content . $footer;
}
public function reply($data)
{
if ($this->debug)
{
$this->write_log($data);
}
echo $data;
}
public function valid()
{
if ($this->checkSignature())
{
//if( $_SERVER['REQUEST_METHOD'] =='GET' )
//{
echo $_GET['echostr'];
exit;
//}
}
else
{
write_log('Authentication failed');
exit;
}
}
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$tmpArr = array($this->token, $timestamp, $nonce);
sort ($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature )
return true;
else
return false;
}
private function write_log($log)
{
//This is where you record debugging information. Please improve it for intermediate debugging
}
}
?>
WeChat interface code: weixin.php
header("Content-Type: text/html;charset=utf-8");
include_once('weixin.class.php '); //Refer to the WeChat message processing class just defined
define("TOKEN", "itwatch"); //mmhelper
define('DEBUG', false);
$weixin = new Weixin (TOKEN, DEBUG); //Instantiation
//$weixin->valid();
$weixin->getMsg();
$type = $weixin->msgtype; //Message type
$username = $weixin->msg['FromUserName']; //Which user sent you the message? This $username is encrypted by WeChat, but each user has a one-to-one correspondence
if ($type===='text')
{
//if ($weixin->msg['Content']=='Hello2BizUser')
if ($weixin->msg['Content ']=='Hello')
{ //When a WeChat user follows your account for the first time, your public account will receive a message with the content 'Hello2BizUser'
$reply = $weixin ->makeText('Welcome to the Net Vision Prestige Public Platform');
}
else
{ //Here is the text information entered by the user
$keyword = $weixin->msg[' Content']; //User's text message content
//include_once("chaxun.php"); //Text message calls query program
//$chaxun= new chaxun(DEBUG, $keyword, $username );
//$results['items'] =$chaxun->search(); //Query code
//$reply = $weixin->makeNews($results);
$ arrayCon = array(
array(
"Title"=>"Computer Learning Network",
"Description"=>"One Hundred Thousand Whys-Computer Learning Network",
"PicUrl"=> "http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/website13.jpg",
"Url"=>"http://www.why100000.com/"
),
array(
"Title"=>"Very PHP Learning Network",
"Description"=>"Large PHP Learning Sharing Community",
"PicUrl"=>"http://www. veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/php01.jpg",
"Url"=>"http://www.veryphp.cn/"
)
);
$ results = $arrayCon;
$reply = $weixin->makeNews($results);
}
}
elseif ($type==='location')
{
//The user sends location information which will be processed later
}
elseif ($type===='image')
{
//The user sends an image which will be processed later
} elseif ($type===='voice')
{
//The user sends a voice that will be processed later
}
//
$weixin->reply($reply);
?>
To verify the code of the WeChat interface, use the curl function to complete. You need to open the curl extension of PHP. Just remove the comment from //$weixin->valid(); in the weixin.php file to verify it. When finished, just comment out this sentence.
//header("Content-Type : text/html;charset=utf-8");
//Prepare data
define('TOKEN', 'itwatch');//The token you define is a private key for communication
$ echostr = 'Returning this data indicates correctness. ';
$timestamp = (string)time(); //It is an integer and must be converted to a string
$nonce = 'my-nonce';
$signature = signature(TOKEN, $timestamp , $nonce);
function signature($token, $timestamp, $nonce)
{
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
return $tmpStr;
}
//Submit
$post_data = array(
"signature=$signature",
"timestamp=$timestamp",
"nonce=$nonce",
"echostr=$echostr"
);
$post_data = implode('&',$post_data);
$url='http://www.veryphp.cn/tools/weixin/weixin.php';
$ch = curl_init( );
curl_setopt($ch, CURLOPT_URL, $url.'?'.$post_data); //Simulate GET method
ob_start();
curl_exec($ch);
$result = ob_get_contents();
ob_end_clean();
echo $result;
?>
The above core code is two files weixin.class.php and weixin.php, which I debugged Successfully, it has been deployed on my server. If you want to test, use your mobile phone WeChat to listen to the WeChat ID: itwatch, and then enter "Hello", the string will be returned: Welcome to pay attention to the Net Vision Weixin Public Platform. Just type in and a graphic message will open.
Okay, I admit that the above code is very messy because I am very sleepy and about to go to bed. But the above code does work and is a typical principle implementation test code. I hope to provide an idea to WeChat developers. After understanding it, they can write a fully functional WeChat information background management program in combination with the database. .
If you have a WeChat service account, you can develop a menu on this basis, and then call the message reply system developed based on the above code. It's actually very simple.
This is a real network communication program. It is much more interesting than writing a corporate website, inputting data, and then retrieving it in order and displaying it in pages.
Mesh-Zhang Qing
2013-12-3 ?

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
