萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

基於 EaglePHP 框架的微信 5.0 API 開發完整指南

項目背景

EaglePHP 是一款輕量級 PHP 框架。本文分享一個封裝微信 5.0 所有核心接口的 WeixinChat 類,涵蓋基礎接口、自定義菜單、高級接口等 12 大功能模塊,適用於 Windows/Linux 環境。

功能清單

  1. 接收用戶消息(文本、圖片、語音、視頻、地理位置、鏈接、事件)
  2. 向用戶回復消息(文本、圖文、音樂等)
  3. 接收事件推送(關注、掃碼、地理位置上報等)
  4. 會話界面自定義菜單(創建、查詢、刪除)
  5. 語音識別(需服務號高級接口權限)
  6. 客服接口(發送客服消息)
  7. OAuth2.0 網頁授權(獲取 code、access_token、用戶信息)
  8. 生成帶參數二維碼(創建 ticket、換取圖片)
  9. 獲取用戶地理位置
  10. 獲取用戶基本信息
  11. 獲取關注者列表
  12. 用戶分組管理(查詢、創建、修改、移動用戶)

核心類結構

<?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); // 假設有回復方法

注意事項

  • 需在微信公眾平台配置服務器 URL、Token、EncodingAESKey
  • 高級接口(客服、OAuth、二維碼等)需認證服務號
  • access_token 建議緩存(如 Redis)避免頻繁請求
  • 生產環境請加入簽名驗證、異常捕獲與日誌記錄
copyright © 萬盛學電腦網 all rights reserved