Skip to content
This repository has been archived by the owner on Dec 15, 2020. It is now read-only.

API文档

王辰 edited this page Jan 9, 2014 · 3 revisions

介绍

本文详细Wechat Robot使用,包括如下内容

  • 获取用户消息及相关信息
  • 发送消息(文本消息、图文消息、图片消息等)
  • 响应用户消息(onText()onSubscribe()等)
  • 设置调试模式

用法

WechatRobot类继承了Wechat类(wechat.php文件中)
通过在WechatRobot中重写 onSubscribe() 等方法响应关注等请求:

class WechatRobot extends Wechat {
  protected function onSubscribe() {} // 用户关注
  protected function onUnsubscribe() {} // 用户取消关注

  protected function onText() {   // 收到文本消息

  }

  protected function onImage() {} // 收到图片消息
  protected function onLocation() {} // 收到地理位置消息
  protected function onLink() {} // 收到链接消息
  protected function onUnknown() {} // 收到未知类型消息
}

使用 getRequest() 可以获取本次请求中的参数(不区分大小写):

$this->getRequest();           // 无参数时,返回包含所有参数的数组

$this->getRequest('msgtype');  // 有参数且参数存在时,返回该参数的值

$this->getRequest('ghost');    // 有参数但参数不存在时,返回 NULL

所有请求均包含:

ToUserName    接收方帐号(该公众号ID)
FromUserName  发送方帐号(代表用户的唯一标识)
CreateTime    消息创建时间(时间戳)
MsgId         消息ID(64位整型)

文本消息请求:

MsgType  text
Content  文本消息内容

图片消息请求:

MsgType  image
PicUrl   图片链接

地理位置消息请求:

MsgType     location
Location_X  地理位置纬度
Location_Y  地理位置经度
Scale       地图缩放大小
Label       地理位置信息

链接消息请求:

MsgType      link
Title        消息标题
Description  消息描述
Url          消息链接

事件推送:

MsgType   event
Event     事件类型
EventKey  事件 Key 值,与自定义菜单接口中 Key 值对应

其中,事件类型 Event 的值包括以下几种:

subscribe    关注
unsubscribe  取消关注
CLICK        自定义菜单点击事件(未验证)

使用 responseText() 方法回复文本消息:

$this->responseText(
  $content,  // 消息内容
  $funcFlag  // 可选参数(默认为0),设为1时星标刚才收到的消息
);

使用 responseMusic() 方法回复音乐消息:

$this->responseMusic(
  $title,        // 音乐标题
  $description,  // 音乐描述
  $musicUrl,     // 音乐链接
  $hqMusicUrl,   // 高质量音乐链接,Wi-Fi 环境下优先使用
  $funcFlag      // 可选参数,默认为0,设为1时星标刚才收到的消息
);

使用 responseNews() 方法回复图文消息:

$this->responseNews(
  $items,    // 由单条图文消息类型 NewsResponseItem() 组成的数组
  $funcFlag  // 可选参数,默认为0,设为1时星标刚才收到的消息
)

其中单条图文消息类型 NewsResponseItem() 格式如下:

$items[] = new NewsResponseItem(
  $title,        // 图文消息标题
  $description,  // 图文消息描述
  $picUrl,       // 图片链接
  $url           // 点击图文消息跳转链接
);

构造函数

Wechat类得构造函数接受两个参数
第一个参数是token,需要和微信后台设置相同
第二个参数是debug选项,如果debug设为true(默认false)可将错误通过文本返回

Clone this wiki locally