亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development Share a complete WeChat development php code

Share a complete WeChat development php code

Mar 13, 2017 pm 01:59 PM
php WeChat development

This article mainly shares a complete WeChat developmentphp code, which has certain reference value. Interested friends can refer to it

The examples in this article are shared with everyone. I developed the php code for WeChat for your reference. The specific content is as follows


<?php
  //封裝成一個微信接口類
 
  class WeixinApi
  {
    private $appid;
    private $appsecret; 
 
    //構造方法 初始化賦值
    public function construct($appid="",$appsecret="")
    {
      $this->appid = $appid;
      $this->appsecret = $appsecret;
    }
 
    //驗證服務器地址有效性
    public function valid()
    {
      if($this->checkSignature())
      {
        $echostr = $_GET[&#39;echostr&#39;];//隨機的字符串
        return $echostr;
      }
      else
      {
        return "Error";
      }
    }
 
    //檢查簽名
    private function checkSignature()
    {
      //一、接收微信服務器GET方式提交過來的4個參數(shù)數(shù)據(jù)
 
      $signature = $_GET[&#39;signature&#39;];//微信加密簽名
 
      $timestamp = $_GET[&#39;timestamp&#39;];//時間戳
 
      $nonce = $_GET[&#39;nonce&#39;];//隨機數(shù)
 
      //二、加密/校驗過程
      // 1. 將token、timestamp、nonce三個參數(shù)進行字典序排序;
      // bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) 對數(shù)組排序 
       
      $tmpArr = array(TOKEN,$timestamp,$nonce);//將上面三個參數(shù)放到一個數(shù)組里面
      sort($tmpArr,SORT_STRING);
 
      // 2. 將三個參數(shù)字符串拼接成一個字符串進行sha1加密;
      $tmpStr = implode($tmpArr); //將數(shù)組轉化成字符串
 
      $signatureStr = sha1($tmpStr);
 
      // 3. 開發(fā)者獲得加密后的字符串與signature對比。
      if($signatureStr == $signature)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
 
    //響應消息
    public function responseMsg()
    {
      //接收微信服務器發(fā)送POST請求到開發(fā)者服務器,攜帶的XML數(shù)據(jù)包
      $postData = $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;];
 
      //處理xml數(shù)據(jù)包
      $xmlObj = simplexml_load_string($postData,"SimpleXMLElement",LIBXML_NOCDATA);
 
      if(!$xmlObj)
      {
        echo "";
        exit;
      }
 
      //獲取接收消息中的參數(shù)內容
      $toUserName = $xmlObj->ToUserName;//開發(fā)者微信號
      $fromUserName = $xmlObj->FromUserName;//發(fā)送方的微信號(openid)
      $msgType = $xmlObj->MsgType;//消息類型
      switch ($msgType) {
        //接收文本消息
        case &#39;text&#39;:
          //獲取文本消息的關鍵字
          $keyword = $this->receiveText($xmlObj); 
          //進行關鍵字回復
          switch($keyword)
          {
            case "w001":
            case "W001":
              return $this->replyText($xmlObj,"Hi~你好");
              break;
            case "w002":
            case "W002":
              return $this->replyText($xmlObj,"Hi~尷尬了");
              break;
            case "笑話":
              $key = "dee9ebc68fd5a61f67286063932afe56";
              return $this->replyNews($xmlObj,$this->joke_text($key));
              break;
            default:
              $key = "dee9ebc68fd5a61f67286063932afe56";
              return $this->replyNews($xmlObj,$this->joke_text($key));
              break;
          }    
          break;
        //接收圖片消息
        case &#39;image&#39;:
          return $this->receiveImage($xmlObj);
          break;
        //接收事件推送
        case &#39;event&#39;:
          return $this->receiveEvent($xmlObj);
          break;
      }      
    }
 
    //接收事件推送
    public function receiveEvent($obj)
    {
      //接收事件類型
      $event = $obj->Event;
      switch ($event)
      {
        //關注事件
        case &#39;subscribe&#39;:
          //下發(fā)歡迎消息
          $newsArr = array(
                  array(
                    "Title"=>"做有價值的頭條資訊!",
                    "Description"=>"把握價值頭條資訊,日常更加有談資呢!",
                    "PicUrl"=>"http://jober.applinzi.com/news/img/news.png",
                    "Url"=>"http://jober.applinzi.com/news/index.php"
                  )                
                );
          //回復圖文消息
          return $this->replyNews($obj,$newsArr); 
          break;
        //取消關注事件
        case &#39;unsubscribe&#39;:
          //賬號的解綁操作等等
          break;
        //自定義菜單推送CLICK事件
        case &#39;CLICK&#39;:
          $eventKey = $obj->EventKey;//獲取事件KEY值,與自定義菜單接口中KEY值對應
          switch ($eventKey) 
          {
            case &#39;old&#39;:
   
              $weixinArr = $this->history("da675ebc6a0d72920dca3f676122a693");
              $weixinArr = array_slice($weixinArr, 0,5);
              $newsArr = array();
 
              foreach ($weixinArr as $item) 
              {
                $newsArr = array(array(
                          "Title" => $item[&#39;Description&#39;],
                          "Description" => $item[&#39;Title&#39;],
                          "PicUrl" => "http://1.jober.applinzi.com/news/img/2.jpg",
                          "Url" => "http://www.todayonhistory.com/"                          
                        ));
              }
              return $this->replyNews($obj,$newsArr);
              break;
          }
        break;
      }
    }
 
    //接收文本消息
    public function receiveText($obj)
    {
      $content = trim($obj->Content);//文本消息的內容
      return $content;
    }
 
    //接收圖片消息
    public function receiveImage($obj)
    {
      $picUrl = $obj->PicUrl;//圖片的鏈接
      $mediaId = $obj->MediaId;//圖片消息媒體id
      return $this->replyImage($obj,$mediaId);
    }
 
    //回復圖片消息
    public function replyImage($obj,$mediaId)
    {
      $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[image]]></MsgType>
              <Image>
                <MediaId><![CDATA[%s]]></MediaId>
              </Image>
            </xml>";
      return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$mediaId);
           
    }
 
    //回復文本消息
    public function replyText($obj,$content)
    {
      $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[text]]></MsgType>
              <Content><![CDATA[%s]]></Content>
            </xml>";
      return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$content);
    }
     
    //回復圖文消息
    public function replyNews($obj,$newsArr)
    {
      //判斷是否為數(shù)組類型
      if(!is_array($newsArr))
      {
        return;
      }
      // 判斷數(shù)組是否為空數(shù)組
      if(!$newsArr)
      {
        return;
      }
      $itemStr = "";
      //定義item模板
      $itemXml = "<item>
              <Title><![CDATA[%s]]></Title> 
              <Description><![CDATA[%s]]></Description>
              <PicUrl><![CDATA[%s]]></PicUrl>
              <Url><![CDATA[%s]]></Url>
            </item>";
      foreach($newsArr as $item)
      {
        $itemStr .= sprintf($itemXml,$item[&#39;Title&#39;],$item[&#39;Description&#39;],$item[&#39;PicUrl&#39;],$item[&#39;Url&#39;]);
      }
      $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[news]]></MsgType>
              <ArticleCount>".count($newsArr)."</ArticleCount>
              <Articles>".$itemStr."</Articles>
            </xml>"; 
      return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time());     
    }
 
    //封裝https請求(GET和POST)
   
    protected function https_request($url,$data=null)
    {
      //1、初始化curl
      $ch = curl_init();
 
      //2、設置傳輸選項
      curl_setopt($ch, CURLOPT_URL, $url);//請求的url地址
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//將請求的結果以文件流的形式返回
       
      if(!empty($data))
      {
        curl_setopt($ch,CURLOPT_POST,1);//請求POST方式
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST提交的內容
      }
 
      //3、執(zhí)行請求并處理結果
      $outopt = curl_exec($ch);
 
      //把json數(shù)據(jù)轉化成數(shù)組
      $outoptArr = json_decode($outopt,TRUE);
 
      //4、關閉curl
      curl_close($ch);
 
      //如果返回的結果$outopt是json數(shù)據(jù),則需要判斷一下
      if(is_array($outoptArr))
      {  
        return $outoptArr;
      }
      else
      {
        return $outopt;
      }      
    }
 
    public function juhe_weixin($key,$type)
    {
      $url ="http://v.juhe.cn/toutiao/index?type={$type}&key={$key}";
      $result = $this->https_request($url);
      if($result[&#39;error_code&#39;] == 0)
      {
        return $result[&#39;result&#39;][&#39;data&#39;];
      }
      else
      {
        return array();
      }
    }
 
    //聚合數(shù)據(jù)-獲取最新趣圖
    public function joke_text($key,$pagesize=10)
    {
      $url = "http://japi.juhe.cn/joke/img/text.from?key={$key}&pagesize={$pagesize}";
      $jokeArr = $this->https_request($url);
      $resultArr = $jokeArr[&#39;result&#39;][&#39;data&#39;];
      // $content = $resultArr[0][&#39;content&#39;];
      // return $this->replyText($xmlObj,$content);
       
      $newsArr = array();
      //判斷笑話接口是否獲取數(shù)據(jù)
      if($jokeArr[&#39;error_code&#39;] == 0)
      {
        foreach($resultArr as $item)
        {
          $newsArr[] = array(
                "Title"=>$item[&#39;content&#39;],
                "Description"=>$item[&#39;updatetime&#39;],
                "PicUrl"=>$item[&#39;url&#39;],
                "Url"=>$item[&#39;url&#39;]
              );
        }        
      }
      return $newsArr;
    }
 
 
    //聚合數(shù)據(jù)-獲取歷史上的今天
       
    public function history($key)
    {
      $m = idate(&#39;m&#39;);
      $d = idate(&#39;d&#39;);
      $day = "{$m}/{$d}";
     
      $url = "http://v.juhe.cn/todayOnhistory/queryEvent.php?key={$key}&date={$day}";
      $historyArr = $this->https_request($url);
      $resultArr = $historyArr[&#39;result&#39;];
      // $content = $resultArr[&#39;title&#39;];
      // return $this->replyText($xmlObj,$content);
       
      $newsArr = array();
      //判斷接口是否獲取數(shù)據(jù)
      if($jokeArr[&#39;error_code&#39;] == 0)
      {
        foreach($resultArr as $item)
        {
          $newsArr[] = array(
                "Title"=>$item[&#39;title&#39;],
                "Description"=>$item[&#39;date&#39;],
                "PicUrl"=>"",
                "Url"=>""
              );
        }        
      }
      return $newsArr;
    }
 
    public function fund($key)
    {
 
      $url = "http://japi.juhe.cn/jingzhi/query.from?key={$key}";
      $fundArr = $this->https_request($url);
      $resultArr = $fundArr[&#39;result&#39;];
      // $content = $resultArr[&#39;title&#39;];
      // return $this->replyText($xmlObj,$content);
       
      $newsArr = array();
      //判斷接口是否獲取數(shù)據(jù)
      if($jokeArr[&#39;error_code&#39;] == 0)
      {
        foreach($resultArr as $item)
        {
          $newsArr[] = array(
                "Title"=>$item[&#39;day&#39;],
                "Description"=>$item[&#39;title&#39;],
                "PicUrl"=>"",
                "Url"=>"http://www.baidu.com"
              );
        }        
      }
      return $newsArr;
    }
 
    /**
      *獲取基礎支持里面的接口調用憑證access_token并緩存access_token
      *@return access_token string 接口憑證
    **/
    public function getAccessToken()
    {
      //獲取memcache緩存的access_token
      $access_token = $this->_memcache_get("access_token");
      //如果緩存的access_token失效
      if(!$access_token)
      {  
        //如果失效調用獲取接口憑證來獲取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        $outoptArr = $this->https_request($url);
        if(!isset($outoptArr[&#39;errcode&#39;]))
        {
          //memcache緩存access_token
          $this->_memcache_set("access_token",$outoptArr[&#39;access_token&#39;],7000);
          return $outoptArr[&#39;access_token&#39;];
        }
      }  
      return $access_token;
    }
 
    //初始化memcache
    private function _memcache_init()
    {
      $mmc = new Memcache;
      $ret = $mmc -> connect();
      if ($ret == false) 
      {
        return;
      } 
      return $mmc;
    }
 
    //設置memcache
    private function _memcache_set($key,$value,$time=0)
    {
      $mmc = $this->_memcache_init();
      $mmc -> set($key,$value,0,$time);
    }
 
    //獲取memcahce
    private function _memcache_get($key)
    {
      $mmc = $this->_memcache_init(); 
      return $mmc -> get($key);  
    }
 
    //自定義菜單創(chuàng)建
 
    public function menu_create($data)
    {
      $access_token = $this->getAccessToken();
      //自定義菜單創(chuàng)建接口地址
      $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
      return $this->https_request($url,$data);
    }
 
    //自定義菜單刪除
    public function menu_delete()
    {
      $access_token = $this->getAccessToken();
      $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$access_token}";
      return $this->https_request($url);
    }
  }
?>

The above is the detailed content of Share a complete WeChat development php code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles