Home php教程 php手册 微信公众号开发之微信公共平台消息回复类

微信公众号开发之微信公共平台消息回复类

May 25, 2016 pm 04:39 PM
foreach select

微信公众号开发代码我在网上看到了有不少,其实都是大同小义了都是参考官方给出的demo文件进行修改的,下面给各位分享一个。

初次接触的时候写的一些,有点乱…也没去整理…

ps—最近都不想工作了,各种烦,午饭也没吃,就是想表达一下我过的不好。—请忽略个人情绪往下看。

<?php
/**
 * 微信公共平台消息回复类
 *
 *
 */
class BBCweixin {
    private $APPID = "******";
    private $APPSECRET = "******";
    /*
     *文本消息回复
     *@param array object
     *@param string content
     *@return string
    */
    public function resText($object, $content, $flag = 0) {
        $xmlText = "<xml>
                  <ToUserName><![CDATA[%s]]></ToUserName>
                  <FromUserName><![CDATA[%s]]></FromUserName>
                  <CreateTime>%s</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[%s]]></Content>
                  <FuncFlag>%d</FuncFlag>
                  </xml>";
        $resultStr = sprintf($xmlText, $object->FromUserName, $object->ToUserName, time() , $content, $flag);
        echo $resultStr;
        exit();
    }
    /*
     *图片消息回复
     *@param array object
     *@param string url
     *@return string
    */
    public function resImage($object, $media_id) {
        $xmlImage = "<xml>";
        $xmlImage.= "<ToUserName><![CDATA[%s]]></ToUserName>";
        $xmlImage.= "<FromUserName><![CDATA[%s]]></FromUserName>";
        $xmlImage.= "<CreateTime>%s</CreateTime>";
        $xmlImage.= "<MsgType><![CDATA[image]]></MsgType>";
        $xmlImage.= "<Image><MediaId><![CDATA[%s]]></MediaId></Image>";
        $xmlImage.= "</xml>";
        $resultStr = sprintf($xmlImage, $object->FromUserName, $object->ToUserName, time() , $media_id);
        echo $resultStr;
        exit();
    }
    /*
     *图文消息回复
     *@param array object
     *@param array newsData 二维数组 必须包含[Title][Description][PicUrl][Url]字段
     *@return string
    */
    public function resNews($object, $newsData = array()) {
        $CreateTime = time();
        $FuncFlag = 0;
        $newTplHeader = "<xml>
        <ToUserName><![CDATA[{$object->FromUserName}]]></ToUserName>
        <FromUserName><![CDATA[{$object->ToUserName}]]></FromUserName>
        <CreateTime>{$CreateTime}</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        <ArticleCount>%s</ArticleCount><Articles>";
        $newTplItem = "<item>
      <Title><![CDATA[%s]]></Title>
      <Description><![CDATA[%s]]></Description>
      <PicUrl><![CDATA[%s]]></PicUrl>
      <Url><![CDATA[%s]]></Url>
      </item>";
        $newTplFoot = "</Articles>
      <FuncFlag>%s</FuncFlag>
      </xml>";
        $Content = &#39;&#39;;
        $itemsCount = count($newsData);
        $itemsCount = $itemsCount < 10 ? $itemsCount : 10; //微信公众平台图文回复的消息一次最多10条
        if ($itemsCount) {
            foreach ($newsData as $key => $item) {
                if ($key <= 9) {
                    $Content.= sprintf($newTplItem, $item[&#39;Title&#39;], $item[&#39;Description&#39;], $item[&#39;PicUrl&#39;], $item[&#39;Url&#39;]);
                }
            }
        }
        $header = sprintf($newTplHeader, 0, $itemsCount);
        $footer = sprintf($newTplFoot, $FuncFlag);
        echo $header . $Content . $footer;
        exit();
    }
    /*
     *音乐消息回复
     *@param array object
     *@param array musicContent 二维数组 包含[Title][Description][MusicUrl][HQMusicUrl]字段
     *@return string
    */
    public function resMusic($object, $musicContent = array()) {
        $xmlMusic = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[music]]></MsgType>
                    <Music>
     <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <MusicUrl><![CDATA[%s]]></MusicUrl>
                    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                    </Music>
                    </xml>";
        if (empty($musicContent[0][&#39;HQMusicUrl&#39;])) {
            $musicContent[0][&#39;HQMusicUrl&#39;] = $musicContent[0][&#39;MusicUrl&#39;];
        }
        $resultStr = sprintf($xmlMusic, $object->FromUserName, $object->ToUserName, time() , $musicContent[0][&#39;Title&#39;], $musicContent[0][&#39;Description&#39;], $musicContent[0][&#39;MusicUrl&#39;], $musicContent[0][&#39;HQMusicUrl&#39;]);
        echo $resultStr;
        exit();
    }
    /*
     *上传多媒体文件接口
     *@param
     *@param array mediaArr filename、filelength、content-type
     *@return object
    */
    public function uploadMedia($accessToken, $type = &#39;image&#39;, $mediaArr) {
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $accessToken . "&type=" . $type;
        $doPost = self::curlPost($mediaArr, $url);
        return $doPost;
    }
    /*
     *GPS,谷歌坐标转换成百度坐标
     *@param lnt
     *@param lat
     *@return array
    */
    public function mapApi($lng, $lat, $type) {
        $map = array();
        if ($type == &#39;gps&#39;) {
            $url = "http://map.yanue.net/gpsApi.php?lat=" . $lat . "&lng=" . $lng;
            $res = json_decode(file_get_contents($url));
            $map[&#39;lng&#39;] = $res->baidu->lng;
            $map[&#39;lat&#39;] = $res->baidu->lat;
        }
        if ($type == &#39;google&#39;) {
            $url = "http://api.map.baidu.com/ag/coord/convert?from=2&to=4&mode=1&x=" . $lng . "&y=" . $lat;
            $res = json_decode(file_get_contents($url));
            $map[&#39;lng&#39;] = base64_decode($res[0]->x);
            $map[&#39;lat&#39;] = base64_decode($res[0]->y);
        }
        return $map;
    }
    /**************************************************************
     *
     *  使用特定function对数组中所有元素做处理
     *  @param  string  &$array     要处理的字符串
     *  @param  string  $function   要执行的函数
     *  @return boolean $apply_to_keys_also     是否也应用到key上
     *  @access public
     *
     *************************************************************/
    public function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die(&#39;possible deep recursion attack&#39;);
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                self::arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }
            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    }
    /**************************************************************
     *
     *  将数组转换为JSON字符串(兼容中文)
     *  @param  array   $array      要转换的数组
     *  @return string      转换得到的json字符串
     *  @access public
     *
     *************************************************************/
    public function JSON($array) {
        self::arrayRecursive($array, &#39;urlencode&#39;, true);
        $json = json_encode($array);
        return urldecode($json);
    }
    /*
     *创建菜单
     *
    */
    public function creatMenu($shop_id, $data) {
        $jsonArray = self::JSON($data);
        $AccessToken = self::accessToken($weiXin[0][&#39;key&#39;], $weiXin[0][&#39;secret&#39;]);
        $MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $AccessToken;
        return self::curlPost($jsonArray, $MENU_URL);
    }
    /*
     *客服消息回复
     *@param array jsonArray Array {"touser":"OPENID","msgtype":"text","text":{"content":"Hello World"}}
     *@return string
    */
    public function customService($jsonArray, $hash) {
        if (empty($jsonArray)) {
            return false;
        }
        $db = M();
        $sql = "select * from bbc_wechats where hash=&#39;" . $hash . "&#39;";
        $weChast = $db->query($sql);
        $AccessToken = self::accessToken($weChast[0][&#39;key&#39;], $weChast[0][&#39;secret&#39;]);
        $TokenUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $AccessToken;
        $CustomRes = self::curlPost($jsonArray, $TokenUrl);
        return $CustomRes;
    }
    /*
    
    *获取access_token
    *@return objectStr
    */
    public function accessToken($appid, $secret) {
        $access_token = BBCcache::getCache(&#39;accesstoken&#39; . $appid);
        if ($access_token) {
            $AccessTokenRet = $access_token;
        } else {
            $TookenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            $AccessTokenRes = @file_get_contents($TookenUrl);
            $AccessToken = json_decode($AccessTokenRes);
            $AccessTokenRet = $AccessToken->access_token;
            BBCcache::setCache(&#39;accesstoken&#39; . $appid, $AccessToken->access_token, 3600);
        }
        return $AccessTokenRet;
    }
    /*
     *向远程接口POST数据
     *@data Array {"touser":"OPENID","msgtype":"text","text":{"content":"Hello World"}}
     *@return objectArray
    */
    public function curlPost($data, $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, &#39;Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)&#39;);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $info = curl_exec($ch);
        if (curl_errno($ch)) {
            echo &#39;Errno&#39; . curl_error($ch);
        }
        curl_close($ch);
        return json_decode($info);
    }
    //根据经纬度计算距离和方向
    function getRadian($d) {
        return $d * M_PI / 180;
    }
    function getDistance($lat1, $lng1, $lat2, $lng2) {
        $EARTH_RADIUS = 6378.137; //地球半径
        $lat1 = getRadian($lat1);
        $lat2 = getRadian($lat2);
        $a = $lat1 - $lat2;
        $b = getRadian($lng1) - getRadian($lng2);
        $v = 2 * asin(sqrt(pow(sin($a / 2) , 2) + cos($lat1) * cos($lat2) * pow(sin($b / 2) , 2)));
        $v = round($EARTH_RADIUS * $v * 10000) / 10000;
        return $v;
    }
}
?>
Copy after login


教程网址:

欢迎收藏∩_∩但请保留本文链接。

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to determine the number of foreach loop in php How to determine the number of foreach loop in php Jul 10, 2023 pm 02:18 PM

​The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

How to hide the select element in jquery How to hide the select element in jquery Aug 15, 2023 pm 01:56 PM

How to hide the select element in jquery: 1. hide() method, introduce the jQuery library into the HTML page, you can use different selectors to hide the select element, the ID selector replaces the selectId with the ID of the select element you actually use; 2. css() method, use the ID selector to select the select element that needs to be hidden, use the css() method to set the display attribute to none, and replace selectId with the ID of the select element.

Asynchronous processing method of Select Channels Go concurrent programming using golang Asynchronous processing method of Select Channels Go concurrent programming using golang Sep 28, 2023 pm 05:27 PM

Asynchronous processing method of SelectChannelsGo concurrent programming using golang Introduction: Concurrent programming is an important area in modern software development, which can effectively improve the performance and responsiveness of applications. In the Go language, concurrent programming can be implemented simply and efficiently using Channels and Select statements. This article will introduce how to use golang for asynchronous processing methods of SelectChannelsGo concurrent programming, and provide specific

How to implement change event binding of select elements in jQuery How to implement change event binding of select elements in jQuery Feb 23, 2024 pm 01:12 PM

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

What is the reason why Linux uses select? What is the reason why Linux uses select? May 19, 2023 pm 03:07 PM

Because select allows developers to wait for multiple file buffers at the same time, it can reduce IO waiting time and improve the IO efficiency of the process. The select() function is an IO multiplexing function that allows the program to monitor multiple file descriptors and wait for one or more of the monitored file descriptors to become "ready"; the so-called "ready" state is Refers to: the file descriptor is no longer blocked and can be used for certain types of IO operations, including readable, writable, and exceptions. select is a computer function located in the header file #include. This function is used to monitor file descriptor changes—reading, writing, or exceptions. 1. Introduction to the select function. The select function is an IO multiplexing function.

PHP returns the current element in an array PHP returns the current element in an array Mar 21, 2024 pm 12:36 PM

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element

See all articles