<?php
namespace app\index\controller;
use think\Controller;
class index extends Controller
{
public function index(){
//获得参数 signature nonce token timestamp echostr
$nonce = $_GET['nonce'];
$token = 'imooc';
$timestamp = $_GET['timestamp'];
$echostr = isset($_GET['echostr'])?$_GET['echostr']:'';
$signature = $_GET['signature'];
//形成数组,然后按字典序排序
$array = array();
$array = array($nonce, $timestamp, $token);
sort($array);
//拼接成字符串,sha1加密 ,然后与signature进行校验
$str = sha1( implode( $array ) );
if( $str == $signature && $echostr ){
//第一次接入weixin api接口的时候
echo $echostr;
exit;
}else{
$this->reponseMsg();
}
}
// 接收事件推送并回复
public function reponseMsg(){
//获取微信推送过来的数据(xml格式)
$postArr = $GLOBALS["HTTP_RAW_POST_DATA"];
$tmpstr = $postArr;
//处理消息,并设置回复类型
$postObj = simplexml_load_string($postArr);
//关注回复
if (strtolower($postObj->MsgType) =="event"){
//如果是关注事件
if(strtolower($postObj->Event) == "subscribe"){
//回复用户消息
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time = time();
$msgType = "text";
$content = "欢迎关注我的公众号:\n 我的公众号"."\n\n微信用户的openid:\n".$postObj->FromUserName."\n\n如需关键字测试请输入:\n( 你好 || phone || composer )\n\n图文测试请输入:\n( 单图文 || 多图文 )";
$template = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml> ";
$info = sprintf( $template,$toUser,$fromUser,$time,$msgType,$content);
echo $info;
$this->sendTempMsg();
}
}
//回复图文消息
if (strtolower($postObj->MsgType) == "text" && trim($postObj->Content == "单图文")){
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$array = array(
array(
"title"=>"微博",
"description"=>"微博首页!",
"picUrl"=>"http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg",
"url"=>"http://weibo.com/",
),
array(
"title"=>"微博2",
"description"=>"微博首页2!",
"picUrl"=>"http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg",
"url"=>"http://weibo.com/",
),
array(
"title"=>"微博3",
"description"=>"微博首页3!",
"picUrl"=>"http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg",
"url"=>"http://weibo.com/",
),
);
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>".count($array)."</ArticleCount>
<Articles>";
foreach ($array as $key => $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>";
$time = time();
echo sprintf( $template,$toUser,$fromUser,$time,"news");
}elseif (strtolower($postObj->MsgType) == "text" && trim($postObj->Content == "多图文")) {
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$array = array(
array(
"title"=>"腾讯网",
"description"=>"腾讯首页!",
"picUrl"=>"图片url地址",
"url"=>"http://weibo.com/",
),
array(
"title"=>"easywechat文档",
"description"=>"微信文档!",
"picUrl"=>"图片url地址",
"url"=>"http://weibo.com/",
),
array(
"title"=>"laravel学院",
"description"=>"学院君!",
"picUrl"=>"图片url地址",
"url"=>"http://weibo.com/",
),
);
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>".count($array)."</ArticleCount>
<Articles>";
foreach ($array as $key => $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>";
$time = time();
echo sprintf( $template,$toUser,$fromUser,$time,"news");
}else{
switch ($postObj->Content) {
case '你好':
$content = "hello 你好!";
break;
case 'phone':
$content = "我的手机号码:\n12339475";
break;
case 'php':
$content = "我是php";
break;
case 'composer':
$content = "<a href='http://www.baidu.com'>composer</a>";
break;
default:
$content = '无法匹配';
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);
}
}
//获access_token
public function getToken(){
if( isset($_SESSION['access_token']) && isset($_SESSION['expire_time']) && $_SESSION['expire_time']>time()){
echo '11';echo '<hr>';
//如果access_token在session没有过期
echo $_SESSION['access_token'];;
return $_SESSION['access_token'];
}
else{
//如果access_token比存在或者已经过期,重新取access_token
//1 请求url地址
//此处为测试账号的信息。
$appid = 'wxb12d95dcb4f3932f';
$appsecret = '3aa265b2e46e003484f046f57dc5ae91';
$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'];
//将重新获取到的aceess_token存到session
$_SESSION['access_token']=$access_token;
$_SESSION['expire_time']=time()+7000;
return $access_token;
}
}
//微信服务器ip获取
public function getWxServerIp(){
$accessToken = '13_PHDJ96-MY0aOqSQ0yw_KUtDgZeakRDj2SHLLaw7mujw5Z985WDS0kzorjUTs8ubtc5VjfuKckCydi3b4ATumKCnY190RB3LV13ImQDLB1WDIhByVg0MrUrXabFwb4Us9KThDjitqfS5mwOoDUXNiADAZCS';
$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);
if(curl_errno($ch)){
var_dump(curl_errno($ch));
}
curl_close($ch);
$arr = json_decode($res,true);
var_dump($arr);
}
public function definedItem(){
//创建微信菜单
//目前微信接口的调用方式都是通过 curl post/get
header('content-type:text/html;charset=utf-8');
$access_token=$this ->getToken();
$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://www.baidu.com'
),//第二个二级菜单
)
),
array(
'name'=>urlencode('菜单三'),
'type'=>'view',
'url'=>'http://www.qq.com',
),//第三个一级菜单
));
$postJson = urldecode(json_encode($postArr));
$res = $this->http_curl($url,'post','json',$postJson);
var_dump($res);
}
//$url 接口url string
//$type 请求类型string
//$res 返回类型string
//$arr= 请求参数string
public function http_curl($url,$type='get',$res='json',$arr=''){
//1.初始化curl
$ch =curl_init();
//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);
if($res=='json'){
if(curl_error($ch)){
//请求失败,返回错误信息
return curl_error($ch);
}else{
//请求成功,返回错误信息
return json_decode($output,true);
}
}
//4.关闭
curl_close($ch);
echo var_dump( $output );
}
//群发消息
public function sendMsgAll(){
$access_token=$this ->getToken();
$url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$access_token;
$array = array(
"touser" => "obuiT0ja_Hbg45j8ipo44yHTWRWU",
"text"=>array( "content"=>"abcdefg" ),
"msgtype"=>"text",
);
$postJson = json_encode($array);
$res = $this->http_curl($url,'post','json',$postJson);
var_dump($res);
}
public function qunfa(){
$access_token=$this ->getToken();
$url1 ="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$access_token;
$postJson1 = json_encode(array("type"=>"news","offset"=>0,"count"=>10));
$data = $this->http_curl($url1,'post','json',$postJson1);
if($data){
$data=json_decode($data,true);
$url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$access_token;
$postJson = json_encode(array("touser"=>"obuiT0ja_Hbg45j8ipo44yHTWRWU","mpnews"=>array("media_id"=>$data['item'][0]['media_id']),"msgtype"=>"mpnews","send_ignore_reprint"=>1));
$res = $this->http_curl($url,'post','json',$postJson);
}else{
echo "推送失败!";
}
}
//测试账号模板消息
public function sendTempMsg(){
$access_token=$this ->getToken();
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
$array = array(
"touser" => "obuiT0vE6Mp27-fomFL1U9jcTdEg",
"template_id"=>"NQhDps6hFCqgMrRqPGgxR7hVh4GdmnLvDf6d4ili7NI",
"url"=>"http://www.baidu.com",
"data"=>array(
'name'=> array('value'=>'ami','color'=>'#173177'),
'money'=> array('value'=>100,'color'=>'#173177'),
'date'=> array('value'=>date('Y-m-d H:i:s',time()),'color'=>'#173177'),
),
);
$postJson = json_encode($array);
$res = $this->http_curl($url,'post','json',$postJson);
var_dump($res);
}
//网页授权
public function getBaseInfo(){
//1 第一步:用户同意授权,获取code
$appid = "wxb12d95dcb4f3932f";
$redirect_uri = urlencode("http://123.56.15.254/index.php/index/index/getOpenId");
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirec";
header('location:'.$url);
}
public function getOpenId(){
//var_dump($code);
// echo '<hr>';
$appid = 'wxb12d95dcb4f3932f';
$appsecret = '3aa265b2e46e003484f046f57dc5ae91';
$code= $_GET['code'];
//2 通过code换取网页授权access_token
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
var_dump($url);
echo '<hr>';
$res = $this->http_curl($url,'get');
var_dump($res);
echo '<hr>';
}
//获取微信用户信息
public function getUserDetail(){
//1 第一步:用户同意授权,获取code
$appid = "wxb12d95dcb4f3932f";
$redirect_uri = urlencode("http://123.56.15.254/index.php/index/index/getUserInfo");
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirec";
header('location:'.$url);
}
public function getUserInfo(){
$code= $_GET['code'];
if (isset($code)){
$appid = 'wxb12d95dcb4f3932f';
$appsecret = '3aa265b2e46e003484f046f57dc5ae91';
$code= $_GET['code'];
//2 通过code换取网页授权access_token
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$res = $this->http_curl($url,'get');
$access_token = $res["access_token"];
$openid = $res["openid"];
//用户信息
$result = $this->http_curl("https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN",'get');
var_dump($result);
}else{
echo "NO CODE";
}
}
}