zoukankan      html  css  js  c++  java
  • php 用户向微信发送信息

    1:制作微信菜单栏

    <?php
    header("Content-type: text/html; charset=utf-8");
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }
    /*$xml="<xml>
     <ToUserName>bj_xiangfubao</ToUserName>
     <FromUserName>oMbrFjgLt5W6SjwIQTLRHhIvX4ro</FromUserName>
     <CreateTime>time()</CreateTime>
     <MsgType>text</MsgType>
     <Content>dffff</Content>
     <MsgId>1234567890123456</MsgId>
     </xml>";*/
    //$result = request_post($url = 'http://integral.xiangfubao.com.cn/beidong.php', $xml);
    //var_dump($result);
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    function getToken($appid, $appsecret)
    {
        /*if (S($appid)) {
            $access_token = S($appid);
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $token = $this->request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
            S($appid, $access_token, 720);
        }*/
         $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $token = request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
            return $access_token;
    }
    $token = getToken('wxdeeda2690614a91f', 'fb9dd84cef34972c607c967d71b28402');
    $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$token;
    $data = '{
         "button":[
          {
               "name":"祥付电商",
               "sub_button":[
                {
                   "type":"view",
                   "name":"祥付·海淘商城",
                   "url":"http://shop.gogo198.cn/app/index.php?i=6&c=entry&p=designer&pageid=23&m=sz_yi&do=plugin&mid=35"
                },
                {
                   "type":"view",
                   "name":"祥付·友卖网站",
                   "url":"http://shop.xiangfubao.com.cn"
                }]
          },
          {
               "name":"关于我的",
               "sub_button":[
                {
                   "type":"click",
                   "name":"积分查询",
                   "key":"V1001_HELLO_WORLD"
                }]
           }]
    }';
    $result = dataPost($data,$url);


     function dataPost($post_string,$url)
     {//POST方式提交数据
         $context =
        array ('http' =>
        array ('method' =>
        "POST",
        'header' =>
        "User-Agent:
         Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) Accept: */*",
        'content' =>
        $post_string )
         );
         $stream_context =
         stream_context_create ( $context );
         $data =
        file_get_contents (
        $url,
         FALSE, $stream_context );
         return $data;
     }
    var_dump($result);
    ?>

    2:微信服务器端接收消息回复用户信息

    <?php  
    header("Content-type: text/html; charset=utf-8");  
    $testObj = new Test();

    if(!empty($_GET['echostr'])){
        $testObj->valid();  
          
    }else{
        $testObj->responseMsg();  
    }
     
    exit;
     
    class Test  
    {  
        /**
         * 绑定url、token信息
         */  
        public function valid(){  
            $echoStr = $_GET["echostr"];  
            if ($this->checkSignature()) {  
                echo $echoStr;  
            }  
            exit();  
        }  
        /**
         * 检查签名,确保请求是从微信发过来的
         */  
        private function checkSignature()  
        {  
            $signature = $_GET["signature"];  
            $timestamp = $_GET["timestamp"];  
            $nonce = $_GET["nonce"];      
                      $this->log('--'.$signature.'--');
            $token = "Fyh3b27ih7vveRQeRDI3Ydd3Vb32iVZs";//与在微信配置的token一致,不可泄露  
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr,SORT_STRING);  
            $tmpStr = implode( $tmpArr );  
            $tmpStr = sha1( $tmpStr );
            if( $tmpStr == $signature ){  
                return true;  
            }else{  
                return false;  
            }  
        }  
     
        /**
         * 接收消息,并自动发送响应信息
         */  
        public function responseMsg(){  
              
            //验证签名  
            if (11){  
                //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
                $postStr=file_get_contents('php://input');
                $this->log_request_info();  
          
                //提取post数据  
                if (!empty($postStr)){  
                        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);  
                        $fromUsername = $postObj->FromUserName;//发送人  
                        $toUsername = $postObj->ToUserName;//接收人  
                        $MsgType = $postObj->MsgType;//消息类型
                        $ContentText = $postObj->Content;//消息类型
                        $MsgId = $postObj->MsgId;//消息id  
                        $time = time();//当前时间做为回复时间   
                        //如果是文本消息(表情属于文本信息)  
                        if($MsgType == 'text'){  
                            $content = trim($postObj->Content);//消息内容  
                            if(!empty( $content )){  
                                  
                                //如果文本内容是图文,则回复图文信息,否则回复文本信息  
                                if($content == "图文"){  
                                      
                                    //回复图文消息,ArticleCount图文消息个数,多条图文消息信息,默认第一个item为大图  
                                    $ArticleCount = 2;   
                                    $newsTpl = "<xml>  
                                    <ToUserName><![CDATA[%s]]></ToUserName>  
                                    <FromUserName><![CDATA[%s]]></FromUserName>  
                                    <CreateTime>%s</CreateTime>  
                                    <MsgType><![CDATA[%s]]></MsgType>  
                                    <ArticleCount>%s</ArticleCount>  
                                    <Articles>  
                                    <item>  
                                    <Title><![CDATA[%s]]></Title>   
                                    <Description><![CDATA[%s]]></Description>  
                                    <PicUrl><![CDATA[%s]]></PicUrl>  
                                    <Url><![CDATA[%s]]></Url>  
                                    </item>  
                                    <item>  
                                    <Title><![CDATA[%s]]></Title>  
                                    <Description><![CDATA[%s]]></Description>  
                                    <PicUrl><![CDATA[%s]]></PicUrl>  
                                    <Url><![CDATA[%s]]></Url>  
                                    </item>  
                                    </Articles>  
                                    </xml>";
                                    $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, 'news',   
                                                $ArticleCount,'我是图文信息','我是描述信息','http://www.test.com/DocCenterService/image?photo_id=236',  
                                                'http://www.test.com','爱城市网正式开通上线','描述2','http://jn.test.com/ac/skins/img/upload/img/20131116/48171384568991509.png',  
                                                'http://www.test.com');  
                                    echo $resultStr;  
                                    $this->log($resultStr);  
                                }else{
                                    if($ContentText=='积分查询')
                                    {
                                        require('mysql.php');
                                        $db = new mysql('localhost', 'root', '123456', "jifen");
                                        $db->select("user", "*", "openid = "."'".$fromUsername."'");
                                        $re = $db->fetchArray(MYSQL_ASSOC);
                                        $jifen = $re[0]['jifen'];
                                        $jifen =(string)$jifen.'积分';
                                        //回复文本信息  
                                        $textTpl = "<xml>  
                                                    <ToUserName><![CDATA[%s]]></ToUserName>  
                                                    <FromUserName><![CDATA[%s]]></FromUserName>  
                                                    <CreateTime>%s</CreateTime>  
                                                    <MsgType><![CDATA[%s]]></MsgType>  
                                                    <Content><![CDATA[%s]]></Content>  
                                                    <FuncFlag>0</FuncFlag>  
                                                    </xml>";               
                                        //$contentStr = '你发送的信息是:接收人:'.$toUsername.',发送人:'.$fromUsername.',消息类型:'.$MsgType.',消息内容:'.$jifen.' www.icity365.com';
                                        $contentStr = '您目前'.$jifen;
                                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
                                        echo $resultStr;  
                                        $this->log($resultStr);
                                    }                                  
                                }  
                            }else{  
                                echo "Input something...";  
                                $this->log($resultStr);  
                            }  
                              
                          //如果是图片消息  
                        }elseif ($MsgType == 'image'){  
                            $MediaId = $postObj->MediaId;//图片消息媒体id,可以调用多媒体文件下载接口拉取数据。  
                            $imageTpl = "<xml>  
                                        <ToUserName><![CDATA[%s]]></ToUserName>  
                                        <FromUserName><![CDATA[%s]]></FromUserName>  
                                        <CreateTime>%s</CreateTime>  
                                        <MsgType><![CDATA[%s]]></MsgType>  
                                        <Image>  
                                        <MediaId><![CDATA[%s]]></MediaId>  
                                        </Image>  
                                        </xml>";  
                            $resultStr = sprintf($imageTpl, $fromUsername, $toUsername, $time, $MsgType, $MediaId);  
                            echo $resultStr;  
                            $this->log("自动响应图片信息");  
                            $this->log($resultStr);  
                              
                        //如果是视频  
                        }else if($MsgType == 'video'){  
                            $MediaId = $postObj->MediaId;//视频消息媒体id,可以调用多媒体文件下载接口拉取数据。  
                            $ThumbMediaId = $postObj->ThumbMediaId;//视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。   
                            $videoTpl = "<xml>  
                                        <ToUserName><![CDATA[%s]]></ToUserName>  
                                        <FromUserName><![CDATA[%s]]></FromUserName>  
                                        <CreateTime>%s</CreateTime>  
                                        <MsgType><![CDATA[%s]]></MsgType>  
                                        <Video>  
                                        <MediaId><![CDATA[%s]]></MediaId>  
                                        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>  
                                        <Title><![CDATA[%s]]></Title>  
                                        <Description><![CDATA[%s]]></Description>  
                                        </Video>   
                                        </xml>";  
                            $resultStr = sprintf($videoTpl, $fromUsername, $toUsername, $time, $MsgType, $MediaId,$ThumbMediaId,'我是标题','我是描述');  
                            echo $resultStr;  
                            $this->log("自动响应视频信息".$ThumbMediaId);  
                            $this->log($resultStr);  
                              
                        //如果是地理位置  
                        }else if($MsgType == 'location'){  
                            $Location_X = $postObj->Location_X;//维度  
                            $Location_Y = $postObj->Location_Y;//经度  
                            $Scale = $postObj->Scale;//地图缩放大小  
                            $Label = $postObj->Label;//地里位置信息  
                              
                            //回复文本信息  
                            $textTpl = "<xml>  
                                        <ToUserName><![CDATA[%s]]></ToUserName>  
                                        <FromUserName><![CDATA[%s]]></FromUserName>  
                                        <CreateTime>%s</CreateTime>  
                                        <MsgType><![CDATA[%s]]></MsgType>  
                                        <Content><![CDATA[%s]]></Content>  
                                        <FuncFlag>0</FuncFlag>  
                                        </xml>";               
                            $msgType = "text";  
                            $contentStr = '经度:'.$Location_Y.',维度:'.$Location_X.',地图缩放大小'.$Scale.',地理位置信息:'.$Label;  
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);  
                            echo $resultStr;  
                            $this->log($resultStr);  
                              
                        //如果是事件  
                        }else if($MsgType == 'event'){  
                              
                            $Event = $postObj->Event;  
                              
                            //subscribe(关注,也叫订阅)  
                            if($Event == 'subscribe'){  
                                  
                                $EventKey = $postObj->EventKey;//事件KEY值,qrscene_为前缀,后面为二维码的参数值  
                                  
                                //未关注时,扫描二维码  
                                if(!empty($EventKey)){  
                                    $Ticket = $postObj->Ticket;//二维码的ticket,可用来换取二维码图片  
                                    $this->log($fromUsername.'扫描二维码关注!EventKey='.$EventKey.',Ticket='.$Ticket);  
                                }else{  
                                    $this->log($fromUsername.'关注我了!');  
                                }  
                                  
                            //unsubscribe(取消关注)  
                            }elseif ($Event == 'unsubscribe'){  
                                $this->log($fromUsername.'取消关注我了!');  
                                  
                            //已关注时,扫描二维码事件  
                            }elseif($Event == 'SCAN' || $Event == 'scan'){  
                                $EventKey = $postObj->EventKey;//事件KEY值,是一个32位无符号整数,即创建二维码时的二维码scene_id  
                                $Ticket = $postObj->Ticket;//二维码的ticket,可用来换取二维码图片  
                                $this->log($fromUsername.'关注我了!EventKey='.$EventKey.',Ticket='.$Ticket);  
                              
                            //菜单点击事件  
                            }elseif($Event == 'CLICK'){
                                require('mysql.php');
                                $db = new mysql('localhost', 'root', '123456', "jifen");
                                $db->select("user", "*", "openid = "."'".$fromUsername."'");
                                $re = $db->fetchArray(MYSQL_ASSOC);
                                $jifen = $re[0]['jifen'];
                                $jifen =(string)$jifen.'积分';
                                $EventKey = $postObj->EventKey;//事件KEY值,与自定义菜单接口中KEY值对应  
                                //回复文本信息  
                                $textTpl = "<xml>  
                                            <ToUserName><![CDATA[%s]]></ToUserName>  
                                            <FromUserName><![CDATA[%s]]></FromUserName>  
                                            <CreateTime>%s</CreateTime>  
                                            <MsgType><![CDATA[%s]]></MsgType>  
                                            <Content><![CDATA[%s]]></Content>  
                                            <FuncFlag>0</FuncFlag>  
                                            </xml>";               
                                //$contentStr = '你点击了菜单,菜单项key='.$EventKey;
                                $contentStr = '您目前有'.$jifen;
                                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);  
                                echo $resultStr;  
                                $this->log($resultStr);  
     
                            //其他事件类型  
                            }else{  
                                $this->log('事件类型:'.$Event);  
                            }  
                              
                        //其他消息类型,链接、语音等  
                        }else{  
                            //回复文本信息  
                            $textTpl = "<xml>  
                                        <ToUserName><![CDATA[%s]]></ToUserName>  
                                        <FromUserName><![CDATA[%s]]></FromUserName>  
                                        <CreateTime>%s</CreateTime>  
                                        <MsgType><![CDATA[%s]]></MsgType>  
                                        <Content><![CDATA[%s]]></Content>  
                                        <FuncFlag>0</FuncFlag>  
                                        </xml>";               
                            $contentStr = '消息类型:'.$MsgType.'我们还没做处理。。。。【爱城市网】';  
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);  
                            echo $resultStr;  
                            $this->log($resultStr);  
                        }  
          
                }else {  
                    $this->log("未收到post信息:");    
                    exit;  
                }  
            }else{  
                    $this->log("验证签名未通过!");        
            }  
        }  
        /**
         * 记录请求信息
         */  
        function log_request_info() {  
            $post = '';
            foreach($_POST   as   $key   =>   $value)   {   
                $post = $post.$key.' : '.$value.' , ';   
            }   
            $get = '';  
            foreach($_GET   as   $key   =>   $value)   {   
                $get = $get.$key.' : '.$value.' , ';   
            }   
            $this->log("get信息:".$get);  
            $this->log("post信息:".$post);  
        }  
        /**
         * 记录日志
         * @param $str
         * @param $mode
         */  
        function log($str){  
            $mode='a';//追加方式写  
            $file = "log.txt";  
            $oldmask = @umask(0);  
            $fp = @fopen($file,$mode);  
            @flock($fp, 3);  
            if(!$fp)  
            {  
                Return false;  
            }  
            else  
            {  
                @fwrite($fp,$str);  
                @fclose($fp);  
                @umask($oldmask);  
                Return true;  
            }  
        }  
    }  
     
    ?>

  • 相关阅读:
    JUC并发工具包之Semaphore
    Linux命令
    uWSGI
    数据库 MySQL 练习
    c++
    c++ 初阶
    Git
    MySQl 和 Redis
    MySQL 查询
    MySQL 命令
  • 原文地址:https://www.cnblogs.com/gzyx1988/p/7125623.html
Copyright © 2011-2022 走看看