EaglePHP 是一款輕量級 PHP 框架。本文分享一個封裝微信 5.0 所有核心接口的 WeixinChat 類,涵蓋基礎接口、自定義菜單、高級接口等 12 大功能模塊,適用於 Windows/Linux 環境。
<?php
class WeixinChat {
private $token, $appid, $appsecret, $access_token;
private $_receive = array(), $_reply = '';
private $errCode = '', $errMsg = '';
// 微信 API 端點常量
const CONNECT_OAUTH_AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
const SNS_OAUTH_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
const SNS_OAUTH_REFRESH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?';
const SHOW_QRCODE_URL = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?';
const SNS_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
// ... 菜單、用戶、分組、客服、二維碼等接口常量
public function __construct($options) {
$this->token = isset($options['token']) ? $options['token'] : '';
$this->appid = isset($options['appid']) ? $options['appid'] : '';
$this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : '';
}
// 接收消息入口
public function getRev() {
$postStr = file_get_contents('php://input');
if ($postStr) {
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
}
return $this;
}
// 消息獲取器示例
public function getRevText() {
if (isset($this->_receive['Content'])) return trim($this->_receive['Content']);
elseif (isset($this->_receive['Recognition'])) return trim($this->_receive['Recognition']);
else return false;
}
// ... 其他 getRev* 方法省略
}
?>
$options = array(
'token' => 'YOUR_TOKEN',
'appid' => 'YOUR_APPID',
'appsecret' => 'YOUR_APPSECRET'
);
$weixin = new WeixinChat($options);
$weixin->getRev(); // 解析微信推送的 XML
$msgType = $weixin->getRevType();
$content = $weixin->getRevText();
$fromUser = $weixin->getRevFrom();
// 業務邏輯處理...
$weixin->replyText('收到:' . $content); // 假設有回復方法