欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP封装的微信公众平台接口开发操作类完整示例

程序员文章站 2022-05-28 11:08:27
本文实例讲述了php封装的微信公众平台接口开发操作类。分享给大家供大家参考,具体如下: 示例调用 index.php

本文实例讲述了php封装的微信公众平台接口开发操作类。分享给大家供大家参考,具体如下:

示例调用 index.php

<?php
/**
* author: 惹妹子生气了
* date: 2017-08-10
*/
class mpweixin
{
  public $config;
  public $class_obj;
  public $is_check_signature = false;
  public function __construct()
  {
    //获取配置
    $this->config = array('appid'=>'dfdfdfdfdf', 'secret'=>'343434343434');
    $echostr = isset($_get['echostr']) ? $_get['echostr'] : ''; // 是否来自于微信的服务器配置验证
    if ($echostr) {
      $this->is_check_signature = true;
    }else{
      $this->is_check_signature = false;
      include_once "mpweixin.class.php";
      $this->class_obj = new mpweixin($this->config); //实例化对应的插件
    }
  }
  /**
   * 服务器地址(用户消息和开发者需要的事件推送,会被转发到该url中)
   */
  public function index()
  {
    if ($this->is_check_signature) {
      $this->valid();
    }else{
      $this->class_obj->responsemsg();
    }
  }
  /**
   * 开发者对签名(即signature)的效验,来判断此条消息的真实性
   */
  public function valid()
  {
    $echostr = $this->checksignature();
    if($echostr){
      header('content-type:text');
      exit($echostr);
    }
  }
  /**
  * 验证是否来自于微信
  * @return [type] [description]
  */
  public function checksignature()
  {
    //微信会发送4个参数到我们的服务器后台 签名 时间戳 随机字符串 随机数
    $signature = $_get['signature']; // 签名
    $timestamp = $_get['timestamp']; // 时间戳
    $echostr = $_get['echostr']; // 随机字符串
    $nonce = $_get['nonce']; // 随机数
    if ($signature && $timestamp && $echostr && $nonce) {
      // 微信公众号基本配置中的token
      $token = token;
      //将token、timestamp、nonce按字典序排序
      $tmparr = array($token, $timestamp, $nonce);
      sort($tmparr, sort_string);
      // 将三个参数字符串拼接成一个字符串进行sha1加密
      $tmpstr = implode($tmparr);
      $tmpstr = sha1($tmpstr);
      // 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
      if($tmpstr == $signature){
        return $echostr;
      } else {
        return false;
      }
    }
  }
}
?>

php类文件 mpweixin.class.php

<?php
/*
* 微信公众号插件
* 开发者模式,请先注册微信开放平台账号,然后启动开发模式
*/
class mpweixin{
  public $appid;
  public $secret;
  public function __construct($config){
    $this->appid = $config['appid'];
    $this->secret = $config['secret'];
  }
  /* ----------------------------------响应----------------------------- */
  /**
   * 响应消息
   */
  public function responsemsg()
  {
    $poststr = file_get_contents("php://input");
    if (!empty($poststr)){
      $this->logger("r \r\n".$poststr);
      $postobj = simplexml_load_string($poststr, 'simplexmlelement', libxml_nocdata);
      $rx_type = trim($postobj->msgtype);
      switch ($rx_type)
      {
        // 事件
        case "event":
          $result = $this->receiveevent($postobj);
          break;
        // 文本
        case "text":
          if (strstr($postobj->content, "第三方")){
            $result = $this->relaypart3("http://www.fangbei.org/test.php".'?'.$_server['uery_string';], $poststr);
          }else{
            $result = $this->receivetext($postobj);
          }
          break;
        // 图片
        case "image":
          $result = $this->receiveimage($postobj);
          break;
        // 地理位置
        case "location":
          $result = $this->receivelocation($postobj);
          break;
        // 语音
        case "voice":
          $result = $this->receivevoice($postobj);
          break;
        // 视频
        case "video":
          $result = $this->receivevideo($postobj);
          break;
        // 链接
        case "link":
          $result = $this->receivelink($postobj);
          break;
        default:
          $result = "unknown msg type: ".$rx_type;
          break;
      }
      $this->logger("t \r\n".$result);
      echo $result;
    }else {
      echo "";
      exit;
    }
  }
  /* ----------------------------------接收----------------------------- */
  /**
   * 接收事件消息
   */
  private function receiveevent($object)
  {
    $content = "";
    switch ($object->event)
    {
      // 关注时的事件推送
      case "subscribe":
        $content = "欢迎关注方倍工作室";
        $content .= (!empty($object->eventkey)) ? ("\n来自二维码场景".str_replace("qrscene_","",$object->eventkey)) : "";
        break;
      // 取消关注事件
      case "unsubscribe":
        $content = "取消关注";
        break;
      // 点击菜单拉取消息时的事件推送
      case "click":
        switch ($object->eventkey)
        {
          case "company":
            $content = array();
            $content[] = array("title"=>"方倍工作室", "description"=>"", "picurl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg";, "url" =>"http://m.cnblogs.com/?u=txw1958";);
            break;
          default:
            $content = "点击菜单:".$object->eventkey;
            break;
        }
        break;
      // 点击菜单跳转链接时的事件推送
      case "view":
        $content = "跳转链接 ".$object->eventkey;
        break;
      // 扫描带参数二维码场景,用户已关注时的事件推送
      case "scan":
        $content = "扫描场景 ".$object->eventkey;
        break;
      // 上报地理位置事件
      case "location":
        $content = "上传位置:纬度 ".$object->latitude.";经度 ".$object->longitude;
        break;
      // 扫码推事件且弹出“消息接收中”提示框的事件推送
      case "scancode_waitmsg":
        if ($object->scancodeinfo->scantype == "qrcode"){
          $content = "扫码带提示:类型 二维码 结果:".$object->scancodeinfo->scanresult;
        }else if ($object->scancodeinfo->scantype == "barcode"){
          $codeinfo = explode(",",strval($object->scancodeinfo->scanresult));
          $codevalue = $codeinfo[1];
          $content = "扫码带提示:类型 条形码 结果:".$codevalue;
        }else{
          $content = "扫码带提示:类型 ".$object->scancodeinfo->scantype." 结果:".$object->scancodeinfo->scanresult;
        }
        break;
      // 扫码推事件的事件推送
      case "scancode_push":
        $content = "扫码推事件";
        break;
      // 弹出系统拍照发图的事件推送
      case "pic_sysphoto":
        $content = "系统拍照";
        break;
      // 弹出微信相册发图器的事件推送
      case "pic_weixin":
        $content = "相册发图:数量 ".$object->sendpicsinfo->count;
        break;
      // 弹出拍照或者相册发图的事件推送
      case "pic_photo_or_album":
        $content = "拍照或者相册:数量 ".$object->sendpicsinfo->count;
        break;
      // 弹出地理位置选择器的事件推送
      case "location_select":
        $content = "发送位置:标签 ".$object->sendlocationinfo->label;
        break;
      default:
        $content = "receive a new event: ".$object->event;
        break;
    }
    if(is_array($content)){
      if (isset($content[0]['picurl'])){
        $result = $this->transmitnews($object, $content);
      }else if (isset($content['musicurl'])){
        $result = $this->transmitmusic($object, $content);
      }
    }else{
      $result = $this->transmittext($object, $content);
    }
    return $result;
  }
  /**
   * 接收文本消息
   */
  private function receivetext($object)
  {
    $keyword = trim($object->content);
    //多客服人工回复模式
    if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){
      $result = $this->transmitservice($object);
      return $result;
    }
    //自动回复模式
    if (strstr($keyword, "文本")){
      $content = "这是个文本消息";
    }else if (strstr($keyword, "表情")){
      $content = "中国:".$this->bytes_to_emoji(0x1f1e8).$this->bytes_to_emoji(0x1f1f3)."\n仙人掌:".$this->bytes_to_emoji(0x1f335);
    }else if (strstr($keyword, "单图文")){
      $content = array();
      $content[] = array("title"=>"单图文标题", "description"=>"单图文内容", "picurl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg";, "url" =>"http://m.cnblogs.com/?u=txw1958";);
    }else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){
      $content = array();
      $content[] = array("title"=>"多图文1标题", "description"=>"", "picurl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg";, "url" =>"http://m.cnblogs.com/?u=txw1958";);
      $content[] = array("title"=>"多图文2标题", "description"=>"", "picurl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg";, "url" =>"http://m.cnblogs.com/?u=txw1958";);
      $content[] = array("title"=>"多图文3标题", "description"=>"", "picurl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg";, "url" =>"http://m.cnblogs.com/?u=txw1958";);
    }else if (strstr($keyword, "音乐")){
      $content = array();
      $content = array("title"=>"最炫民族风", "description"=>"歌手:凤凰传奇", "musicurl"=>"http://121.199.4.61/music/zxmzf.mp3";, "hqmusicurl"=>"http://121.199.4.61/music/zxmzf.mp3";);
    }else{
      $content = date("y-m-d h:i:s",time())."\nopenid:".$object->fromusername."\n技术支持 方倍工作室";
    }
    if(is_array($content)){
      if (isset($content[0])){
        $result = $this->transmitnews($object, $content);
      }else if (isset($content['musicurl'])){
        $result = $this->transmitmusic($object, $content);
      }
    }else{
      $result = $this->transmittext($object, $content);
    }
    return $result;
  }
  /**
   * 接收图片消息
   */
  private function receiveimage($object)
  {
    $content = array("mediaid"=>$object->mediaid);
    $result = $this->transmitimage($object, $content);
    return $result;
  }
  /**
   * 接收位置消息
   */
  private function receivelocation($object)
  {
    $content = "你发送的是位置,经度为:".$object->location_y.";纬度为:".$object->location_x.";缩放级别为:".$object->scale.";位置为:".$object->label;
    $result = $this->transmittext($object, $content);
    return $result;
  }
  /**
   * 接收语音消息
   */
  private function receivevoice($object)
  {
    if (isset($object->recognition) && !empty($object->recognition)){
      $content = "你刚才说的是:".$object->recognition;
      $result = $this->transmittext($object, $content);
    }else{
      $content = array("mediaid"=>$object->mediaid);
      $result = $this->transmitvoice($object, $content);
    }
    return $result;
  }
  /**
   * 接收视频消息
   */
  private function receivevideo($object)
  {
    $content = array("mediaid"=>$object->mediaid, "thumbmediaid"=>$object->thumbmediaid, "title"=>"", "description"=>"");
    $result = $this->transmitvideo($object, $content);
    return $result;
  }
  /**
   * 接收链接消息
   */
  private function receivelink($object)
  {
    $content = "你发送的是链接,标题为:".$object->title.";内容为:".$object->description.";链接地址为:".$object->url;
    $result = $this->transmittext($object, $content);
    return $result;
  }
  /* ----------------------------------回复----------------------------- */
  /**
   * 回复文本消息
   */
  private function transmittext($object, $content)
  {
    if (!isset($content) || empty($content)){
      return "";
    }
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[text]]></msgtype>
            <content><![cdata[%s]]></content>
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time(), $content);
    return $result;
  }
  /**
   * 回复多客服消息
   */
  private function transmitservice($object)
  {
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[transfer_customer_service]]></msgtype>
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time());
    return $result;
  }
  /**
   * 回复图文消息
   */
  private function transmitnews($object, $newsarray)
  {
    if(!is_array($newsarray)){
      return "";
    }
    $itemtpl = "<item>
            <title><![cdata[%s]]></title>
            <description><![cdata[%s]]></description>
            <picurl><![cdata[%s]]></picurl>
            <url><![cdata[%s]]></url>
          </item>";
    $item_str = "";
    foreach ($newsarray as $item){
      $item_str .= sprintf($itemtpl, $item['title'], $item['description'], $item['picurl'], $item['url']);
    }
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[news]]></msgtype>
            <articlecount>%s</articlecount>
            <articles>$item_str</articles>
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time(), count($newsarray));
    return $result;
  }
  /**
   * 回复音乐消息
   */
  private function transmitmusic($object, $musicarray)
  {
    if(!is_array($musicarray)){
      return "";
    }
    $itemtpl = "<music>
            <title><![cdata[%s]]></title>
            <description><![cdata[%s]]></description>
            <musicurl><![cdata[%s]]></musicurl>
            <hqmusicurl><![cdata[%s]]></hqmusicurl>
          </music>";
    $item_str = sprintf($itemtpl, $musicarray['title'], $musicarray['description'], $musicarray['musicurl'], $musicarray['hqmusicurl']);
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[music]]></msgtype>
            $item_str
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time());
    return $result;
  }
  /**
   * 回复图片消息
   */
  private function transmitimage($object, $imagearray)
  {
    $itemtpl = "<image>
            <mediaid><![cdata[%s]]></mediaid>
          </image>";
    $item_str = sprintf($itemtpl, $imagearray['mediaid']);
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[image]]></msgtype>
            $item_str
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time());
    return $result;
  }
  /**
   * 回复语音消息
   */
  private function transmitvoice($object, $voicearray)
  {
    $itemtpl = "<voice>
            <mediaid><![cdata[%s]]></mediaid>
          </voice>";
    $item_str = sprintf($itemtpl, $voicearray['mediaid']);
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[voice]]></msgtype>
            $item_str
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time());
    return $result;
  }
  /**
   * 回复视频消息
   */
  private function transmitvideo($object, $videoarray)
  {
    $itemtpl = "<video>
            <mediaid><![cdata[%s]]></mediaid>
            <thumbmediaid><![cdata[%s]]></thumbmediaid>
            <title><![cdata[%s]]></title>
            <description><![cdata[%s]]></description>
          </video>";
    $item_str = sprintf($itemtpl, $videoarray['mediaid'], $videoarray['thumbmediaid'], $videoarray['title'], $videoarray['description']);
    $xmltpl =  "<xml>
            <tousername><![cdata[%s]]></tousername>
            <fromusername><![cdata[%s]]></fromusername>
            <createtime>%s</createtime>
            <msgtype><![cdata[video]]></msgtype>
            $item_str
          </xml>";
    $result = sprintf($xmltpl, $object->fromusername, $object->tousername, time());
    return $result;
  }
  /* ----------------------------------通用----------------------------- */
  /**
   * 回复第三方接口消息
   */
  private function relaypart3($url, $rawdata)
  {
    $headers = array("content-type: text/xml; charset=utf-8");
    $ch = curl_init();
    curl_setopt($ch, curlopt_url, $url);
    curl_setopt($ch, curlopt_returntransfer, 1);
    curl_setopt($ch, curlopt_httpheader, $headers);
    curl_setopt($ch, curlopt_post, 1);
    curl_setopt($ch, curlopt_postfields, $rawdata);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
  }
  /**
   * 字节转emoji表情
   */
  function bytes_to_emoji($cp)
  {
    if ($cp > 0x10000){    # 4 bytes
      return chr(0xf0 | (($cp & 0x1c0000) >> 18)).chr(0x80 | (($cp & 0x3f000) >> 12)).chr(0x80 | (($cp & 0xfc0) >> 6)).chr(0x80 | ($cp & 0x3f));
    }else if ($cp > 0x800){  # 3 bytes
      return chr(0xe0 | (($cp & 0xf000) >> 12)).chr(0x80 | (($cp & 0xfc0) >> 6)).chr(0x80 | ($cp & 0x3f));
    }else if ($cp > 0x80){  # 2 bytes
      return chr(0xc0 | (($cp & 0x7c0) >> 6)).chr(0x80 | ($cp & 0x3f));
    }else{          # 1 byte
      return chr($cp);
    }
  }
  /**
   * 日志记录
   */
  private function logger($log_content)
  {
    if (isset($_server['http_appname'])) {  //sae
      sae_set_display_errors(false);
      sae_debug($log_content);
      sae_set_display_errors(true);
    } else if ($_server['remote_addr'] != "127.0.0.1") { //local
      $max_size = 1000000;
      $log_filename = "mpweixin.log.xml";
      if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
        unlink($log_filename);
      }
      file_put_contents($log_filename, date('y-m-d h:i:s')." ".$log_content."\r\n", file_append);
    }
  }
  /**
   * 获取access_token
   */
  private function getaccesstoken()
  {
    $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="; . $this->appid . "&secret=" . $this->secret;
    $response = $this->get_contents($token_url);
    $params = array();
    $params = json_decode($response,true);
    if (isset($params['errcode']))
    {
      echo "<h3>error:</h3>" . $params['errcode'];
      echo "<h3>msg :</h3>" . $params['errmsg'];
      exit;
    }
    return $params['access_token'];
  }
  public function get_contents($url){
    $ch = curl_init();
    curl_setopt($ch, curlopt_ssl_verifypeer, false);
    curl_setopt($ch, curlopt_returntransfer, true);
    curl_setopt($ch, curlopt_url, $url);
    $response = curl_exec($ch);
    curl_close($ch);
    //-------请求为空
    if(empty($response)){
      exit("50001");
    }
    return $response;
  }
}
?>

更多关于php相关内容感兴趣的读者可查看本站专题:《php微信开发技巧汇总》、《php编码与转码操作技巧汇总》、《php网络编程技巧总结》、《php字符串(string)用法总结》、《php中json格式数据操作技巧汇总》及《php针对xml文件操作技巧总结

希望本文所述对大家php程序设计有所帮助。