my_class_sample.md 5.31 KB

PHP自定义类示例(Weixin消息解析类)

/**
 * Created by Qingger. 
 * User: jsspf
 * Date: 2017/3/24
 * Time: 10:50
 */

namespace App\Service;

use App\Exception\TPException;
use App\Library\VarDefines\GlobalErrCode;

/**
 * 微信公众号消息的接收与回复
 * @desc : 消息加解密指引参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318611&lang=zh_CN
 * Class WXMPEventMessageParser
 * @package App\Services\WeixinFunc
 */
class WeixinMPEventMessageParser extends WeixinBaseFuncService
{

    /**
     * @var object
     * 接收消息的消息体结构 (text | image | voice | video | shortvideo | location | link)
     */
    private $_messageReceiveBody = null;

    /**
     * @var string
     * 接收消息的发送方帐号
     */
    private $_messageReceiveFrom = null;

    /**
     * @var string
     * 接收消息的接收方帐号
     */
    private $_messageReceiveTo   = null;

    /**
     * @var string
     * 接收消息的消息体类型 (text | image | voice | video | shortvideo | location | link)
     */
    private $_messageReceiveType = null;


    /**
     * @var string
     * 接收消息时,Request请求中的nonce信息
     */
    private $_messageNonce = '';

    /**
     * @var WXBizMsgCrypt
     * 微信消息体加解密对象
     */
    private $_wxBizMsgCrypt = null;

   /**
     * @var array
     * 公众号消息回复的模板
     */
    private $_replyMessageTemplate = [
        // 文本消息的回复模板
        'text'  => "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>",

        // 图片消息的回复模板
        'image' => "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image><MediaId><![CDATA[%s]]></MediaId></Image>
                    </xml>",
    ];


    public function __construct($tpSuiteName,$messageNonce='')
    {
        parent::__construct();
        $this->_messageNonce     = $messageNonce;
        $this->_wxBizMsgCrypt = new WXBizMsgCrypt(
            $this->getWxTpConfigParser()->getConfigToken($tpSuiteName),
            $this->getWxTpConfigParser()->getConfigEncodingAesKey($tpSuiteName),
            $this->getWxTpConfigParser()->getConfigId($tpSuiteName)
        );
    }

    /**
     * 对消息体进行微信的加密
     * @param $replyMsgStr
     * @return string
     */
    private function _encryptMessage($replyMsgStr) {
        $replyMessageEncrypt = '';
        $this->_wxBizMsgCrypt->encryptMsg($replyMsgStr,time(),$this->_messageNonce,$replyMessageEncrypt);
        return $replyMessageEncrypt;
    }

    /**
     * 生成文本消息的回复结构
     * @param $content
     * @return string
     */
    public function textMessageReply($content) {
        $replyMessageType = 'text';
        $replyMsgStr = sprintf($this->_replyMessageTemplate[$replyMessageType],
            $this->_messageReceiveFrom,
            $this->_messageReceiveTo,
            time(),
            $content);
        return $this->_encryptMessage($replyMsgStr);
    }

    /**
     * 生成图片消息的回复
     * @param $imageMediaId
     * @return string
     */
    public function imageMessageReply($imageMediaId) {
        $replyMessageType = 'image';
        $replyMsgStr = sprintf($this->_replyMessageTemplate[$replyMessageType],
            $this->_messageReceiveFrom,
            $this->_messageReceiveTo,
            time(),
            $imageMediaId);
        return $this->_encryptMessage($replyMsgStr);
    }

    /**
     * Todo : 需要实现,使用XML对象操作字符串模板
     * 生成音乐消息的回复
     * @param array $musicInfo
     * [
     *      'title'         : 标题 / 可选
     *      'description'   : 描述 / 可选
     *      'musicURL'      : 音乐链接 / 可选
     *      'hqMusicUrl'    : 高质量音乐链接,WIFI环境优先使用该链接播放音乐 / 可选
     *      'ThumbMediaId'  : 缩略图的媒体id,通过素材管理接口上传多媒体文件,得到的id / 可选
     *  ]
     * @throws TPException
     * @return string
     */
    public function musicMessageReply(array $musicInfo) {
        throw new TPException('Music Message Reply Not Support',GlobalErrCode::ERR_FUNCTION_NOT_IMPLEMENT);
    }

    /**
     * 解析Weixin Message消息,并根据相应的消息,进行回复
     * @desc 具体解密参考:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318479&lang=zh_CN
     * @param $messageEventObj
     * @param Closure $doEvent
     * @return mixed
     * @throws TPException
     */
    public function parseEvent($messageEventObj,Closure $doEvent) {
        if(isset($messageEventObj->MsgType)) {
            $this->_messageReceiveBody   = $messageEventObj;
            $this->_messageReceiveFrom   = isset($messageEventObj->FromUserName)?$messageEventObj->FromUserName:null;
            $this->_messageReceiveTo     = isset($messageEventObj->ToUserName)?$messageEventObj->ToUserName:null;
            $this->_messageReceiveType   = $messageEventObj->MsgType;

            $messageReply = $doEvent($messageEventObj);

            return $messageReply;
        } else {
            throw new TPException('MP Message Body Parse Error',GlobalErrCode::ERR_WEIXIN_MESSAGE_INFO_ERROR);
        }


}