


[php development] Implement WeChat public account graphic message reply and access_token (code example)
This article mainly talks about the implementation of WeChat public account graphic message reply and access_token in PHP. It has certain reference value and interested friends can learn about it.
//代码如下 <?php class IndexAction extends Action { public function __construct(){ } public function index(){ //获得参数 signature nonce token timestamp echostr $nonce = $_GET['nonce']; $token = 'imooc'; $timestamp = $_GET['timestamp']; $echostr = $_GET['echostr']; $signature = $_GET['signature']; //形成数组,然后按字典序排序 $array = array(); $array = array($nonce, $timestamp, $token); sort($array); //拼接成字符串,sha1加密 ,然后与signature进行校验 $str = sha1( implode( $array ) ); if( $str == $signature && $echostr ){ //第一次接入weixin api接口的时候 echo $echostr; exit; }else{ $this->reponseMsg(); } } // 接收事件推送并回复 public function reponseMsg(){ //1.获取到微信推送过来post数据(xml格式) $postArr = $GLOBALS['HTTP_RAW_POST_DATA']; //2.处理消息类型,并设置回复类型和内容 /*<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> </xml>*/ $postObj = simplexml_load_string( $postArr ); //$postObj->ToUserName = ''; //$postObj->FromUserName = ''; //$postObj->CreateTime = ''; //$postObj->MsgType = ''; //$postObj->Event = ''; // gh_e79a177814ed //判断该数据包是否是订阅的事件推送 if( strtolower( $postObj->MsgType) == 'event'){ //如果是关注 subscribe 事件 if( strtolower($postObj->Event == 'subscribe') ){ //回复用户消息(纯文本格式) $toUser = $postObj->FromUserName; $fromUser = $postObj->ToUserName; $time = time(); $msgType = 'text'; $content = '欢迎关注我们的微信公众账号'.$postObj->FromUserName.'-'.$postObj->ToUserName; $template = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content); echo $info; /*<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[你好]]></Content> </xml>*/ } } //当微信用户发送imooc,公众账号回复‘imooc is very good' /*<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[你好]]></Content> </xml>*/ /*if(strtolower($postObj->MsgType) == 'text'){ switch( trim($postObj->Content) ){ case 1: $content = '您输入的数字是1'; break; case 2: $content = '您输入的数字是2'; break; case 3: $content = '您输入的数字是3'; break; case 4: $content = "<a href='http://www.imooc.com'>慕课</a>"; break; case '英文': $content = 'imooc is ok'; break; } $template = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; //注意模板中的中括号 不能少 也不能多 $fromUser = $postObj->ToUserName; $toUser = $postObj->FromUserName; $time = time(); // $content = '18723180099'; $msgType = 'text'; echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content); } } */ //用户发送tuwen1关键字的时候,回复一个单图文 if( strtolower($postObj->MsgType) == 'text' && trim($postObj->Content)=='tuwen2' ){ $toUser = $postObj->FromUserName; $fromUser = $postObj->ToUserName; $arr = array( array( 'title'=>'imooc', 'description'=>"imooc is very cool", 'picUrl'=>'http://www.imooc.com/static/img/common/logo.png', 'url'=>'http://www.imooc.com', ), array( 'title'=>'hao123', 'description'=>"hao123 is very cool", 'picUrl'=>'https://www.baidu.com/img/bdlogo.png', 'url'=>'http://www.hao123.com', ), array( 'title'=>'qq', 'description'=>"qq is very cool", 'picUrl'=>'http://www.imooc.com/static/img/common/logo.png', 'url'=>'http://www.qq.com', ), ); $template = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <ArticleCount>".count($arr)."</ArticleCount> <Articles>"; foreach($arr as $k=>$v){ $template .="<item> <Title><![CDATA[".$v['title']."]]></Title> <Description><![CDATA[".$v['description']."]]></Description> <PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl> <Url><![CDATA[".$v['url']."]]></Url> </item>"; } $template .="</Articles> </xml> "; echo sprintf($template, $toUser, $fromUser, time(), 'news'); //注意:进行多图文发送时,子图文个数不能超过10个 }else{ switch( trim($postObj->Content) ){ case 1: $content = '您输入的数字是1'; break; case 2: $content = '您输入的数字是2'; break; case 3: $content = '您输入的数字是3'; break; case 4: $content = "<a href='http://www.imooc.com'>慕课</a>"; break; case '英文': $content = 'imooc is ok'; break; } $template = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; //注意模板中的中括号 不能少 也不能多 $fromUser = $postObj->ToUserName; $toUser = $postObj->FromUserName; $time = time(); // $content = '18723180099'; $msgType = 'text'; echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content); }//if end }//reponseMsg end function http_curl(){ //获取imooc //1.初始化curl $ch = curl_init(); $url = 'http://www.baidu.com'; //2.设置curl的参数 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //3.采集 $output = curl_exec($ch); //4.关闭 curl_close($ch); var_dump($output); } function getWxAccessToken(){ //1.请求url地址 $appid = 'wx08d5c2cb632bb5e4'; $appsecret = '06d3444fb9abd8d00314eb4a38ad61a8'; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; //2初始化 $ch = curl_init(); //3.设置参数 curl_setopt($ch , CURLOPT_URL, $url); curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1); //4.调用接口 $res = curl_exec($ch); //5.关闭curl curl_close( $ch ); if( curl_errno($ch) ){ var_dump( curl_error($ch) ); } $arr = json_decode($res, true); var_dump( $arr ); } function getWxServerIp(){ $accessToken = "6vOlKOh7r5uWk_ZPCl3DS36NEK93VIH9Q9tacreuxJ5WzcVc235w_9zONy75NoO11gC9P0o4FBVxwvDiEtsdX6ZRFR0Lfs_ymkb8Bf6kRfo"; $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$accessToken; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); $res = curl_exec($ch); curl_close($ch); if(curl_errno($ch)){ var_dump(curl_error($ch)); } $arr = json_decode($res,true); echo "<pre class="brush:php;toolbar:false">"; var_dump( $arr ); echo ""; } }//class end
Related tutorials:
The above is the detailed content of [php development] Implement WeChat public account graphic message reply and access_token (code example). For more information, please follow other related articles on the PHP Chinese website!

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment