How to develop WeChat public account in PHP
phpHow to develop WeChat public account
1. Configure related servers
(1) As follows, configure your own server IP whitelist;
(2) Start configuring the token , when configuring the token, you first need to put the ready-made code on your own server. The code contains the token number of your own settings, so that the configuration can be successful.
Note: After the following code is configured, you can delete the code from the server or change the name of index.php.
url must be a complete url, such as http://118.78.176.74/weixin/index.php
<?php /** * wechat php test * update time: 20141008 */ //define your token //下面的即是你设置的token令牌 define("TOKEN", "zj123456"); $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 (!empty($postStr)) { $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> <funcflag>0</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() { $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; } } }
2. After the configuration is ok, you can then implement related functions related to WeChat public accounts, such as automatic reply robots.
The code contains 3 parts. Of course, some of the following codes are not used by the automatic reply robot.
(1), index.php
<?php define("APPID","xxxxxxx"); define("APPSECRET","xxxxxx"); define("TOKEN","zj123456"); require("./wechat.inc.php"); $wechat = new WeChat(APPID,APPSECRET,TOKEN); $wechat->responseMsg(); ?>
(2), wechat.inc.php
<?php class WeChat { private $_appid; private $_appsecret; private $_token; public function __construct($appid, $appsecret, $token) { $this->_appid = $appid; $this->_appsecret = $appsecret; $this->_token = $token; } /** *_request():发出请求 *@curl:访问的URL *@https:安全访问协议 *@method:请求的方式,默认为get *@data:post方式请求时上传的数据 **/ private function _request($curl, $https = true, $method = 'get', $data = null, $headers = null) { $ch = curl_init(); //初始化 curl_setopt($ch, CURLOPT_URL, $curl); //设置访问的URL // curl_setopt($ch, CURLOPT_HEADER, false); //设置不需要头信息 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容,但不输出 if ($https) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服务器认证 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客户端认证 } if ($method == 'post') { curl_setopt($ch, CURLOPT_POST, true); //设置请求是POST方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST请求的数据 } $str = curl_exec($ch); //执行访问,返回结果 curl_close($ch); //关闭curl,释放资源 return $str; } /** *_getAccesstoken():获取access token **/ private function _getAccesstoken() { $file = './accesstoken'; //用于保存access token if (file_exists($file)) { //判断文件是否存在 $content = file_get_contents($file); //获取文件内容 $content = json_decode($content); //json解码 if (time() - filemtime($file) expires_in) //判断文件是否过期 { return $content->access_token; } //返回access token } $content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->_appid . "&secret=" . $this->_appsecret); //获取access token的json对象 file_put_contents($file, $content); //保存json对象到指定文件 $content = json_decode($content); //进行json解码 return $content->access_token; //返回access token } /** *_getTicket():获取ticket,用于以后换取二维码 *@expires_secords:二维码有效期(秒) *@type :二维码类型(临时或永久) *@scene:场景编号 **/ public function _getTicket($expires_secords = 604800, $type = "temp", $scene = 1) { if ($type == "temp") { //临时二维码的处理 $data = '{"expire_seconds":' . $expires_secords . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //临时二维码生成所需提交数据 return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //发出请求并获得ticket } else { //永久二维码的处理 $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //永久二维码生成所需提交数据 return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //发出请求并获得ticket } } /** *_getQRCode():获取二维码 *@expires_secords:二维码有效期(秒) *@type:二维码类型 *@scene:场景编号 **/ public function _getQRCode($expires_secords, $type, $scene) { $content = json_decode($this->_getTicket($expires_secords, $type, $scene)); //发出请求并获得ticket的json对象 $ticket = $content->ticket; //获取ticket $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket) ); //发出请求获得二维码图像 //$file = "./".$type.$scene.".jpg";// 可以将生成的二维码保存到本地,便于使用 //file_put_contents($file, $image);//保存二维码 return $image; } 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"]; //获得用户发送信息 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); switch ($postObj->MsgType) { case 'event': $this->_doEvent($postObj); break; case 'text': $this->_doText($postObj); break; case 'image': $this->_doImage($postObj); break; case 'voice': $this->_doVoice($postObj); break; case 'video': $this->_doVideo($postObj); break; case 'location': $this->_doLocation($postObj); break; default:exit; } } private function _doEvent($postObj) { //事件处理 switch ($postObj->Event) { case 'subscribe': //订阅 $this->_doSubscribe($postObj); break; case 'unsubscribe': //取消订阅 $this->_doUnsubscribe($postObj); break; default:; } } private function _doSubscribe($postObj) { $tpltext = '<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> </xml>'; $access_token = $this->_getAccesstoken(); $userInfo = $this->getUserinfo($access_token, $postObj->FromUserName); $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '欢迎您关注' . 'Geroge Zhang' . '的世界!'); //还可以保存用户的信息到数据库 echo $str; } private function _doUnsubscribe($postObj) { ; //把用户的信息从数据库中删除 } private function _doText($postObj) { $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> <funcflag>0</funcflag> </xml>"; if (!empty($keyword)) { // $data_add = "question=" . $keyword; // $appcode = "2fd264cdc7914b308e51ab986f73fb86"; // $headers = array(); // array_push($headers, "Authorization:APPCODE " . $appcode); // $contentStr = $this->_request("http://jisuznwd.market.alicloudapi.com/iqa/query?question=" . $data_add, false, "GET", '', $headers); $data_add = urlencode($keyword); $contentStr = $this->_request("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" . $data_add, false, "GET", '', ''); $contentStr = json_decode($contentStr, true); if ($contentStr['result'] == 0) { $contentStr = $contentStr['content']; } if ($keyword == "hello") { $contentStr = "你好"; } if ($keyword == "PHP") { $contentStr = "最流行的网页编程语言!"; } if ($keyword == "JAVA") { $contentStr = "较流行的网页编程语言!"; } $msgType = "text"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } exit; } private function _doImage($postObj) { $tpltext = '<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> </xml>'; $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '您发送的图片在' . $postObj->PicUrl . "。"); echo $str; } 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; } } /** * 获取用户昵称 * @param access_token 前面函数_getAccesstoken已经实现 * @param openid 即FromUserName这个参数 * url $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; * return userInfo */ public function getUserinfo($access_token, $openid) { $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN'; $userInfo = $this->_request($urlid); return $userInfo; } }
Note: If you want to obtain user information, you must have an authenticated subscription account or service account!
To sum up, put the above three files on your configured server to realize the automatic reply robot function.
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of How to develop WeChat public account in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
