微信公众号图文回复验证码并写入数据库的基本思路
程序员文章站
2022-04-04 09:56:37
接了个小活:要求公众号中用户回复1,公众号被动回复7位数验证码,同时把用户openId和验证码写入数据库 简单写了各测试demo:工具 thinkphp 订阅号子钦有话说内申请的测试账号 接口配置信息修改 Controller控制器 输入1得到被动回复验证码(里面大多数代码与标题无关,想必大家能用到 ......
接了个小活:要求公众号中用户回复1,公众号被动回复7位数验证码,同时把用户openid和验证码写入数据库
简单写了各测试demo:工具 thinkphp 订阅号子钦有话说内申请的测试账号
接口配置信息修改
controller控制器 输入1得到被动回复验证码(里面大多数代码与标题无关,想必大家能用到,所以没有删除)
<?php namespace home\controller; use home\common\commoncontroller; /** *@parame 微信公众号开发 */ class wechatcontroller extends commoncontroller { //配置接口信息接入api public function index() { //1.获得参数 signature nonce token timestamp echostr $nonce = $_get['nonce']; $token = 'zhangmangde'; $timestamp = $_get['timestamp']; $echostr = $_get['echostr']; $signature = $_get['signature']; //2.拼成数组,然后按字典序排序 $array = array(); $array = array($nonce,$timestamp,$token); sort($array); //3.拼成字符串,sha1加密,然后和$signature进行比较 $str = sha1(implode($array)); if($str == $signature && $echostr){ //第一次接入微信api的时候 echo $echostr; exit; }else{ $this->responsemsg(); } } /*public function show(){ echo 'zhangmangde'; }*/ //接受事件,推送并回复 public function responsemsg(){ //1.获取到微信推送过来的post数据(xml格式) $postarr = $globals['http_raw_post_data']; //2.处理消息类型,并设置回复内容和类型 /*<xml> <tousername><![cdata[touser]]></tousername> <fromusername><![cdata[fromuser]]></fromusername> <createtime>123456789</createtime> <msgtype><![cdata[event]]></msgtype> <event><![cdata[subscribe]]></event> </xml>*/ $postobj = simplexml_load_string($postarr);//将xml字符串载入对象中 //$postobj->tousername = ''; //$postobj->fromusername = ''; //$postobj->createtime = ''; //$postobj->msgtype = ''; //$postobj->event = ''; //判断该数据包是否是订阅的事件推送 if(strtolower($postobj->msgtype) == 'event'){ //如果是关注subcribe事件 if(strtolower($postobj->event) == 'subscribe'){ //回复用户消息 $arr = array( array( 'title' => '欢迎关注子钦的公众号开发版哟^^~~^^', 'description' => '张子钦很酷哦 or ziqin is very cool 哈哈!关注有惊喜哦', 'picurl' => 'http://waphd.simufengyun.com/public/home/images/zmd123.png', 'url' => 'http://wap.simufengyun.com/', ), ); //实例化模型 $wechatmodel = new \home\model\wechatmodel;//实例化时,一定要注意model的路径问题 下面a()方法是测试路径问题 $wechatmodel->responsesubscribe($postobj,$arr);//调用模型中的方法 } //点击事件 if(strtolower($postobj->event) == 'click'){ //如果是自定义菜单中的event->click if(strtolower($postobj->eventkey) == 'item1'){ $content = "这是菜单一事件的推送"; } if(strtolower($postobj->eventkey) == 'songs'){ $content = "这是歌曲事件的推送"; } //实例化模型 //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } //跳转事件 if(strtolower($postobj->event) == 'view'){ //如果是自定义菜单中的event->view $content = "要跳转的链接是".$postobj->eventkey; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } // if(strtolower($postobj->event) == 'scan'){ //自定义菜单中的event->scan $content = "扫描场景".$postobj->eventkey; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'location'){ //自定义菜单中的event->location $content = "上传位置:纬度".$postobj->latitude.";经度".$postobj->longitude; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'scancode_waitmsg'){ //自定义菜单中的event->scancode_waitmsg $content = "扫描带提示:类型".$postobj->scancodeinfo->scantype."结果:".$postobj->scancodeinfo->scanresult; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'scancode_push'){ //自定义菜单中的event->scancode_push $content = "扫码推事件"; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'pic_sysphoto'){ //自定义菜单中的event->pic_sysphoto $content = "系统拍照"; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'pic_weixin'){ //自定义菜单中的event->pic_weixin $content = "相册发图:数量".$postobj->sendpicsinfo->count; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'pic_photo_or_album'){ //自定义菜单中的event->pic_photo_or_album $content = "拍照或者相册:数量".$postobj->sendpicsinfo->count; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } if(strtolower($postobj->event) == 'location_select'){ //自定义菜单中的event->location_select $content = "发送位置:标签".$postobj->sendlocationinfo->label; //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } } //判断是否是纯文本 /*if(strtolower($postobj->msgtype) == 'text'){ switch(trim($postobj->content)){ case 1: $content = '您输入的数字是1'; break; case 2: $content = '您输入的数字是2'; break; case 3: $content = '您输入的数字是3'; break; case '英文': $content = 'ziqin is very good'; break; case '电话': $content = '15236272691'; break; case '百度': $content = '<a href="https://www.baidu.com">百度搜索</a>'; break; } $template = "<xml> <tousername><![cdata[%s]]></tousername> <fromusername><![cdata[%s]]></fromusername> <createtime>%s</createtime> <msgtype><![cdata[%s]]></msgtype> <content><![cdata[%s]]></content> </xml>"; $touser = $postobj->fromusername; $fromuser = $postobj->tousername; $time = time(); $msgtype = 'text'; echo sprintf($template,$touser,$fromuser,$time,$msgtype,$content); }*/ //用户发送tuwen1关键字的时候,发送一个图文 或者发送纯文本 或者多图文 if(strtolower($postobj->msgtype) == 'text' && trim($postobj->content)=='tuwen1'){ $arr = array( array( 'title' => '私募风云网年度峰会报名开始啦', 'description' => 'ziqin is very cool', 'picurl' => 'http://wap.simufengyun.com//public/home/images/ban1.jpg', 'url' => 'http://wap.simufengyun.com/', ), array( 'title' => '私募风云网官方网站', 'description' => 'simufengyun is very cool', 'picurl' => 'http://wap.simufengyun.com//public/home/images/ban2.jpg', 'url' => 'http://wap.simufengyun.com/', ), array( 'title' => '我是子钦有话说', 'description' => 'ziqin is very cool', 'picurl' => 'http://wap.simufengyun.com//public/home/images/ban3.jpg', 'url' => 'http://wap.simufengyun.com/', ), ); //实例化模型 $wechatmodel = new \home\model\wechatmodel;//实例化时,一定要注意model的路径问题 下面a()方法是测试路径问题 $wechatmodel->responsenews($postobj,$arr);//调用模型中的方法 }else{ switch(trim($postobj->content)){ case 1: $openid = $postobj->fromusername;//获取用户openid
$content .= '您的验证码是:'.getsrandchar(7)."\n";//回复随机7位数验证码
$content .='您的openid是:'.$openid;
//此处可以操作写入数据库 break; case 2: $content = '您输入的数字是2'; break; case 3: $content = '您输入的数字是3'; break; case 4: $content = '张'; break; case '英文': $content = 'ziqin is very good'; break; case '电话': $content = '15236272691'; break; case '百度': $content = '<a href="https://www.baidu.com">百度搜索</a>'; break; default: $content = "没有找到相关信息"; break; } //实例化模型 $wechatmodel = new \home\model\wechatmodel; $wechatmodel->responsetext($postobj,$content);//调用方法 } } //接收事件消息 /* 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": $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." \n技术支持 方倍工作室"; 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; }*/ //采集远程数据 /*function http_curl(){ //获取远程数据 //1.初始化curl $ch = curl_init(); $url = 'http://wap.simufengyun.com'; //2.设置curl参数 curl_setopt($ch,curlopt_url,$url); curl_setopt($ch,curlopt_returntransfer,1); //3.采集 $output = curl_exec($ch); //4.关闭 curl_close($ch); var_dump($output); }*/ /** *$url 接口url string *$type 请求类型 string *$res 返回数据类型 string *$arr post请求参数 string */ function http_curl($url,$type='get',$res='json',$arr=''){ //获取远程数据 //1.初始化curl $ch = curl_init(); //$url = 'http://wap.simufengyun.com'; //2.设置curl参数 curl_setopt($ch,curlopt_url,$url); curl_setopt($ch,curlopt_returntransfer,1); if($type == 'post'){ curl_setopt($ch,curlopt_post,1); curl_setopt($ch,curlopt_postfields,$arr); } //3.采集 $output = curl_exec($ch); //4.关闭 curl_close($ch); if($res == 'json'){ if(curl_error($ch)){ //请求失败,返回错误信息 return curl_error($ch); }else{ return json_decode($output,true); } } //var_dump($output); } //获取access_token和微信服务器ip地址 /*function getwxaccesstoken(){ //1.请求url地址 $appid = 'wxd3a57f24b4e021b2'; $appsecret = 'feffb8659a14792c9323fdf27b4b35f7'; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; //2.初始化 $ch = curl_init(); //3.设置参数 curl_setopt($ch,curlopt_url,$url); curl_setopt($ch,curlopt_returntransfer,1); //4.调用接口(采集) $res = curl_exec($ch); //5.关闭curl curl_close($ch); if(curl_errno($ch)){ var_dump(curl_error($ch)); } $arr = json_decode($res,true); var_dump($arr); }*/ //获取微信服务器ip function getwxserverip(){ $accesstoken = "9e_ha1sd77bprq0gqhyu4g5zplxkzm3yrxa1za0yyyqpwjmxif5ai3nrnube6xesqtqr5sbhhtkvyx5xkcnxkcxn6gvpgvggbcswblmmtqefd1mgxhobq3nktukwfxvvslxgabafyk"; $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$accesstoken; $ch = curl_init(); curl_setopt($ch,curlopt_url,$url); curl_setopt($ch,curlopt_returntransfer,1); $res = curl_exec($ch); curl_close($ch); if(curl_errno($ch)){ var_dump(curl_error($ch)); } $arr = json_decode($res,true); echo "<pre>"; var_dump($arr); echo "<pre>"; } //测试实例化model模型路径问题 public function a(){ $wechatmodel = new \home\model\wechatmodel; var_dump($wechatmodel); } //返回access_token; access_token存入session避免重复调用 public function getwxaccesstoken(){ //将access_token 存在session/cookie中 if($_session['access_token'] && $_session['expires_time']>time()){ //如果access_token在session并没有过期 return $_session['access_token']; }else{ //如果access_token在session不存在或者已经过期,重新取access_token $appid = 'wxd3a';//此处用你自己的appid $appsecret = 'feffb8659a14792c9323fdf';//用你自己的appsecret $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; $res = $this->http_curl($url,'get','json'); $access_token = $res['access_token']; //将重新获取到的access_token存入session $_session['access_token'] = $access_token; $_session['expires_time'] = time() + 7200; return $access_token; } } //自定义菜单 public function defineditem(){ //创建微信菜单 //目前微信接口的调用方式都是通过curl post/get header('content-type:text/html;charset=utf-8');//解决中文乱码 echo $access_token = $this->getwxaccesstoken(); $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token; $postarr = array( 'button'=>array( array( 'name'=>urlencode('子钦'), 'type'=>'click', 'key'=>'item1', ),//第一个一级菜单 array( 'name'=>urlencode('子钦语录'), 'sub_button'=>array( array( 'name'=>urlencode('歌曲'), 'type'=>'click', 'key'=>'songs', ),//第一个二级菜单 array( 'name'=>urlencode('私募风云网'), 'type'=>'view', 'url'=>'http://wap.simufengyun.com', ),//第二个二级菜单 ), ),//第二个一级菜单 array( 'name' =>urlencode('子钦心语'), 'type' =>'view', 'url' => 'http://wap.simufengyun.com', ),//第三个一级菜单 ), ); //其他按钮类型 $postarr2 = array( 'button'=>array( array( 'name'=>urlencode('扫码'), 'sub_button'=>array( array( 'type'=>"scancode_waitmsg", 'name'=>urlencode("扫码带提示"), 'key'=>"rselfmenu_0_0", ),//第一个二级菜单 array( 'type'=>"scancode_push", 'name'=>urlencode("扫码推事件"), 'key'=>"rselfmenu_0_1", ),//第二个二级菜单 ), ),//第一个一级菜单 array( 'name'=>urlencode("发图"), 'sub_button'=>array( array( 'type'=>'pic_sysphoto', 'name'=>urlencode("系统拍照发图"), 'key'=>"rselfmenu_1_0", ),//第一个二级菜单 array( 'type'=>'pic_photo_or_album', 'name'=>urlencode("拍照或者相册发图"), 'key'=>"rselfmenu_1_1", ),//第二个二级菜单 array( 'type'=>'pic_weixin', 'name'=>urlencode("微信相册发图"), 'key'=>"rselfmenu_1_2", ),//第三个二级菜单 ), ),//第二个一级菜单 array( 'name'=>urlencode("发送位置"), 'type'=>"location_select", "key"=>"rselfmenu_2_0", ),//第三个一级菜单 ), ); /*echo '<hr />'; var_dump($postarr); echo '<hr />'; echo $postjson = urldecode(json_encode($postarr)); $res = $this->http_curl($url,'post','json',$postjson); echo "<hr/>"; var_dump($res);*/ echo '<hr />'; var_dump($postarr2); echo '<hr />'; echo $postjson = urldecode(json_encode($postarr2)); $res = $this->http_curl($url,'post','json',$postjson); echo "<hr/>"; var_dump($res); }
}
model类
<?php namespace home\model; use think\model; class wechatmodel extends model{ //多图文的回复微信方法 public function responsenews($postobj,$arr) { $touser = $postobj->fromusername; $fromuser = $postobj->tousername; $time = time(); $template = "<xml> <tousername><![cdata[%s]]></tousername> <fromusername><![cdata[%s]]></fromusername> <createtime>%s</createtime> <msgtype><![cdata[%s]]></msgtype> <articlecount>".count($arr)."</articlecount> <articles>"; foreach($arr as $k=>$v){ $template .="<item> <title><![cdata[".$v['title']."]]></title> <description><![cdata[".$v['description']."]]></description> <picurl><![cdata[".$v['picurl']."]]></picurl> <url><![cdata[".$v['url']."]]></url> </item>"; } $template .= "</articles> </xml>"; echo sprintf($template,$touser,$fromuser,$time,'news'); } //回复单文本 public function responsetext($postobj,$content){ $template = "<xml> <tousername><![cdata[%s]]></tousername> <fromusername><![cdata[%s]]></fromusername> <createtime>%s</createtime> <msgtype><![cdata[%s]]></msgtype> <content><![cdata[%s]]></content> </xml>"; $touser = $postobj->fromusername; $fromuser = $postobj->tousername; $time = time(); $msgtype = 'text'; echo sprintf($template,$touser,$fromuser,$time,$msgtype,$content); } //回复用户关注消息 public function responsesubscribe($postobj,$arr){ $this->responsenews($postobj,$arr); } }
7位验证的函数方法
//生成随机数,length长度 function getsrandchar($length){ $str = null; $strpol = "0123456789abcdefghijklmnopqrstuvwxyz";//不区分大小写
//$strpol = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";//区分大小写 $max = strlen($strpol)-1; for($i=0;$i<$length;$i++){ $str.=$strpol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数 } return $str; }
有不明白的加微信咨询zmd1047773569
下一篇: Tomcat的jvm配置