Home Backend Development PHP Tutorial Simulation test of WeChat interface and WeChat development test code_PHP tutorial

Simulation test of WeChat interface and WeChat development test code_PHP tutorial

Jul 13, 2016 pm 05:18 PM
interface simulation test

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 = "
msg['FromUserName']}]]>
msg['ToUserName']}]]>
{$CreateTime}


%s
";
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 = "
msg['FromUserName']}]]>
msg['ToUserName']}]]>
{$CreateTime}


%s";
$ newTplItem = "




";
$newTplFoot = "
%s
";
$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 ?

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621644.htmlTechArticleTo become a developer of a WeChat public account (subscription account or service account), you need to verify the interface first. This can be done in Set up after logging into WeChat https://mp.weixin.qq.com background. But I find it troublesome...
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)

What do you think of furmark? - How is furmark considered qualified? What do you think of furmark? - How is furmark considered qualified? Mar 19, 2024 am 09:25 AM

What do you think of furmark? 1. Set the "Run Mode" and "Display Mode" in the main interface, and also adjust the "Test Mode" and click the "Start" button. 2. After waiting for a while, you will see the test results, including various parameters of the graphics card. How is furmark qualified? 1. Use a furmark baking machine and check the results for about half an hour. It basically hovers around 85 degrees, with a peak value of 87 degrees and room temperature of 19 degrees. Large chassis, 5 chassis fan ports, two on the front, two on the top, and one on the rear, but only one fan is installed. All accessories are not overclocked. 2. Under normal circumstances, the normal temperature of the graphics card should be between "30-85℃". 3. Even in summer when the ambient temperature is too high, the normal temperature is "50-85℃

What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard Mar 12, 2024 pm 04:34 PM

When we assemble the computer, although the installation process is simple, we often encounter problems in the wiring. Often, users mistakenly plug the power supply line of the CPU radiator into the SYS_FAN. Although the fan can rotate, it may not work when the computer is turned on. There will be an F1 error "CPUFanError", which also causes the CPU cooler to be unable to adjust the speed intelligently. Let's share the common knowledge about the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard. Popular science on the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard 1. CPU_FANCPU_FAN is a dedicated interface for the CPU radiator and works at 12V

Common programming paradigms and design patterns in Go language Common programming paradigms and design patterns in Go language Mar 04, 2024 pm 06:06 PM

As a modern and efficient programming language, Go language has rich programming paradigms and design patterns that can help developers write high-quality, maintainable code. This article will introduce common programming paradigms and design patterns in the Go language and provide specific code examples. 1. Object-oriented programming In the Go language, you can use structures and methods to implement object-oriented programming. By defining a structure and binding methods to the structure, the object-oriented features of data encapsulation and behavior binding can be achieved. packagemaini

Join a new Xianxia adventure! 'Zhu Xian 2' 'Wuwei Test' pre-download is now available Join a new Xianxia adventure! 'Zhu Xian 2' 'Wuwei Test' pre-download is now available Apr 22, 2024 pm 12:50 PM

The "Inaction Test" of the new fantasy fairy MMORPG "Zhu Xian 2" will be launched on April 23. What kind of new fairy adventure story will happen in Zhu Xian Continent thousands of years after the original work? The Six Realm Immortal World, a full-time immortal academy, a free immortal life, and all kinds of fun in the immortal world are waiting for the immortal friends to explore in person! The "Wuwei Test" pre-download is now open. Fairy friends can go to the official website to download. You cannot log in to the game server before the server is launched. The activation code can be used after the pre-download and installation is completed. "Zhu Xian 2" "Inaction Test" opening hours: April 23 10:00 - May 6 23:59 The new fairy adventure chapter of the orthodox sequel to Zhu Xian "Zhu Xian 2" is based on the "Zhu Xian" novel as a blueprint. Based on the world view of the original work, the game background is set

The new king of domestic FPS! 'Operation Delta' Battlefield Exceeds Expectations The new king of domestic FPS! 'Operation Delta' Battlefield Exceeds Expectations Mar 07, 2024 am 09:37 AM

"Operation Delta" will launch a large-scale PC test called "Codename: ZERO" today (March 7). Last weekend, this game held an offline flash mob experience event in Shanghai, and 17173 was also fortunate to be invited to participate. This test is only more than four months away from the last time, which makes us curious, what new highlights and surprises will "Operation Delta" bring in such a short period of time? More than four months ago, I experienced "Operation Delta" in an offline tasting session and the first beta version. At that time, the game only opened the "Dangerous Action" mode. However, Operation Delta was already impressive for its time. In the context of major manufacturers flocking to the mobile game market, such an FPS that is comparable to international standards

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

PHP Jenkins 101: The only way to get started with CI/CD PHP Jenkins 101: The only way to get started with CI/CD Mar 09, 2024 am 10:28 AM

Introduction Continuous integration (CI) and continuous deployment (CD) are key practices in modern software development that help teams deliver high-quality software faster and more reliably. Jenkins is a popular open source CI/CD tool that automates the build, test and deployment process. This article explains how to set up a CI/CD pipeline with Jenkins using PHP. Set up Jenkins Install Jenkins: Download and install Jenkins from the official Jenkins website. Create project: Create a new project from the Jenkins dashboard and name it to match your php project. Configure source control: Configure your PHP project's git repository as Jenkin

What are the differences between function testing and coverage in different languages? What are the differences between function testing and coverage in different languages? Apr 27, 2024 am 11:30 AM

Functional testing verifies function functionality through black-box and white-box testing, while code coverage measures the portion of code covered by test cases. Different languages ​​(such as Python and Java) have different testing frameworks, coverage tools and features. Practical cases show how to use Python's Unittest and Coverage and Java's JUnit and JaCoCo for function testing and coverage evaluation.

See all articles