适用平台:window/Linux
依赖项目:EaglePHP框架
包含微信5.0 API基础接口、自定义菜单、高级接口,具体如下:
1、接收用户消息。
2、向用户回复消息。
3、接受事件推送。
4、会话界面自定义菜单。
5、语音识别。
6、客服接口。
7、OAuth2.0网页授权。
8、生成带参数二维码。
9、获取用户地理位置。
10、获取用户基本信息。
11、获取关注者列表。
12、用户分组。
复制代码 代码如下:
class WeixinChat
{
private $token;
private $appid;
private $appsecret;
private $access_token;
// 接收的数据
private $_receive = array();
private $_reply = '';
// 接口错误码
private $errCode = '';
// 接口错误信息
private $errMsg = '';
// 微信oauth登陆获取code
const CONNECT_OAUTH_AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
// 微信oauth登陆通过code换取网页授权access_token
const SNS_OAUTH_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
// 微信oauth登陆刷新access_token(如果需要)
const SNS_OAUTH_REFRESH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?';
// 通过ticket换取二维码
const SHOW_QRCODE_URL = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?';
// 微信oauth登陆拉取用户信息(需scope为 snsapi_userinfo)
const SNS_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
// 请求api前缀
const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
// 自定义菜单创建
const MENU_CREATE_URL = '/menu/create?';
// 自定义菜单查询
const MENU_GET_URL = '/menu/get?';
// 自定义菜单删除
const MENU_DELETe_URL = '/menu/delete?';
// 获取 access_token
const AUTH_URL = '/token?grant_type=client_credential&';
// 获取用户基本信息
const USER_INFO_URL = '/user/info?';
// 获取关注者列表
const USER_GET_URL = '/user/get?';
// 查询分组
const GROUPS_GET_URL = '/groups/get?';
// 创建分组
const GROUPS_CREATE_URL = '/groups/create?';
// 修改分组名
const GROUPS_UPDATE_URL = '/groups/update?';
// 移动用户分组
const GROUPS_MEMBERS_UPDATE_URL = '/groups/members/update?';
// 发送客服消息
const MESSAGE_CUSTOM_SEND_URL = '/message/custom/send?';
// 创建二维码ticket
const QRCODE_CREATE_URL = '/qrcode/create?';
public function __construct($options)
{
$this->token = isset($options['token']) ? $options['token'] : '';
$this->appid = isset($options['appid']) ? $options['appid'] : '';
$this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : '';
}
public function getRev()
{
$postStr = file_get_contents('php://input');
if($postStr)
{
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//Log::info(var_export($this->_receive, true));
}
return $this;
}
public function getRevData()
{
return $this->_receive;
}
public function getRevTo()
{
return isset($this->_receive['ToUserName']) ? $this->_receive['ToUserName'] : false;
}
public function getRevFrom()
{
return isset($this->_receive['FromUserName']) ? $this->_receive['FromUserName'] : false;
}
public function getRevCTime()
{
return isset($this->_receive['CreateTime']) ? $this->_receive['CreateTime'] : false;
}
public function getRevType()
{
return isset($this->_receive['MsgType']) ? $this->_receive['MsgType'] : false;
}
public function getRevId()
{
return isset($this->_receive['MsgId']) ? $this->_receive['MsgId'] : false;
}
public function getRevText()
{
if(isset($this->_receive['Content'])) return trim($this->_receive['Content']);
elseif(isset($this->_receive['Recognition'])) return trim($this->_receive['Recognition']);
else return false;
}
public function getRevImage()
{
if(isset($this->_receive['PicUrl'])){
return array(
'picUrl' => $this->_receive['PicUrl'], //图片链接
'mediaId' => $this->_receive['MediaId'] //图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
);
}
return false;
}
public function getRevVoice()
{
if(isset($this->_receive['MediaId'])){
return array(
'mediaId' => $this->_receive['MediaId'], //语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
'format' => $this->_receive['Format'] //语音格式,如amr,speex等
);
}
return false;
}
public function getRevVideo()
{
if(isset($this->_receive['MediaId'])){
return array(
'mediaId' => $this->_receive['MediaId'], //视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
'thumbMediaId' => $this->_receive['ThumbMediaId'] //视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
);
}
return false;
}
public function getRevLocation()
{
if(isset($this->_receive['Location_X'])){
return array(
'locationX' => $this->_receive['Location_X'], //地理位置维度
'locationY' => $this->_receive['Location_Y'], //地理位置经度
'scale' => $this->_receive['Scale'], //地图缩放大小
'label' => $this->_receive['Label'] //地理位置信息
);
}
//开通了上报地理位置接口的公众号,用户在关注后进入公众号会话时,会弹框让用户确认是否允许公众号使用其地理位置。
//弹框只在关注后出现一次,用户以后可以在公众号详情页面进行操作。
elseif(isset($this->_receive['Latitude']))
{
return array(
'latitude' => $this->_receive['Latitude'], //地理位置纬度
'longitude' => $this->_receive['Longitude'], //地理位置经度
'precision' => $this->_receive['Precision'] // 地理位置精度
);
}
return false;
}
public function getRevlink()
{
if(isset($this->_receive['Title'])){
return array(
'title' => $this->_receive['Title'], //消息标题
'description' => $this->_receive['Description'], //消息描述
'url' => $this->_receive['Url'] //消息链接
);
}
return false;
}
public function getRevEvent()
{
if(isset($this->_receive['Event']))
{
return array(
'event' => strtolower($this->_receive['Event']),
'key'=> isset($this->_receive['EventKey']) ? $this->_receive['EventKey'] : ''
);
}
return false;
}
public function text($content='')
{
$textTpl = "
$this->_reply = sprintf($textTpl,
$this->getRevFrom(),
$this->getRevTo(),
Date::getTimeStamp(),
'text',
$content
);
return $this;
}
public function music($title, $desc, $musicurl, $hgmusicurl='')
{
$textTpl = '
//
$this->_reply = sprintf($textTpl,
$this->getRevFrom(),
$this->getRevTo(),
Date::getTimeStamp(),
'music',
$title,
$desc,
$musicurl,
$hgmusicurl
);
return $this;
}
public function news($data)
{
$count = count($data);
$subText = '';
if($count > 0)
{
foreach($data as $v)
{
$tmpText = '
$subText .= sprintf(
$tmpText, $v['title'],
isset($v['description']) ? $v['description'] : '',
isset($v['picUrl']) ? $v['picUrl'] : '',
isset($v['url']) ? $v['url'] : ''
);
}
}
$textTpl = '
%s
$this->_reply = sprintf(
$textTpl,
$this->getRevFrom(),
$this->getRevTo(),
Date::getTimeStamp(),
$count,
$subText
);
return $this;
}
public function reply()
{
header('Content-Type:text/xml');
echo $this->_reply;
exit;
}
public function createMenu($data)
{
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return true;
}
return false;
}
public function getMenu()
{
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function deleteMenu()
{
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return true;
}
return false;
}
public function getUserInfo($openid)
{
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function getUserList($next_openid='')
{
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function getGroup()
{
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::GROUPS_GET_URL.'access_token='.$this->access_token);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function createGroup($name)
{
if(!$this->access_token && !$this->checkAuth()) return false;
$data = array('group' => array('name' => $name));
$result = curlRequest(self::API_URL_PREFIX.self::GROUPS_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return true;
}
return false;
}
public function updateGroup($id, $name)
{
if(!$this->access_token && !$this->checkAuth()) return false;
$data = array('group' => array('id' => $id, 'name' => $name));
$result = curlRequest(self::API_URL_PREFIX.self::GROUPS_UPDATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return true;
}
return false;
}
public function updateGroupMembers($openid, $to_groupid)
{
if(!$this->access_token && !$this->checkAuth()) return false;
$data = array('openid' => $openid, 'to_groupid' => $to_groupid);
$result = curlRequest(self::API_URL_PREFIX.self::GROUPS_MEMBERS_UPDATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return true;
}
return false;
}
public function sendCustomMessage($touser, $data, $msgType = 'text')
{
$arr = array();
$arr['touser'] = $touser;
$arr['msgtype'] = $msgType;
switch ($msgType)
{
case 'text': // 发送文本消息
$arr['text']['content'] = $data;
break;
case 'image': // 发送图片消息
$arr['image']['media_id'] = $data;
break;
case 'voice': // 发送语音消息
$arr['voice']['media_id'] = $data;
break;
case 'video': // 发送视频消息
$arr['video']['media_id'] = $data['media_id']; // 发送的视频的媒体ID
$arr['video']['thumb_media_id'] = $data['thumb_media_id']; // 视频缩略图的媒体ID
break;
case 'music': // 发送音乐消息
$arr['music']['title'] = $data['title'];// 音乐标题
$arr['music']['description'] = $data['description'];// 音乐描述
$arr['music']['musicurl'] = $data['musicurl'];// 音乐链接
$arr['music']['hqmusicurl'] = $data['hqmusicurl'];// 高品质音乐链接,wifi环境优先使用该链接播放音乐
$arr['music']['thumb_media_id'] = $data['title'];// 缩略图的媒体ID
break;
case 'news': // 发送图文消息
$arr['news']['articles'] = $data; // title、description、url、picurl
break;
}
if(!$this->access_token && !$this->checkAuth()) return false;
$result = curlRequest(self::API_URL_PREFIX.self::MESSAGE_CUSTOM_SEND_URL.'access_token='.$this->access_token, $this->jsonEncode($arr), 'post');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return true;
}
return false;
}
public function checkAuth()
{
// 从缓存中获取access_token
$cache_flag = 'weixin_access_token';
$access_token = cache($cache_flag);
if($access_token)
{
$this->access_token = $access_token;
return true;
}
// 请求微信服务器获取access_token
$result = curlRequest(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$this->appid.'&secret='.$this->appsecret);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0))
{
$this->error($jsonArr);
}
else
{
$this->access_token = $jsonArr['access_token'];
$expire = isset($jsonArr['expires_in']) ? intval($jsonArr['expires_in'])-100 : 3600;
// 将access_token保存到缓存中
cache($cache_flag, $this->access_token, $expire, Cache::FILE);
return true;
}
}
return false;
}
public function redirectGetOauthCode($redirect_uri, $scope=0, $state='')
{
$scope = ($scope == 0) ? 'snsapi_base' : 'snsapi_userinfo';
$url = self::CONNECT_OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
redirect($url);
}
public function getSnsAccessToken($code)
{
$result = curlRequest(self::SNS_OAUTH_ACCESS_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function refershToken($refresh_token)
{
$result = curlRequest(self::SNS_OAUTH_REFRESH_TOKEN_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function getSnsUserInfo($access_token, $openid)
{
$result = curlRequest(self::SNS_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function createQrcode($scene_id, $type=0, $expire=1800)
{
if(!$this->access_token && !$this->checkAuth()) return false;
$data = array();
$data['action_info'] = array('scene' => array('scene_id' => $scene_id));
$data['action_name'] = ($type == 0 ? 'QR_SCENE' : 'QR_LIMIT_SCENE');
if($type == 0) $data['expire_seconds'] = $expire;
$result = curlRequest(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
if($result)
{
$jsonArr = json_decode($result, true);
if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
else return $jsonArr;
}
return false;
}
public function getQrcodeUrl($ticket)
{
return self::SHOW_QRCODE_URL.'ticket='.urlencode($ticket);
}
public function error($data)
{
$this->errCode = $data['errcode'];
$this->errMsg = $data['errmsg'];
Log::info('WEIXIN API errcode:['.$this->errCode.'] errmsg:['.$this->errMsg.']');
}
public function jsonEncode($arr) {
$parts = array ();
$is_list = false;
//Find out if the given array is a numerical array
$keys = array_keys ( $arr );
$max_length = count ( $arr ) - 1;
if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
$is_list = true;
for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
if ($i != $keys [$i]) { //A key fails at position check.
$is_list = false; //It is an associative array.
break;
}
}
}
foreach ( $arr as $key => $value ) {
if (is_array ( $value )) { //Custom handling for arrays
if ($is_list)
$parts [] = $this->jsonEncode ( $value );
else
$parts [] = '"' . $key . '":' . $this->jsonEncode ( $value );
} else {
$str = '';
if (! $is_list)
$str = '"' . $key . '":';
//Custom handling for multiple data types
if (is_numeric ( $value ) && $value<2000000000)
$str .= $value; //Numbers
elseif ($value === false)
$str .= 'false'; //The booleans
elseif ($value === true)
$str .= 'true';
else
$str .= '"' . addslashes ( $value ) . '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
$parts [] = $str;
}
}
$json = implode ( ',', $parts );
if ($is_list)
return '[' . $json . ']'; //Return numerical JSON
return '{' . $json . '}'; //Return associative JSON
}
public function checkSignature()
{
$signature = HttpRequest::getGet('signature');
$timestamp = HttpRequest::getGet('timestamp');
$nonce = HttpRequest::getGet('nonce');
$token = $this->token;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
return ($tmpStr == $signature ? true : false);
}
public function valid()
{
if($this->checkSignature()) exit(HttpRequest::getGet('echostr'));
}
}



