微信公众号开发

  1. 先有自己的服务器和注册微信公众号
    使用云应用sae,git,首先登陆新浪云创建应用。本次选择的是标准环境,PHP版本为7。创建之后先测试,使用git  clone  [url],仓库地址在新浪云界面-》代码管理-》git仓库信息里。克隆后再工作目录中创建一个测试文件,比如index.php。使用git命令行,git add .      跟踪文件,git commit -m 'test' 提交然后 git push origin 1  推送到远端。完成这些步骤后就可以使用sae的  域名/测试文件名  访问到测试文件。
  2. 公众号和服务器的关联
    登录微信公众平台-》基本配置: 填写URL  例如:http://neglect.applinzi.com/weixin.php  ,weixin.php是用来和微信服务器验证的文件,因为需要处理一些参数。token值随意填写。消息加解密方式学习阶段选择明文模式,EncodingAESKey随机生成即可。填写完之后,需要在上述填写的URL文件中写一些代码验证。注意:$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];   //php7 版本不能在使用了,改成$postStr = file_get_contents('php://input');  weixin.php文件中的代码如下
     1 <?php
     2 
     3 define("TOKEN", "weixin");    //token要一致
     4 $wechatObj = new wechatCallbackapiTest();
     5 $wechatObj->valid();
     6 
     7 class wechatCallbackapiTest
     8 {
     9     public function valid()
    10     {
    11         $echoStr = $_GET["echostr"];
    12         //valid signature , option
    13         if($this->checkSignature()){
    14             echo $echoStr;
    15             exit;
    16         }
    17     }
    18 
    19     public function responseMsg()
    20     {
    21         //get post data, May be due to the different environments
    22         // $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];   //php7 版本不能在使用了
    23         $postStr = file_get_contents('php://input');
    24 
    25         //extract post data
    26         if (!empty($postStr)){
    27                 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
    28                 $fromUsername = $postObj->FromUserName;
    29                 $toUsername = $postObj->ToUserName;
    30                 $keyword = trim($postObj->Content);
    31                 $time = time();
    32                 $textTpl = "<xml>
    33 
    34                             <ToUserName><![CDATA[%s]]></ToUserName>
    35 
    36                             <FromUserName><![CDATA[%s]]></FromUserName>
    37 
    38                             <CreateTime>%s</CreateTime>
    39 
    40                             <MsgType><![CDATA[%s]]></MsgType>
    41 
    42                             <Content><![CDATA[%s]]></Content>
    43 
    44                             <FuncFlag>0</FuncFlag>
    45 
    46                             </xml>";
    47 
    48                 if(!empty( $keyword ))
    49 
    50                 {
    51                     $msgType = "text";
    52 
    53                     $contentStr = "Welcome to weixin world!";
    54 
    55                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    56 
    57                     echo $resultStr;
    58 
    59                 }else{
    60                     echo "Input something...";
    61                 }
    62         }else {
    63             echo "";
    64             exit;
    65         }
    66     }
    67 
    68     private function checkSignature()
    69     {
    70         $signature = $_GET["signature"];
    71         $timestamp = $_GET["timestamp"];
    72         $nonce = $_GET["nonce"];
    73         $token = TOKEN;
    74         $tmpArr = array($token, $timestamp, $nonce);
    75         sort($tmpArr);
    76         $tmpStr = implode( $tmpArr );
    77         $tmpStr = sha1( $tmpStr );
    78         if( $tmpStr == $signature ){
    79             return true;
    80         }else{
    81             return false;
    82         }
    83     }
    84 }
    View Code
  3. 接下来就是开发了(参考微信文档)被动回复模板
  4. postman安装
  5. https://www.cnblogs.com/mchina/category/486546.html
  6. 被动回复图片等素材类消息时,需要获取mediaid ,获取mediaid需要先获取access_token,获取access_token方法:
     1 <?php
     2 
     3 class Curl
     4 {
     5 
     6     /**
     7      * @param url
     8      * @return 
     9      */
    10     public static function get($url)
    11     {
    12         $ch = curl_init();
    13         curl_setopt($ch, CURLOPT_URL, $url);
    14         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    15         //超时时间10秒,超过十秒未响应则关闭
    16         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    17         $res = curl_exec($ch);
    18         curl_close($ch);
    19         return $res;
    20     }
    21 
    22     //post
    23     public static function post($url,$data)
    24     {
    25         $ch = curl_init();
    26         curl_setopt($ch, CURLOPT_URL, $url);
    27         curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    28         //以post方式
    29         curl_setopt($ch,CURLOPT_POST,1);
    30         //post数据
    31         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    32         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    33         $res = curl_exec($ch);
    34         curl_close($ch);
    35         return $res;
    36     }
    37 
    38     
    39     //模拟发送file请求 (文件上传)
    40     /**
    41      * @param $url  请求的url地址   eg: http://www.a.com/index.php
    42      * @param $data 普通字段值    eg: ['username'=>'abc' , 'email'=>'1121@qq.com']
    43      * @param $file 文件上传字段 路径一定要为绝对路径 eg: ['img'=>'D:/1.jpg','profile'=>'D:/2.jpg'] 
    44      * @param $header  头信息数组  eg: ['user-agent: abc','referer: www.baidu.com']
    45      */
    46     public static function ufile($url, $data, $file, $header) {
    47         $ch = curl_init($url);
    48 
    49         //
    50         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    51         curl_setopt($ch, CURLOPT_POST, 1);
    52         //实例化curlFIle  class   这里必须要使用绝对路径   php5.5版本之前  
    53 
    54         if(!empty($file)) {
    55             $tmp = array();
    56             foreach ($file as $key => $value) {
    57                 $tmp[$key] = new curlFile($value);
    58                 // $tmp[$key] = '@'.$value;
    59             }
    60             $data = array_merge($data, $tmp);
    61         }
    62 
    63         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    64 
    65         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    66         if(!empty($header)){
    67             curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    68         }
    69 
    70         //获取结果
    71         $res = curl_exec($ch);
    72 
    73         $r =curl_error($ch);
    74 
    75         curl_close($ch);
    76 
    77         return $res;
    78     }
    79 }
    View Code
     1 include './Curl.class.php';
     2 
     3 //获取token
     4 function getToken()
     5 {
     6     $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8be980fd823b553e&secret=780815aae6772377c21efa3c2feb9b4b";
     7     $res = Curl::get($url);  //返回的是字符串
     8     // var_dump($res);
     9     $res = json_decode($res,true);  //要加第二个参数true,转换成数组
    10     // var_dump($res);
    11     return $res['access_token'];
    12 }
    13 // echo getToken();
    View Code

    获取到token后,再获取mediaID,使用封装的curl类中上传文件方法,但是这里有一点注意:文件的路径必须是绝对路径。当不确定文件在服务器上的 绝对路径的时候,可以使用函数  realpath() ,非常好用。代码:

     1 <?php
     2 
     3 include './Curl.class.php';
     4 
     5 //获取token
     6 function getToken()
     7 {
     8     $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8be980fd823b553e&secret=780815aae6772377c21efa3c2feb9b4b";
     9     $res = Curl::get($url);  //返回的是字符串
    10     // var_dump($res);
    11     $res = json_decode($res,true);  //要加第二个参数true,转换成数组
    12     // var_dump($res);
    13     return $res['access_token'];
    14 }
    15 // echo getToken();
    16 
    17 //获取mediaID
    18  function mediaId()
    19  {
    20      //********************************找不到文件的绝对路径的时候,可以使用realpath()函数
    21      $token = getToken();
    22      //获取文件的绝对路径
    23      $path = realpath('./statics/images/1.jpg');
    24      // var_dump($path);
    25      //把要上传的文件的绝对路径放在一个数组中
    26      $filePath = ['media'=>$path];
    27      $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$token}&type=image";
    28      var_dump($url);
    29      $mediaID = Curl::ufile($url,array(),$filePath,array());
    30      var_dump($mediaID);
    31  }
    32 
    33  echo mediaId();
    View Code

    这样就能获取到mediaID,然后就可以实现回复图片了。(需要把mediaid字符串复制放进去)(对了,可以吧mediaid全部存到数据库中) 

原文地址:https://www.cnblogs.com/bneglect/p/10553924.html