您的位置:首页 > 移动开发 > 微信开发

微信接口开发 php版的

2015-09-30 15:57 639 查看
<?php
define("TOKEN", "weixin");
define('APP_ID', 'wx1ef130fb414dc2d2');//改成自己的APPID
define('APP_SECRET', 'f4c4862dad3fe3f1c72eb8a3919e1b4d');//改成自己的APPSECRET

$wechatObj = new wechatCallbackapiTest();
$wechatObj->Run();

class wechatCallbackapiTest
{
private $fromUsername;
private $toUsername;
private $times;
private $keyword;
private $app_id;
private $app_secret;
private $openId;
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
exit;
}
}

public function Run()
{
if (isset($_GET['echostr'])) {
$this->valid();
}else{
$this->responseMsg();
$newpic = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>";
$msgType = "news";
$title = "驻马店特价网“抢大白”活动由《中国驻马店APP》举办"; //标题
$desription = "所有小朋友!青少年!所有的帅哥美女们!(报名完全免费)萌物!暖男!你忠诚的伙伴!如果我有个大白就好了!画出你心里的大白,通过拉投票,免费领大白毛绒萌物啦!".$this->userInfo();;
$image = "http://www.zzasp.com/images/dabai_top640.jpg"; //图片地址
$turl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1ef130fb414dc2d2&redirect_uri=http://www.zzasp.com/index.php&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect"; //链接地址
$resultStr = sprintf($newpic, $this->fromUsername, $this->toUsername, $this->times, $msgType, $title,$desription,$image,$turl);
echo $resultStr;
//$arr[]= "您好,这是自动回复,我现在不在,有事请留言,我会尽快回复你的^_^";
//echo $this->make_xml("text",$arr);
}
}

private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];

$token = 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()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//返回回复数据
if (!empty($postStr)){
$access_token = $this->get_access_token();//获取access_token
$this->createmenu($access_token);//创建菜单
//$this->delmenu($access_token);//删除菜单
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->fromUsername = $postObj->FromUserName;//发送消息方ID
$this->toUsername = $postObj->ToUserName;//接收消息方ID
$this->keyword = trim($postObj->Content);//用户发送的消息
$this->times = time();//发送时间
$MsgType = $postObj->MsgType;//消息类型
if($MsgType=='event'){
$MsgEvent = $postObj->Event;//获取事件类型
if ($MsgEvent=='subscribe') {//订阅事件

/*此处可以直接用make_xml("news",$arr)后期扩展*/
$newpic = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>";
$msgType = "news";
$title = "驻马店特价网“抢大白”活动由《中国驻马店APP》举办"; //标题
$desription = "所有小朋友!青少年!所有的帅哥美女们!(报名完全免费)萌物!暖男!你忠诚的伙伴!如果我有个大白就好了!画出你心里的大白,通过拉投票,免费领大白毛绒萌物啦!".$this->userInfo();
$image = "http://www.zzasp.com/images/dabai_top640.jpg"; //图片地址
$turl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1ef130fb414dc2d2&redirect_uri=http://www.zzasp.com/index.php&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect"; //链接地址
$resultStr = sprintf($newpic, $this->fromUsername, $this->toUsername, $this->times, $msgType, $title,$desription,$image,$turl);
echo $resultStr;
//$arr[] = "你好,我是xxx,现在我们是好友咯![愉快][玫瑰]";
//echo $this->make_xml("text",$arr);
exit;
}elseif ($MsgEvent=='CLICK') {//点击事件
$EventKey = $postObj->EventKey;//菜单的自定义的key值,可以根据此值判断用户点击了什么内容,从而推送不同信息
$arr[] = $EventKey;
/*此处可以直接用make_xml("news",$arr)后期扩展*/
$newpic = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>";
$msgType = "news";
$title = "驻马店特价网“抢大白”活动由《中国驻马店APP》举办"; //标题
$desription = "所有小朋友!青少年!所有的帅哥美女们!(报名完全免费)萌物!暖男!你忠诚的伙伴!如果我有个大白就好了!画出你心里的大白,通过拉投票,免费领大白毛绒萌物啦!".$this->userInfo();
$image = "http://www.zzasp.com/images/dabai_top640.jpg"; //图片地址
$turl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1ef130fb414dc2d2&redirect_uri=http://www.zzasp.com/index.php&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect"; //链接地址
$resultStr = sprintf($newpic, $this->fromUsername, $this->toUsername, $this->times, $msgType, $title,$desription,$image,$turl);
echo $resultStr;

//echo $this->make_xml("news",$arr);
exit;
}
elseif($MsgEvent=='unsubscribe'){
$iphost = '116.255.150.169';
$dataUser = 'dabaibaby_f';//数据库用户名
$dataPWD = 'd367dde';//数据库密码
$dataB = 'dabaibaby';//数据库名称
$link = mysqli_connect($iphost, $dataUser, $dataPWD, $dataB, '4007');//创建数据库链接,推荐使用mysqli
$sql = "Delete from dv_user_openid WHERE weixinID='".$this->fromUsername."'";
mysqli_query($link, 'set names utf8');
mysqli_query($link, $sql);
unset($_SESSION['nameisCheck']);
exit;
}
}
}else {
echo "微信公众平台";
}

}

/**
* 获取access_token
*/
private function get_access_token()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APP_ID."&secret=".APP_SECRET;
$data = json_decode(file_get_contents($url),true);
if($data['access_token']){
return $data['access_token'];
}else{
return "获取access_token错误";
}
}

