搜尋
首頁後端開發php教程【php開發】實作微信公眾號圖文訊息回覆與access_token(程式碼範例)

本篇文章主要講述的是PHP實現微信公眾號圖文訊息回覆與access_token,具有一定的參考價值,有興趣的朋友可以了解一下。

 //代码如下
<?php
class IndexAction extends Action {
public function __construct(){

}
public function index(){
//获得参数 signature nonce token timestamp echostr
$nonce     = $_GET[&#39;nonce&#39;];
$token     = &#39;imooc&#39;;
$timestamp = $_GET[&#39;timestamp&#39;];
$echostr   = $_GET[&#39;echostr&#39;];
$signature = $_GET[&#39;signature&#39;];
//形成数组,然后按字典序排序
$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[&#39;HTTP_RAW_POST_DATA&#39;];
//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 = &#39;&#39;;
//$postObj->FromUserName = &#39;&#39;;
//$postObj->CreateTime = &#39;&#39;;
//$postObj->MsgType = &#39;&#39;;
//$postObj->Event = &#39;&#39;;
// gh_e79a177814ed
//判断该数据包是否是订阅的事件推送
if( strtolower( $postObj->MsgType) == &#39;event&#39;){
//如果是关注 subscribe 事件
if( strtolower($postObj->Event == &#39;subscribe&#39;) ){
//回复用户消息(纯文本格式)	
$toUser   = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time     = time();
$msgType  =  &#39;text&#39;;
$content  = &#39;欢迎关注我们的微信公众账号&#39;.$postObj->FromUserName.&#39;-&#39;.$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&#39;
/*<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>*/
/*if(strtolower($postObj->MsgType) == &#39;text&#39;){
switch( trim($postObj->Content) ){
case 1:
$content = &#39;您输入的数字是1&#39;;
break;
case 2:
$content = &#39;您输入的数字是2&#39;;
break;
case 3:
$content = &#39;您输入的数字是3&#39;;
break;
case 4:
$content = "<a href=&#39;http://www.imooc.com&#39;>慕课</a>";
break;
case &#39;英文&#39;:
$content = &#39;imooc is ok&#39;;
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  = &#39;18723180099&#39;;
$msgType  = &#39;text&#39;;
echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content);

}
}
*/
//用户发送tuwen1关键字的时候,回复一个单图文
if( strtolower($postObj->MsgType) == &#39;text&#39; && trim($postObj->Content)==&#39;tuwen2&#39; ){
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$arr = array(
array(
&#39;title&#39;=>&#39;imooc&#39;,
&#39;description&#39;=>"imooc is very cool",
&#39;picUrl&#39;=>&#39;http://www.imooc.com/static/img/common/logo.png&#39;,
&#39;url&#39;=>&#39;http://www.imooc.com&#39;,
),
array(
&#39;title&#39;=>&#39;hao123&#39;,
&#39;description&#39;=>"hao123 is very cool",
&#39;picUrl&#39;=>&#39;https://www.baidu.com/img/bdlogo.png&#39;,
&#39;url&#39;=>&#39;http://www.hao123.com&#39;,
),
array(
&#39;title&#39;=>&#39;qq&#39;,
&#39;description&#39;=>"qq is very cool",
&#39;picUrl&#39;=>&#39;http://www.imooc.com/static/img/common/logo.png&#39;,
&#39;url&#39;=>&#39;http://www.qq.com&#39;,
),
);
$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[&#39;title&#39;]."]]></Title> 
<Description><![CDATA[".$v[&#39;description&#39;]."]]></Description>
<PicUrl><![CDATA[".$v[&#39;picUrl&#39;]."]]></PicUrl>
<Url><![CDATA[".$v[&#39;url&#39;]."]]></Url>
</item>";
}

$template .="</Articles>
</xml> ";
echo sprintf($template, $toUser, $fromUser, time(), &#39;news&#39;);
//注意:进行多图文发送时,子图文个数不能超过10个
}else{
switch( trim($postObj->Content) ){
case 1:
$content = &#39;您输入的数字是1&#39;;
break;
case 2:
$content = &#39;您输入的数字是2&#39;;
break;
case 3:
$content = &#39;您输入的数字是3&#39;;
break;
case 4:
$content = "<a href=&#39;http://www.imooc.com&#39;>慕课</a>";
break;
case &#39;英文&#39;:
$content = &#39;imooc is ok&#39;;
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  = &#39;18723180099&#39;;
$msgType  = &#39;text&#39;;
echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content);

}//if end
}//reponseMsg end
function http_curl(){
//获取imooc
//1.初始化curl
$ch = curl_init();
$url = &#39;http://www.baidu.com&#39;;
//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 = &#39;wx08d5c2cb632bb5e4&#39;;
$appsecret =  &#39;06d3444fb9abd8d00314eb4a38ad61a8&#39;;
$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

相關教學:

PHP影片教學

#微信小程式影片教學

###################################################

以上是【php開發】實作微信公眾號圖文訊息回覆與access_token(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:博客园。如有侵權,請聯絡admin@php.cn刪除
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。