php网站怎么对接微信群,PHP对接微信公众平台消息接口开发流程教程

PHP(外文名:PHP: Hypertext

Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,利于学习,使用广泛,主要适用于Web开发领域。微信公众平台也运用到了,今天小编就来讲一讲PHP对接微信公众平台消息接口开发流程教程,供大家参考一下。

b1186b05248222ce153497adf8c8ceb1.png

一、写好接口程序

在你的服务器上上传好一个接口程序文件,如http://www.yourdomain.com/weixin.php 内容如下:

复制代码 代码如下:

define("TOKEN", "weixin");//自己定义的token 就是个通信的私钥

$wechatObj = new wechatCallbackapiTest();

$wechatObj->valid();

//$wechatObj->responseMsg();

class wechatCallbackapiTest

{

public function valid()

{

$echoStr = $_GET["echostr"];

if($this->checkSignature()){

echo $echoStr;

exit;

}

}

public function responseMsg()

{

$postStr = $GLOBALS["HTTP_RAW_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 = "

%s

0

";

if(!empty( $keyword ))

{

$msgType = "text";

$contentStr = '你好啊,屌丝';

$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,

$contentStr);

echo $resultStr;

}else{

echo '咋不说哈呢';

}

}else {

echo '咋不说哈呢';

exit;

}

}

private function checkSignature()

{

$signature = $_GET["signature"];

$timestamp = $_GET["timestamp"];

$nonce = $_GET["nonce"];

$token =TOKEN;

$tmpArr = array($token, $timestamp, $nonce);

sort($tmpArr);

$tmpStr = implode( $tmpArr );

$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){

return true;

}else{

return false;

}

}

}

?>

二、配置微信公众平台回复接口

设置回复接口,填好URL和Token(url填上面的http://www.yourdomain.com/weixin.php,token必须跟上面程序里面定义的Token一致)

39e419f6479130635f1976e32741a691.png

三、验证接口

用自己的个人微信关注下你的公众账号,给这个账号发一条消息过去,收到原样的消息返回,即验证成功了。

四、开始自定义回复

注释掉$wechatObj->valid(); 这行,同时去掉//$wechatObj->responseMsg();这行的注释。

你可以修改responseMsg函数里面的代码,根据用户的消息类型('text','image','location')和消息内容来回复用户不同的内容。

消息接口就可以使用了,发个消息试试看吧?

1.封装weixin.class.php

由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处理。

我们就考虑在这个基础上做一次封装,weixin.class.php,代码如下:

复制代码 代码如下:

class Weixin

{

public $token = '';//token

public $debug = false;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据

public $setFlag = false;

public $msgtype = 'text'; //('text','image','location')

public $msg = array();

public function __construct($token,$debug)

{

$this->token = $token;

$this->debug = $debug;

}

//获得用户发过来的消息(消息内容和消息类型 )

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']);

}

}

//回复文本消息

public function makeText($text='')

{

$CreateTime = time();

$FuncFlag = $this->setFlag ? 1 : 0;

$textTpl = "

msg['FromUserName']}]]>

msg['ToUserName']}]]>

{$CreateTime}

1

]>

%s

";

return sprintf($textTpl,$text,$FuncFlag);

}

//根据数组参数回复图文消息

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['items']);

$itemsCount = $itemsCount < 10 ? $itemsCount :

10;//微信公众平台图文回复的消息一次最多10条

if ($itemsCount) {

foreach ($newsData['items'] as $key => $item) {

if ($key<=9) {

$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('认证失败');

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){

//这里是你记录调试信息的地方 请自行完善 以便中间调试

}

}

?>

2.调用weixin.class.php

把你的微信公众平台主接口文件(如前面定义的http://www.yourdomain.com/weixin.php)中,修改代码为:

复制代码 代码如下:

include_once('weixin.class.php');//引用刚定义的微信消息处理类

define("TOKEN", "mmhelper");

define('DEBUG', true);

$weixin = new Weixin(TOKEN,DEBUG);//实例化

$weixin->getMsg();

$type = $weixin->msgtype;//消息类型

$username =

$weixin->msg['FromUserName'];//哪个用户给你发的消息,这个$username是微信加密之后的,但是每个用户都是一一对应的

if ($type==='text') {

if ($weixin->msg['Content']=='Hello2BizUser')

{//微信用户第一次关注你的账号的时候,你的公众账号就会受到一条内容为'Hello2BizUser'的消息

$reply = $weixin->makeText('欢迎你关注哦,屌丝');

}else{//这里就是用户输入了文本信息

$keyword = $weixin->msg['Content']; //用户的文本消息内容

include_once("chaxun.php");//文本消息 调用查询程序

$chaxun= new chaxun(DEBUG,$keyword,$username);

$results['items'] =$chaxun->search();//查询的代码

$reply = $weixin->makeNews($results);

}

}elseif ($type==='location') {

//用户发送的是位置信息 稍后的文章中会处理

}elseif ($type==='image') {

//用户发送的是图片 稍后的文章中会处理

}elseif ($type==='voice') {

//用户发送的是声音 稍后的文章中会处理

}

$weixin->reply($reply);

?>

3.查询代码

还需要将数据库里面的查询结果格式化为特定的形式

复制代码 代码如下:

public function search(){

$record=array(); //定义返回结果的数组

$list = $this->search($this->keyword);//普通的根据关键词查询数据库的操作 代码就不用分享了

if(is_array($list)&&!empty($list)){

foreach($list as $msg){

$record[]=array(//以下代码,将数据库中查询返回的数组格式化为微信返回消息能接收的数组形式,即title、description、picurl、url

详见微信官方的文档描述

'title' =>$msg['title'],

'description' =>$msg['discription'],

'picurl' => $msg['pic_url'],

'url' =>$msg['url']

);

}

}

return $record;

}

?>

以上就是小编精心准备的PHP对接微信公众平台消息接口开发流程教程的全部内容,更多更详细关于微信开发接口的文章,请持续关注微信公众号素材网。

更多推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对接微信公众号模板消息接口,需要进行以下步骤: 1. 在微信公众平台上创建模板消息,获取模板 ID 和模板消息中需要填充的关键词。 2. 在 PHP 代码中编写发送模板消息的代码,包括获取 access_token 和发送模板消息。 3. 在用户触发某些事件时,调用 PHP 发送模板消息的代码。 以下是一个简单的 PHP 示例代码: ```php // 获取 access_token function getAccessToken($appID, $appSecret) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appID}&secret={$appSecret}"; $result = file_get_contents($url); $json = json_decode($result, true); if (isset($json['access_token'])) { return $json['access_token']; } else { return false; } } // 发送模板消息 function sendTemplateMessage($accessToken, $openID, $templateID, $data, $url = '') { $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}"; $data = [ 'touser' => $openID, 'template_id' => $templateID, 'url' => $url, 'data' => $data ]; $data = json_encode($data, JSON_UNESCAPED_UNICODE); $result = http_post_data($url, $data); $json = json_decode($result, true); if (isset($json['errcode']) && $json['errcode'] == 0) { return true; } else { return false; } } // 发送 POST 请求 function http_post_data($url, $data_string) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); ob_start(); curl_exec($ch); $result = ob_get_contents(); ob_end_clean(); curl_close($ch); return $result; } // 示例代码 $appID = 'your-app-id'; $appSecret = 'your-app-secret'; $accessToken = getAccessToken($appID, $appSecret); $openID = 'your-open-id'; $templateID = 'your-template-id'; $data = [ 'first' => ['value' => 'Hello World!', 'color' => '#173177'], 'keyword1' => ['value' => 'value1', 'color' => '#173177'], 'keyword2' => ['value' => 'value2', 'color' => '#173177'], 'remark' => ['value' => 'This is a remark.', 'color' => '#173177'] ]; $url = 'http://example.com'; $result = sendTemplateMessage($accessToken, $openID, $templateID, $data, $url); if ($result) { echo '发送成功!'; } else { echo '发送失败!'; } ``` 请注意,以上代码仅作为示例,需要根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值