public function createmenu($access_token)
{
$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
$arr = array(
'button' =>array(
array(
'name'=>urlencode("领大白"),
'sub_button'=>array(
array(
'name'=>urlencode("领大白"),
'type'=>'click',
'key'=>'dddd'
))
),
array(
'name'=>urlencode("商家推荐"),
'sub_button'=>array(
array(
'name'=>urlencode("舌尖美食"),
'type'=>'view',
'url'=>'http://dwz.cn/Bw4aW'
),
array(
'name'=>urlencode("家政服务"),
'type'=>'view',
'url'=>'http://dwz.cn/Bw4eR'
),
array(
'name'=>urlencode("二手转让"),
'type'=>'view',
'url'=>'http://dwz.cn/Bw4h1'
),
array(
'name'=>urlencode("宾馆住宿"),
'type'=>'view',
'url'=>'http://dwz.cn/Bw4ju'
) ,
array(
'name'=>urlencode("教育培训"),
'type'=>'view',
'url'=>'http://dwz.cn/Bw4kP'
)
)
),
array(
'name'=>urlencode("实用工具"),
'sub_button'=>array(
array(
'name'=>urlencode("实用查询"),
'type'=>'view',
'url'=>'http://t.cn/8Floqzc'
),
array(
'name'=>urlencode("今日运势"),
'type'=>'view',
'url'=>'http://t.cn/zOcZDeP'
),
array(
'name'=>urlencode("影院查询"),
'type'=>'view',
'url'=>'http://t.cn/z8jor9v'
),
array(
'name'=>urlencode("酒店查询"),
'type'=>'view',
'url'=>'http://t.cn/RPtemiW'
) ,
array(
'name'=>urlencode("天气早知道"),
'type'=>'view',
'url'=>'http://t.cn/zQyRCv2'
)
)
)
)
);
$jsondata = urldecode(json_encode($arr));
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$jsondata);
curl_exec($ch);
curl_close($ch);
}
/**
* 查询菜单
* @param $access_token 已获取的ACCESS_TOKEN
*/

private function getmenu($access_token)
{
# code...
$url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$access_token;
$data = file_get_contents($url);
return $data;
}
/**
* 删除菜单
* @param $access_token 已获取的ACCESS_TOKEN
*/

private function delmenu($access_token)
{
# code...
$url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$access_token;
$data = json_decode(file_get_contents($url),true);
if ($data['errcode']==0) {
# code...
return true;
}else{
return false;
}
}

private function make_xml($type,$value_arr,$o_arr=array(0)){
//=================xml header============
$con="<xml>
<ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
<FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
<CreateTime>{$this->times}</CreateTime>
<MsgType><![CDATA[{$type}]]></MsgType>";

//=================type content============
switch($type){

case "text" :
$con.="<Content><![CDATA[{$value_arr[0]}]]></Content>
<FuncFlag>{$o_arr}</FuncFlag>";
break;

case "news" :
$con.="<ArticleCount>{$o_arr[0]}</ArticleCount>
<Articles>";
foreach($value_arr as $id=>$v){
if($id>=$o_arr[0]) break; else null; //判断数组数不超过设置数
$con.="<item>
<Title><![CDATA[{$v[0]}]]></Title>
<Description><![CDATA[{$v[1]}]]></Description>
<PicUrl><![CDATA[{$v[2]}]]></PicUrl>
<Url><![CDATA[{$v[3]}]]></Url>
</item>";
}
$con.="</Articles>
<FuncFlag>{$o_arr[1]}</FuncFlag>";
break;
} //end switch
//=================end return============
$con.="</xml>";
return $con;
}
/**
* 获取关注用户信息
*/
public function userInfo()
{
$access_token = $this->get_access_token();
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//返回回复数据
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); //这个很重要没有这个会出现错误代码{"errcode:4003","errmsg":"invalid openid"}
$openId = $postObj->FromUserName;//发送消息方ID
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openId;
$data = file_get_contents($url);
/**正确的数据是这样的格式
* {
"subscribe": 1,
"openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
"nickname": "Band",
"sex": 1,
"language": "zh_CN",
"city": "广州",
"province": "广东",
"country": "中国",
"headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
"subscribe_time": 1382694957,
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
"remark": "",
"groupid": 0
}
*/
//获取错误的代码信息
//出现错误代码{"errcode:4003","errmsg":"invalid openid"}
$obj = json_decode($data);
if($obj->subscribe == '1'){
$iphost = '116.255.150.169';
$dataUser = 'dabaibaby_f';//数据库用户名
$dataPWD = 'd367dde';//数据库密码
$dataB = 'dabaibaby';//数据库名称
$link = mysqli_connect($iphost, $dataUser, $dataPWD, $dataB, '4007');//创建数据库链接,推荐使用mysqli
$weixinID=$obj->openid;
$sql ="select weixinID from dv_user_openid where weixinID="."'".$weixinID."'";
mysqli_query($link, 'set names utf8');
$res = mysqli_query($link, $sql);
$row = mysqli_fetch_row($res);
if($row[0]!=''){
//				return "已经存在数据";
}else{
mysqli_query($link, 'set names utf8');
$sql="insert into dv_user_openid (weixinID) values ('$weixinID')";
$res=mysqli_query($link,$sql);
//                if($res){
//                    return "插入成功".$sql;
//                }
}
}else{
return $obj->errcode;
}

//return $data;
}
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: