Simulation test of WeChat interface and WeChat development test code_PHP tutorial

WBOY
Release: 2016-07-13 17:18:38
Original
835 people have browsed it

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...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!