首先引入微信sdk,然後配置appid,appsecret,然後實例化類
發送模板消息前期準備
先通過appid
appsecret獲取code ,然後通過code獲取access_token
通過access_token獲取到用戶信息後就可以發送模板消息了
微信sdk
<?php
/**
* 微信公衆平臺PHP-SDK, 官方API部分
* @author dodge <[email protected]>
* @link https://github.com/dodgepudding/wechat-php-sdk
* @version 1.2
* usage:
* $options = array(
* 'token'=>'tokenaccesskey', //填寫你設定的key
* 'encodingaeskey'=>'encodingaeskey', //填寫加密用的EncodingAESKey
* 'appid'=>'wxdk1234567890', //填寫高級調用功能的app id
* 'appsecret'=>'xxxxxxxxxxxxxxxxxxx' //填寫高級調用功能的密鑰
* );
* $weObj = new Wechat($options);
* $weObj->valid();
* $type = $weObj->getRev()->getRevType();
* switch($type) {
* case Wechat::MSGTYPE_TEXT:
* $weObj->text("hello, I'm wechat")->reply();
* exit;
* break;
* case Wechat::MSGTYPE_EVENT:
* ....
* break;
* case Wechat::MSGTYPE_IMAGE:
* ...
* break;
* default:
* $weObj->text("help info")->reply();
* }
*
* //獲取菜單操作:
* $menu = $weObj->getMenu();
* //設置菜單
* $newmenu = array(
* "button"=>
* array(
* array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
* array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
* )
* );
* $result = $weObj->createMenu($newmenu);
*/
class Wechat
{
const MSGTYPE_TEXT = 'text';
const MSGTYPE_IMAGE = 'image';
const MSGTYPE_LOCATION = 'location';
const MSGTYPE_LINK = 'link';
const MSGTYPE_EVENT = 'event';
const MSGTYPE_MUSIC = 'music';
const MSGTYPE_NEWS = 'news';
const MSGTYPE_VOICE = 'voice';
const MSGTYPE_VIDEO = 'video';
const MSGTYPE_SHORTVIDEO = 'shortvideo';
const EVENT_SUBSCRIBE = 'subscribe'; //訂閱
const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消訂閱
const EVENT_SCAN = 'SCAN'; //掃描帶參數二維碼
const EVENT_LOCATION = 'LOCATION'; //上報地理位置
const EVENT_MENU_VIEW = 'VIEW'; //菜單 - 點擊菜單跳轉鏈接
const EVENT_MENU_CLICK = 'CLICK'; //菜單 - 點擊菜單拉取消息
const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜單 - 掃碼推事件(客戶端跳URL)
const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜單 - 掃碼推事件(客戶端不跳URL)
const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜單 - 彈出系統拍照發圖
const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜單 - 彈出拍照或者相冊發圖
const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜單 - 彈出微信相冊發圖器
const EVENT_MENU_LOCATION = 'location_select'; //菜單 - 彈出地理位置選擇器
const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //發送結果 - 高級羣發完成
const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//發送結果 - 模板消息發送結果
const EVENT_KF_SEESION_CREATE = 'kfcreatesession'; //多客服 - 接入會話
const EVENT_KF_SEESION_CLOSE = 'kfclosesession'; //多客服 - 關閉會話
const EVENT_KF_SEESION_SWITCH = 'kfswitchsession'; //多客服 - 轉接會話
const EVENT_CARD_PASS = 'card_pass_check'; //卡券 - 審覈通過
const EVENT_CARD_NOTPASS = 'card_not_pass_check'; //卡券 - 審覈未通過
const EVENT_CARD_USER_GET = 'user_get_card'; //卡券 - 用戶領取卡券
const EVENT_CARD_USER_DEL = 'user_del_card'; //卡券 - 用戶刪除卡券
const EVENT_MERCHANT_ORDER = 'merchant_order'; //微信小店 - 訂單付款通知
const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
const AUTH_URL = '/token?grant_type=client_credential&';
const MENU_CREATE_URL = '/menu/create?';
const MENU_GET_URL = '/menu/get?';
const MENU_DELETE_URL = '/menu/delete?';
const GET_TICKET_URL = '/ticket/getticket?';
const CALLBACKSERVER_GET_URL = '/getcallbackip?';
const QRCODE_CREATE_URL='/qrcode/create?';
const QR_SCENE = 0;
const QR_LIMIT_SCENE = 1;
const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
const SHORT_URL='/shorturl?';
const USER_GET_URL='/user/get?';
const USER_INFO_URL='/user/info?';
const USER_UPDATEREMARK_URL='/user/info/updateremark?';
const GROUP_GET_URL='/groups/get?';
const USER_GROUP_URL='/groups/getid?';
const GROUP_CREATE_URL='/groups/create?';
const GROUP_UPDATE_URL='/groups/update?';
const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
const GROUP_MEMBER_BATCHUPDATE_URL='/groups/members/batchupdate?';
const CUSTOM_SEND_URL='/message/custom/send?';
const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
const MASS_SEND_URL = '/message/mass/send?';
const TEMPLATE_SET_INDUSTRY_URL = '/message/template/api_set_industry?';
const TEMPLATE_ADD_TPL_URL = '/message/template/api_add_template?';
const TEMPLATE_SEND_URL = '/message/template/send?';
const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
const MASS_DELETE_URL = '/message/mass/delete?';
const MASS_PREVIEW_URL = '/message/mass/preview?';
const MASS_QUERY_URL = '/message/mass/get?';
const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
const MEDIA_UPLOAD_URL = '/media/upload?';
const MEDIA_UPLOADIMG_URL = '/media/uploadimg?';//圖片上傳接口
const MEDIA_GET_URL = '/media/get?';
const MEDIA_VIDEO_UPLOAD = '/media/uploadvideo?';
const MEDIA_FOREVER_UPLOAD_URL = '/material/add_material?';
const MEDIA_FOREVER_NEWS_UPLOAD_URL = '/material/add_news?';
const MEDIA_FOREVER_NEWS_UPDATE_URL = '/material/update_news?';
const MEDIA_FOREVER_GET_URL = '/material/get_material?';
const MEDIA_FOREVER_DEL_URL = '/material/del_material?';
const MEDIA_FOREVER_COUNT_URL = '/material/get_materialcount?';
const MEDIA_FOREVER_BATCHGET_URL = '/material/batchget_material?';
const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
const OAUTH_AUTHORIZE_URL = '/authorize?';
///多客服相關地址
const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getonlinekflist?';
const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com'; //以下API接口URL需要使用此前綴
const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
const OAUTH_USERINFO_URL = '/sns/userinfo?';
const OAUTH_AUTH_URL = '/sns/auth?';
///多客服相關地址
const CUSTOM_SESSION_CREATE = '/customservice/kfsession/create?';
const CUSTOM_SESSION_CLOSE = '/customservice/kfsession/close?';
const CUSTOM_SESSION_SWITCH = '/customservice/kfsession/switch?';
const CUSTOM_SESSION_GET = '/customservice/kfsession/getsession?';
const CUSTOM_SESSION_GET_LIST = '/customservice/kfsession/getsessionlist?';
const CUSTOM_SESSION_GET_WAIT = '/customservice/kfsession/getwaitcase?';
const CS_KF_ACCOUNT_ADD_URL = '/customservice/kfaccount/add?';
const CS_KF_ACCOUNT_UPDATE_URL = '/customservice/kfaccount/update?';
const CS_KF_ACCOUNT_DEL_URL = '/customservice/kfaccount/del?';
const CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL = '/customservice/kfaccount/uploadheadimg?';
///卡券相關地址
const CARD_CREATE = '/card/create?';
const CARD_DELETE = '/card/delete?';
const CARD_UPDATE = '/card/update?';
const CARD_GET = '/card/get?';
const CARD_BATCHGET = '/card/batchget?';
const CARD_MODIFY_STOCK = '/card/modifystock?';
const CARD_LOCATION_BATCHADD = '/card/location/batchadd?';
const CARD_LOCATION_BATCHGET = '/card/location/batchget?';
const CARD_GETCOLORS = '/card/getcolors?';
const CARD_QRCODE_CREATE = '/card/qrcode/create?';
const CARD_CODE_CONSUME = '/card/code/consume?';
const CARD_CODE_DECRYPT = '/card/code/decrypt?';
const CARD_CODE_GET = '/card/code/get?';
const CARD_CODE_UPDATE = '/card/code/update?';
const CARD_CODE_UNAVAILABLE = '/card/code/unavailable?';
const CARD_TESTWHILELIST_SET = '/card/testwhitelist/set?';
const CARD_MEETINGCARD_UPDATEUSER = '/card/meetingticket/updateuser?'; //更新會議門票
const CARD_MEMBERCARD_ACTIVATE = '/card/membercard/activate?'; //激活會員卡
const CARD_MEMBERCARD_UPDATEUSER = '/card/membercard/updateuser?'; //更新會員卡
const CARD_MOVIETICKET_UPDATEUSER = '/card/movieticket/updateuser?'; //更新電影票(未加方法)
const CARD_BOARDINGPASS_CHECKIN = '/card/boardingpass/checkin?'; //飛機票-在線選座(未加方法)
const CARD_LUCKYMONEY_UPDATE = '/card/luckymoney/updateuserbalance?'; //更新紅包金額
const SEMANTIC_API_URL = '/semantic/semproxy/search?'; //語義理解
///數據分析接口
static $DATACUBE_URL_ARR = array( //用戶分析
'user' => array(
'summary' => '/datacube/getusersummary?', //獲取用戶增減數據(getusersummary)
'cumulate' => '/datacube/getusercumulate?', //獲取累計用戶數據(getusercumulate)
),
'article' => array( //圖文分析
'summary' => '/datacube/getarticlesummary?', //獲取圖文羣發每日數據(getarticlesummary)
'total' => '/datacube/getarticletotal?', //獲取圖文羣發總數據(getarticletotal)
'read' => '/datacube/getuserread?', //獲取圖文統計數據(getuserread)
'readhour' => '/datacube/getuserreadhour?', //獲取圖文統計分時數據(getuserreadhour)
'share' => '/datacube/getusershare?', //獲取圖文分享轉發數據(getusershare)
'sharehour' => '/datacube/getusersharehour?', //獲取圖文分享轉發分時數據(getusersharehour)
),
'upstreammsg' => array( //消息分析
'summary' => '/datacube/getupstreammsg?', //獲取消息發送概況數據(getupstreammsg)
'hour' => '/datacube/getupstreammsghour?', //獲取消息分送分時數據(getupstreammsghour)
'week' => '/datacube/getupstreammsgweek?', //獲取消息發送週數據(getupstreammsgweek)
'month' => '/datacube/getupstreammsgmonth?', //獲取消息發送月數據(getupstreammsgmonth)
'dist' => '/datacube/getupstreammsgdist?', //獲取消息發送分佈數據(getupstreammsgdist)
'distweek' => '/datacube/getupstreammsgdistweek?', //獲取消息發送分佈週數據(getupstreammsgdistweek)
'distmonth' => '/datacube/getupstreammsgdistmonth?', //獲取消息發送分佈月數據(getupstreammsgdistmonth)
),
'interface' => array( //接口分析
'summary' => '/datacube/getinterfacesummary?', //獲取接口分析數據(getinterfacesummary)
'summaryhour' => '/datacube/getinterfacesummaryhour?', //獲取接口分析分時數據(getinterfacesummaryhour)
)
);
///微信搖一搖周邊
const SHAKEAROUND_DEVICE_APPLYID = '/shakearound/device/applyid?';//申請設備ID
const SHAKEAROUND_DEVICE_UPDATE = '/shakearound/device/update?';//編輯設備信息
const SHAKEAROUND_DEVICE_SEARCH = '/shakearound/device/search?';//查詢設備列表
const SHAKEAROUND_DEVICE_BINDLOCATION = '/shakearound/device/bindlocation?';//配置設備與門店ID的關係
const SHAKEAROUND_DEVICE_BINDPAGE = '/shakearound/device/bindpage?';//配置設備與頁面的綁定關係
const SHAKEAROUND_MATERIAL_ADD = '/shakearound/material/add?';//上傳搖一搖圖片素材
const SHAKEAROUND_PAGE_ADD = '/shakearound/page/add?';//增加頁面
const SHAKEAROUND_PAGE_UPDATE = '/shakearound/page/update?';//編輯頁面
const SHAKEAROUND_PAGE_SEARCH = '/shakearound/page/search?';//查詢頁面列表
const SHAKEAROUND_PAGE_DELETE = '/shakearound/page/delete?';//刪除頁面
const SHAKEAROUND_USER_GETSHAKEINFO = '/shakearound/user/getshakeinfo?';//獲取搖周邊的設備及用戶信息
const SHAKEAROUND_STATISTICS_DEVICE = '/shakearound/statistics/device?';//以設備爲維度的數據統計接口
const SHAKEAROUND_STATISTICS_PAGE = '/shakearound/statistics/page?';//以頁面爲維度的數據統計接口
///微信小店相關接口
const MERCHANT_ORDER_GETBYID = '/merchant/order/getbyid?';//根據訂單ID獲取訂單詳情
const MERCHANT_ORDER_GETBYFILTER = '/merchant/order/getbyfilter?';//根據訂單狀態/創建時間獲取訂單詳情
const MERCHANT_ORDER_SETDELIVERY = '/merchant/order/setdelivery?';//設置訂單發貨信息
const MERCHANT_ORDER_CLOSE = '/merchant/order/close?';//關閉訂單
private $token;
private $encodingAesKey;
private $encrypt_type;
private $appid;
private $appsecret;
private $access_token;
private $jsapi_ticket;
private $api_ticket;
private $user_token;
private $partnerid;
private $partnerkey;
private $paysignkey;
private $postxml;
private $_msg;
private $_funcflag = false;
private $_receive;
private $_text_filter = true;
public $debug = false;
public $errCode = 40001;
public $errMsg = "no access";
public $logcallback;
public function __construct($options)
{
$this->token = isset($options['token'])?$options['token']:'';
$this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
$this->appid = isset($options['appid'])?$options['appid']:'';
$this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
$this->debug = isset($options['debug'])?$options['debug']:false;
$this->logcallback = isset($options['logcallback'])?$options['logcallback']:false;
}
/**
* For weixin server validation
*/
private function checkSignature($str='')
{
$signature = isset($_GET["signature"])?$_GET["signature"]:'';
$signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密驗證則用加密驗證段
$timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
$nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
$token = $this->token;
$tmpArr = array($token, $timestamp, $nonce,$str);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
/**
* For weixin server validation
* @param bool $return 是否返回
*/
public function valid($return=false)
{
$encryptStr="";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$postStr = file_get_contents("php://input");
$array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"]: '';
if ($this->encrypt_type == 'aes') { //aes加密
$this->log($postStr);
$encryptStr = $array['Encrypt'];
$pc = new Prpcrypt($this->encodingAesKey);
$array = $pc->decrypt($encryptStr,$this->appid);
if (!isset($array[0]) || ($array[0] != 0)) {
if (!$return) {
die('decrypt error!');
} else {
return false;
}
}
$this->postxml = $array[1];
if (!$this->appid)
$this->appid = $array[2];//爲了沒有appid的訂閱號。
} else {
$this->postxml = $postStr;
}
} elseif (isset($_GET["echostr"])) {
$echoStr = $_GET["echostr"];
if ($return) {
if ($this->checkSignature())
return $echoStr;
else
return false;
} else {
if ($this->checkSignature())
die($echoStr);
else
die('no access');
}
}
if (!$this->checkSignature($encryptStr)) {
if ($return)
return false;
else
die('no access');
}
return true;
}
/**
* 設置發送消息
* @param array $msg 消息數組
* @param bool $append 是否在原消息數組追加
*/
public function Message($msg = '',$append = false){
if (is_null($msg)) {
$this->_msg =array();
}elseif (is_array($msg)) {
if ($append)
$this->_msg = array_merge($this->_msg,$msg);
else
$this->_msg = $msg;
return $this->_msg;
} else {
return $this->_msg;
}
}
/**
* 設置消息的星標標誌,官方已取消對此功能的支持
*/
public function setFuncFlag($flag) {
$this->_funcflag = $flag;
return $this;
}
/**
* 日誌記錄,可被重載。
* @param mixed $log 輸入日誌
* @return mixed
*/
protected function log($log){
if ($this->debug && function_exists($this->logcallback)) {
if (is_array($log)) $log = print_r($log,true);
return call_user_func($this->logcallback,$log);
}
}
/**
* 獲取微信服務器發來的信息
*/
public function getRev()
{
if ($this->_receive) return $this;
$postStr = !empty($this->postxml)?$this->postxml:file_get_contents("php://input");
//兼顧使用明文又不想調用valid()方法的情況
$this->log($postStr);
if (!empty($postStr)) {
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
}
return $this;
}
/**
* 獲取微信服務器發來的信息
*/
public function getRevData()
{
return $this->_receive;
}
/**
* 獲取消息發送者
*/
public function getRevFrom() {
if (isset($this->_receive['FromUserName']))
return $this->_receive['FromUserName'];
else
return false;
}
/**
* 獲取消息接受者
*/
public function getRevTo() {
if (isset($this->_receive['ToUserName']))
return $this->_receive['ToUserName'];
else
return false;
}
/**
* 獲取接收消息的類型
*/
public function getRevType() {
if (isset($this->_receive['MsgType']))
return $this->_receive['MsgType'];
else
return false;
}
/**
* 獲取消息ID
*/
public function getRevID() {
if (isset($this->_receive['MsgId']))
return $this->_receive['MsgId'];
else
return false;
}
/**
* 獲取消息發送時間
*/
public function getRevCtime() {
if (isset($this->_receive['CreateTime']))
return $this->_receive['CreateTime'];
else
return false;
}
/**
* 獲取接收消息內容正文
*/
public function getRevContent(){
if (isset($this->_receive['Content']))
return $this->_receive['Content'];
else if (isset($this->_receive['Recognition']))//獲取語音識別文字內容,需申請開通
return $this->_receive['Recognition'];
else
return false;
}
/**
* 獲取接收消息圖片
*/
public function getRevPic(){
if (isset($this->_receive['PicUrl']))
return array(
'mediaid'=>$this->_receive['MediaId'],
'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl爲空導致解析出錯
);
else
return false;
}
/**
* 獲取接收消息鏈接
*/
public function getRevLink(){
if (isset($this->_receive['Url'])){
return array(
'url'=>$this->_receive['Url'],
'title'=>$this->_receive['Title'],
'description'=>$this->_receive['Description']
);
} else
return false;
}
/**
* 獲取接收地理位置
*/
public function getRevGeo(){
if (isset($this->_receive['Location_X'])){
return array(
'x'=>$this->_receive['Location_X'],
'y'=>$this->_receive['Location_Y'],
'scale'=>$this->_receive['Scale'],
'label'=>$this->_receive['Label']
);
} else
return false;
}
/**
* 獲取上報地理位置事件
*/
public function getRevEventGeo(){
if (isset($this->_receive['Latitude'])){
return array(
'x'=>$this->_receive['Latitude'],
'y'=>$this->_receive['Longitude'],
'precision'=>$this->_receive['Precision'],
);
} else
return false;
}
/**
* 獲取接收事件推送
*/
public function getRevEvent(){
if (isset($this->_receive['Event'])){
$array['event'] = $this->_receive['Event'];
}
if (isset($this->_receive['EventKey'])){
$array['key'] = $this->_receive['EventKey'];
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取自定義菜單的掃碼推事件信息
*
* 事件類型爲以下兩種時則調用此方法有效
* Event 事件類型,scancode_push
* Event 事件類型,scancode_waitmsg
*
* @return: array | false
* array (
* 'ScanType'=>'qrcode',
* 'ScanResult'=>'123123'
* )
*/
public function getRevScanInfo(){
if (isset($this->_receive['ScanCodeInfo'])){
if (!is_array($this->_receive['ScanCodeInfo'])) {
$array=(array)$this->_receive['ScanCodeInfo'];
$this->_receive['ScanCodeInfo']=$array;
}else {
$array=$this->_receive['ScanCodeInfo'];
}
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取自定義菜單的圖片發送事件信息
*
* 事件類型爲以下三種時則調用此方法有效
* Event 事件類型,pic_sysphoto 彈出系統拍照發圖的事件推送
* Event 事件類型,pic_photo_or_album 彈出拍照或者相冊發圖的事件推送
* Event 事件類型,pic_weixin 彈出微信相冊發圖器的事件推送
*
* @return: array | false
* array (
* 'Count' => '2',
* 'PicList' =>array (
* 'item' =>array (
* 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
* 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
* ),
* ),
* )
*
*/
public function getRevSendPicsInfo(){
if (isset($this->_receive['SendPicsInfo'])){
if (!is_array($this->_receive['SendPicsInfo'])) {
$array=(array)$this->_receive['SendPicsInfo'];
if (isset($array['PicList'])){
$array['PicList']=(array)$array['PicList'];
$item=$array['PicList']['item'];
$array['PicList']['item']=array();
foreach ( $item as $key => $value ){
$array['PicList']['item'][$key]=(array)$value;
}
}
$this->_receive['SendPicsInfo']=$array;
} else {
$array=$this->_receive['SendPicsInfo'];
}
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取自定義菜單的地理位置選擇器事件推送
*
* 事件類型爲以下時則可以調用此方法有效
* Event 事件類型,location_select 彈出地理位置選擇器的事件推送
*
* @return: array | false
* array (
* 'Location_X' => '33.731655000061',
* 'Location_Y' => '113.29955200008047',
* 'Scale' => '16',
* 'Label' => '某某市某某區某某路',
* 'Poiname' => '',
* )
*
*/
public function getRevSendGeoInfo(){
if (isset($this->_receive['SendLocationInfo'])){
if (!is_array($this->_receive['SendLocationInfo'])) {
$array=(array)$this->_receive['SendLocationInfo'];
if (empty($array['Poiname'])) {
$array['Poiname']="";
}
if (empty($array['Label'])) {
$array['Label']="";
}
$this->_receive['SendLocationInfo']=$array;
} else {
$array=$this->_receive['SendLocationInfo'];
}
}
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取接收語音推送
*/
public function getRevVoice(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'format'=>$this->_receive['Format'],
);
} else
return false;
}
/**
* 獲取接收視頻推送
*/
public function getRevVideo(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'thumbmediaid'=>$this->_receive['ThumbMediaId']
);
} else
return false;
}
/**
* 獲取接收TICKET
*/
public function getRevTicket(){
if (isset($this->_receive['Ticket'])){
return $this->_receive['Ticket'];
} else
return false;
}
/**
* 獲取二維碼的場景值
*/
public function getRevSceneId (){
if (isset($this->_receive['EventKey'])){
return str_replace('qrscene_','',$this->_receive['EventKey']);
} else{
return false;
}
}
/**
* 獲取主動推送的消息ID
* 經過驗證,這個和普通的消息MsgId不一樣
* 當Event爲 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH
*/
public function getRevTplMsgID(){
if (isset($this->_receive['MsgID'])){
return $this->_receive['MsgID'];
} else
return false;
}
/**
* 獲取模板消息發送狀態
*/
public function getRevStatus(){
if (isset($this->_receive['Status'])){
return $this->_receive['Status'];
} else
return false;
}
/**
* 獲取羣發或模板消息發送結果
* 當Event爲 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH,即高級羣發/模板消息
*/
public function getRevResult(){
if (isset($this->_receive['Status'])) //發送是否成功,具體的返回值請參考 高級羣發/模板消息 的事件推送說明
$array['Status'] = $this->_receive['Status'];
if (isset($this->_receive['MsgID'])) //發送的消息id
$array['MsgID'] = $this->_receive['MsgID'];
//以下僅當羣發消息時纔會有的事件內容
if (isset($this->_receive['TotalCount'])) //分組或openid列表內粉絲數量
$array['TotalCount'] = $this->_receive['TotalCount'];
if (isset($this->_receive['FilterCount'])) //過濾(過濾是指特定地區、性別的過濾、用戶設置拒收的過濾,用戶接收已超4條的過濾)後,準備發送的粉絲數
$array['FilterCount'] = $this->_receive['FilterCount'];
if (isset($this->_receive['SentCount'])) //發送成功的粉絲數
$array['SentCount'] = $this->_receive['SentCount'];
if (isset($this->_receive['ErrorCount'])) //發送失敗的粉絲數
$array['ErrorCount'] = $this->_receive['ErrorCount'];
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取多客服會話狀態推送事件 - 接入會話
* 當Event爲 kfcreatesession 即接入會話
* @return string | boolean 返回分配到的客服
*/
public function getRevKFCreate(){
if (isset($this->_receive['KfAccount'])){
return $this->_receive['KfAccount'];
} else
return false;
}
/**
* 獲取多客服會話狀態推送事件 - 關閉會話
* 當Event爲 kfclosesession 即關閉會話
* @return string | boolean 返回分配到的客服
*/
public function getRevKFClose(){
if (isset($this->_receive['KfAccount'])){
return $this->_receive['KfAccount'];
} else
return false;
}
/**
* 獲取多客服會話狀態推送事件 - 轉接會話
* 當Event爲 kfswitchsession 即轉接會話
* @return array | boolean 返回分配到的客服
* {
* 'FromKfAccount' => '', //原接入客服
* 'ToKfAccount' => '' //轉接到客服
* }
*/
public function getRevKFSwitch(){
if (isset($this->_receive['FromKfAccount'])) //原接入客服
$array['FromKfAccount'] = $this->_receive['FromKfAccount'];
if (isset($this->_receive['ToKfAccount'])) //轉接到客服
$array['ToKfAccount'] = $this->_receive['ToKfAccount'];
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取卡券事件推送 - 卡卷審覈是否通過
* 當Event爲 card_pass_check(審覈通過) 或 card_not_pass_check(未通過)
* @return string|boolean 返回卡券ID
*/
public function getRevCardPass(){
if (isset($this->_receive['CardId']))
return $this->_receive['CardId'];
else
return false;
}
/**
* 獲取卡券事件推送 - 領取卡券
* 當Event爲 user_get_card(用戶領取卡券)
* @return array|boolean
*/
public function getRevCardGet(){
if (isset($this->_receive['CardId'])) //卡券 ID
$array['CardId'] = $this->_receive['CardId'];
if (isset($this->_receive['IsGiveByFriend'])) //是否爲轉贈,1 代表是,0 代表否。
$array['IsGiveByFriend'] = $this->_receive['IsGiveByFriend'];
$array['OldUserCardCode'] = $this->_receive['OldUserCardCode'];
if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列號。自定義 code 及非自定義 code的卡券被領取後都支持事件推送。
$array['UserCardCode'] = $this->_receive['UserCardCode'];
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取卡券事件推送 - 刪除卡券
* 當Event爲 user_del_card(用戶刪除卡券)
* @return array|boolean
*/
public function getRevCardDel(){
if (isset($this->_receive['CardId'])) //卡券 ID
$array['CardId'] = $this->_receive['CardId'];
if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列號。自定義 code 及非自定義 code的卡券被領取後都支持事件推送。
$array['UserCardCode'] = $this->_receive['UserCardCode'];
if (isset($array) && count($array) > 0) {
return $array;
} else {
return false;
}
}
/**
* 獲取訂單ID - 訂單付款通知
* 當Event爲 merchant_order(訂單付款通知)
* @return orderId|boolean
*/
public function getRevOrderId(){
if (isset($this->_receive['OrderId'])) //訂單 ID
return $this->_receive['OrderId'];
else
return false;
}
public static function xmlSafeStr($str)
{
return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
}
/**
* 數據XML編碼
* @param mixed $data 數據
* @return string
*/
public static function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml .= "<$key>";
$xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
list($key, ) = explode(' ', $key);
$xml .= "</$key>";
}
return $xml;
}
/**
* XML編碼
* @param mixed $data 數據
* @param string $root 根節點名
* @param string $item 數字索引的子節點名
* @param string $attr 根節點屬性
* @param string $id 數字索引子節點key轉換的屬性名
* @param string $encoding 數據編碼
* @return string
*/
public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
if(is_array($attr)){
$_attr = array();
foreach ($attr as $key => $value) {
$_attr[] = "{$key}=\"{$value}\"";
}
$attr = implode(' ', $_attr);
}
$attr = trim($attr);
$attr = empty($attr) ? '' : " {$attr}";
$xml = "<{$root}{$attr}>";
$xml .= self::data_to_xml($data, $item, $id);
$xml .= "</{$root}>";
return $xml;
}
/**
* 過濾文字回覆\r\n換行符
* @param string $text
* @return string|mixed
*/
private function _auto_text_filter($text) {
if (!$this->_text_filter) return $text;
return str_replace("\r\n", "\n", $text);
}
/**
* 設置回覆消息
* Example: $obj->text('hello')->reply();
* @param string $text
*/
public function text($text='')
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_TEXT,
'Content'=>$this->_auto_text_filter($text),
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 設置回覆消息
* Example: $obj->image('media_id')->reply();
* @param string $mediaid
*/
public function image($mediaid='')
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_IMAGE,
'Image'=>array('MediaId'=>$mediaid),
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 設置回覆消息
* Example: $obj->voice('media_id')->reply();
* @param string $mediaid
*/
public function voice($mediaid='')
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_VOICE,
'Voice'=>array('MediaId'=>$mediaid),
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 設置回覆消息
* Example: $obj->video('media_id','title','description')->reply();
* @param string $mediaid
*/
public function video($mediaid='',$title='',$description='')
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_VIDEO,
'Video'=>array(
'MediaId'=>$mediaid,
'Title'=>$title,
'Description'=>$description
),
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
public function shortvideo($mediaid='',$title='',$description='')
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_VIDEO,
'Video'=>array(
'MediaId'=>$mediaid,
'Title'=>$title,
'Description'=>$description
),
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 設置回覆音樂
* @param string $title
* @param string $desc
* @param string $musicurl
* @param string $hgmusicurl
* @param string $thumbmediaid 音樂圖片縮略圖的媒體id,非必須
*/
public function music($title,$desc,$musicurl,$hgmusicurl='',$thumbmediaid='') {
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'CreateTime'=>time(),
'MsgType'=>self::MSGTYPE_MUSIC,
'Music'=>array(
'Title'=>$title,
'Description'=>$desc,
'MusicUrl'=>$musicurl,
'HQMusicUrl'=>$hgmusicurl
),
'FuncFlag'=>$FuncFlag
);
if ($thumbmediaid) {
$msg['Music']['ThumbMediaId'] = $thumbmediaid;
}
$this->Message($msg);
return $this;
}
/**
* 設置回覆圖文
* @param array $newsData
* 數組結構:
* array(
* "0"=>array(
* 'Title'=>'msg title',
* 'Description'=>'summary text',
* 'PicUrl'=>'http://www.domain.com/1.jpg',
* 'Url'=>'http://www.domain.com/1.html'
* ),
* "1"=>....
* )
*/
public function news($newsData=array())
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$count = count($newsData);
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_NEWS,
'CreateTime'=>time(),
'ArticleCount'=>$count,
'Articles'=>$newsData,
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
*
* 回覆微信服務器, 此函數支持鏈式操作
* Example: $this->text('msg tips')->reply();
* @param string $msg 要發送的信息, 默認取$this->_msg
* @param bool $return 是否返回信息而不拋出到瀏覽器 默認:否
*/
public function reply($msg=array(),$return = false)
{
if (empty($msg)) {
if (empty($this->_msg)) //防止不先設置回覆內容,直接調用reply方法導致異常
return false;
$msg = $this->_msg;
}
$xmldata= $this->xml_encode($msg);
$this->log($xmldata);
if ($this->encrypt_type == 'aes') { //如果來源消息爲加密方式
$pc = new Prpcrypt($this->encodingAesKey);
$array = $pc->encrypt($xmldata, $this->appid);
$ret = $array[0];
if ($ret != 0) {
$this->log('encrypt err!');
return false;
}
$timestamp = time();
$nonce = rand(77,999)*rand(605,888)*rand(11,99);
$encrypt = $array[1];
$tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公衆平臺多了一個加密的密文
sort($tmpArr, SORT_STRING);
$signature = implode($tmpArr);
$signature = sha1($signature);
$xmldata = $this->generate($encrypt, $signature, $timestamp, $nonce);
$this->log($xmldata);
}
if ($return)
return $xmldata;
else
echo $xmldata;
}
/**
* xml格式加密,僅請求爲加密方式時再用
*/
private function generate($encrypt, $signature, $timestamp, $nonce)
{
//格式化加密信息
$format = "<xml>
<Encrypt><![CDATA[%s]]></Encrypt>
<MsgSignature><![CDATA[%s]]></MsgSignature>
<TimeStamp>%s</TimeStamp>
<Nonce><![CDATA[%s]]></Nonce>
</xml>";
return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
}
/**
* GET 請求
* @param string $url
*/
private function http_get($url){
$oCurl = curl_init();
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(intval($aStatus["http_code"])==200){
return $sContent;
}else{
return false;
}
}
/**
* POST 請求
* @param string $url
* @param array $param
* @param boolean $post_file 是否文件上傳
* @return string content
*/
private function http_post($url,$param,$post_file=false){
$oCurl = curl_init();
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
if (is_string($param) || $post_file) {
$strPOST = $param;
} else {
$aPOST = array();
foreach($param as $key=>$val){
$aPOST[] = $key."=".urlencode($val);
}
$strPOST = join("&", $aPOST);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($oCurl, CURLOPT_POST,true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(intval($aStatus["http_code"])==200){
return $sContent;
}else{
return false;
}
}
/**
* 設置緩存,按需重載
* @param string $cachename
* @param mixed $value
* @param int $expired
* @return boolean
*/
protected function setCache($cachename,$value,$expired){
//TODO: set cache implementation
return false;
}
/**
* 獲取緩存,按需重載
* @param string $cachename
* @return mixed
*/
protected function getCache($cachename){
//TODO: get cache implementation
return false;
}
/**
* 清除緩存,按需重載
* @param string $cachename
* @return boolean
*/
protected function removeCache($cachename){
//TODO: remove cache implementation
return false;
}
/**
* 獲取access_token
* @param string $appid 如在類初始化時已提供,則可爲空
* @param string $appsecret 如在類初始化時已提供,則可爲空
* @param string $token 手動指定access_token,非必要情況不建議用
*/
public function checkAuth($appid='',$appsecret='',$token=''){
if (!$appid || !$appsecret) {
$appid = $this->appid;
$appsecret = $this->appsecret;
}
if ($token) { //手動指定token,優先使用
$this->access_token=$token;
return $this->access_token;
}
$authname = 'wechat_access_token'.$appid;
if ($rs = $this->getCache($authname)) {
$this->access_token = $rs;
return $rs;
}
$result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
if ($result)
{
$json = json_decode($result,true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->access_token = $json['access_token'];
$expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
$this->setCache($authname,$this->access_token,$expire);
return $this->access_token;
}
return false;
}
/**
* 刪除驗證數據
* @param string $appid
*/
public function resetAuth($appid=''){
if (!$appid) $appid = $this->appid;
$this->access_token = '';
$authname = 'wechat_access_token'.$appid;
$this->removeCache($authname);
return true;
}
/**
* 刪除JSAPI授權TICKET
* @param string $appid 用於多個appid時使用
*/
public function resetJsTicket($appid=''){
if (!$appid) $appid = $this->appid;
$this->jsapi_ticket = '';
$authname = 'wechat_jsapi_ticket'.$appid;
$this->removeCache($authname);
return true;
}
/**
* 獲取JSAPI授權TICKET
* @param string $appid 用於多個appid時使用,可空
* @param string $jsapi_ticket 手動指定jsapi_ticket,非必要情況不建議用
*/
public function getJsTicket($appid='',$jsapi_ticket=''){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!$appid) $appid = $this->appid;
if ($jsapi_ticket) { //手動指定token,優先使用
$this->jsapi_ticket = $jsapi_ticket;
return $this->jsapi_ticket;
}
$authname = 'wechat_jsapi_ticket'.$appid;
if ($rs = $this->getCache($authname)) {
$this->jsapi_ticket = $rs;
return $rs;
}
$result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=jsapi');
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->jsapi_ticket = $json['ticket'];
$expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
$this->setCache($authname,$this->jsapi_ticket,$expire);
return $this->jsapi_ticket;
}
return false;
}
/**
* 獲取JsApi使用簽名
* @param string $url 網頁的URL,自動處理#及其後面部分
* @param string $timestamp 當前時間戳 (爲空則自動生成)
* @param string $noncestr 隨機串 (爲空則自動生成)
* @param string $appid 用於多個appid時使用,可空
* @return array|bool 返回簽名字串
*/
public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
if (!$timestamp)
$timestamp = time();
if (!$noncestr)
$noncestr = $this->generateNonceStr();
$ret = strpos($url,'#');
if ($ret)
$url = substr($url,0,$ret);
$url = trim($url);
if (empty($url))
return false;
$arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
$sign = $this->getSignature($arrdata);
if (!$sign)
return false;
$signPackage = array(
"appId" => $this->appid,
"nonceStr" => $noncestr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $sign
);
return $signPackage;
}
/**
* 微信api不支持中文轉義的json結構
* @param array $arr
*/
static function json_encode($arr) {
if (count($arr) == 0) return "[]";
$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 [] = self::json_encode ( $value ); /* :RECURSION: */
else
$parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
} else {
$str = '';
if (! $is_list)
$str = '"' . $key . '":';
//Custom handling for multiple data types
if (!is_string ( $value ) && 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
}
/**
* 獲取簽名
* @param array $arrdata 簽名數組
* @param string $method 簽名方法
* @return boolean|string 簽名值
*/
public function getSignature($arrdata,$method="sha1") {
if (!function_exists($method)) return false;
ksort($arrdata);
$paramstring = "";
foreach($arrdata as $key => $value)
{
if(strlen($paramstring) == 0)
$paramstring .= $key . "=" . $value;
else
$paramstring .= "&" . $key . "=" . $value;
}
$Sign = $method($paramstring);
return $Sign;
}
/**
* 獲取微信卡券api_ticket
* @param string $appid 用於多個appid時使用,可空
* @param string $api_ticket 手動指定api_ticket,非必要情況不建議用
*/
public function getJsCardTicket($appid='',$api_ticket=''){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!$appid) $appid = $this->appid;
if ($api_ticket) { //手動指定token,優先使用
$this->api_ticket = $api_ticket;
return $this->api_ticket;
}
$authname = 'wechat_api_ticket_wxcard'.$appid;
if ($rs = $this->getCache($authname)) {
$this->api_ticket = $rs;
return $rs;
}
$result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=wx_card');
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->api_ticket = $json['ticket'];
$expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
$this->setCache($authname,$this->api_ticket,$expire);
return $this->api_ticket;
}
return false;
}
/**
* 獲取微信卡券簽名
* @param array $arrdata 簽名數組
* @param string $method 簽名方法
* @return boolean|string 簽名值
*/
public function getTicketSignature($arrdata,$method="sha1") {
if (!function_exists($method)) return false;
$newArray = array();
foreach($arrdata as $key => $value)
{
array_push($newArray,(string)$value);
}
sort($newArray,SORT_STRING);
return $method(implode($newArray));
}
/**
* 生成隨機字串
* @param number $length 長度,默認爲16,最長爲32字節
* @return string
*/
public function generateNonceStr($length=16){
// 密碼字符集,可任意添加你需要的字符
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for($i = 0; $i < $length; $i++)
{
$str .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $str;
}
/**
* 獲取微信服務器IP地址列表
* @return array('127.0.0.1','127.0.0.1')
*/
public function getServerIp(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json['ip_list'];
}
return false;
}
/**
* 創建菜單(認證後的訂閱號可用)
* @param array $data 菜單數組數據
* example:
* array (
* 'button' => array (
* 0 => array (
* 'name' => '掃碼',
* 'sub_button' => array (
* 0 => array (
* 'type' => 'scancode_waitmsg',
* 'name' => '掃碼帶提示',
* 'key' => 'rselfmenu_0_0',
* ),
* 1 => array (
* 'type' => 'scancode_push',
* 'name' => '掃碼推事件',
* 'key' => 'rselfmenu_0_1',
* ),
* ),
* ),
* 1 => array (
* 'name' => '發圖',
* 'sub_button' => array (
* 0 => array (
* 'type' => 'pic_sysphoto',
* 'name' => '系統拍照發圖',
* 'key' => 'rselfmenu_1_0',
* ),
* 1 => array (
* 'type' => 'pic_photo_or_album',
* 'name' => '拍照或者相冊發圖',
* 'key' => 'rselfmenu_1_1',
* )
* ),
* ),
* 2 => array (
* 'type' => 'location_select',
* 'name' => '發送位置',
* 'key' => 'rselfmenu_2_0'
* ),
* ),
* )
* type可以選擇爲以下幾種,其中5-8除了收到菜單事件以外,還會單獨收到對應類型的信息。
* 1、click:點擊推事件
* 2、view:跳轉URL
* 3、scancode_push:掃碼推事件
* 4、scancode_waitmsg:掃碼推事件且彈出“消息接收中”提示框
* 5、pic_sysphoto:彈出系統拍照發圖
* 6、pic_photo_or_album:彈出拍照或者相冊發圖
* 7、pic_weixin:彈出微信相冊發圖器
* 8、location_select:彈出地理位置選擇器
*/
public function createMenu($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 獲取菜單(認證後的訂閱號可用)
* @return array('menu'=>array(....s))
*/
public function getMenu(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 刪除菜單(認證後的訂閱號可用)
* @return boolean
*/
public function deleteMenu(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 上傳臨時素材,有效期爲3天(認證後的訂閱號可用)
* 注意:上傳大文件時可能需要先調用 set_time_limit(0) 避免超時
* 注意:數組的鍵值任意,但文件名前必須加@,使用單引號以避免本地路徑斜槓被轉義
* 注意:臨時素材的media_id是可複用的!
* @param array $data {"media":'@Path\filename.jpg'}
* @param type 類型:圖片:image 語音:voice 視頻:video 縮略圖:thumb
* @return boolean|array
*/
public function uploadMedia($data, $type){
if (!$this->access_token && !$this->checkAuth()) return false;
//原先的上傳多媒體文件接口使用 self::UPLOAD_MEDIA_URL 前綴
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取臨時素材(認證後的訂閱號可用)
* @param string $media_id 媒體文件id
* @param boolean $is_video 是否爲視頻文件,默認爲否
* @return raw data
*/
public function getMedia($media_id,$is_video=false){
if (!$this->access_token && !$this->checkAuth()) return false;
//原先的上傳多媒體文件接口使用 self::UPLOAD_MEDIA_URL 前綴
//如果要獲取的素材是視頻文件時,不能使用https協議,必須更換成http協議
$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
$result = $this->http_get($url_prefix.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
if ($result)
{
if (is_string($result)) {
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
}
return $result;
}
return false;
}
/**
* 上傳圖片,本接口所上傳的圖片不佔用公衆號的素材庫中圖片數量的5000個的限制。圖片僅支持jpg/png格式,大小必須在1MB以下。 (認證後的訂閱號可用)
* 注意:上傳大文件時可能需要先調用 set_time_limit(0) 避免超時
* 注意:數組的鍵值任意,但文件名前必須加@,使用單引號以避免本地路徑斜槓被轉義
* @param array $data {"media":'@Path\filename.jpg'}
*
* @return boolean|array
*/
public function uploadImg($data){
if (!$this->access_token && !$this->checkAuth()) return false;
//原先的上傳多媒體文件接口使用 self::UPLOAD_MEDIA_URL 前綴
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADIMG_URL.'access_token='.$this->access_token,$data,true);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 上傳永久素材(認證後的訂閱號可用)
* 新增的永久素材也可以在公衆平臺官網素材管理模塊中看到
* 注意:上傳大文件時可能需要先調用 set_time_limit(0) 避免超時
* 注意:數組的鍵值任意,但文件名前必須加@,使用單引號以避免本地路徑斜槓被轉義
* @param array $data {"media":'@Path\filename.jpg'}
* @param type 類型:圖片:image 語音:voice 視頻:video 縮略圖:thumb
* @param boolean $is_video 是否爲視頻文件,默認爲否
* @param array $video_info 視頻信息數組,非視頻素材不需要提供 array('title'=>'視頻標題','introduction'=>'描述')
* @return boolean|array
*/
public function uploadForeverMedia($data, $type,$is_video=false,$video_info=array()){
if (!$this->access_token && !$this->checkAuth()) return false;
//#TODO 暫不確定此接口是否需要讓視頻文件走http協議
//如果要獲取的素材是視頻文件時,不能使用https協議,必須更換成http協議
//$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
//當上傳視頻文件時,附加視頻文件信息
if ($is_video) $data['description'] = self::json_encode($video_info);
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 上傳永久圖文素材(認證後的訂閱號可用)
* 新增的永久素材也可以在公衆平臺官網素材管理模塊中看到
* @param array $data 消息結構{"articles":[{...}]}
* @return boolean|array
*/
public function uploadForeverArticles($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPLOAD_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 修改永久圖文素材(認證後的訂閱號可用)
* 永久素材也可以在公衆平臺官網素材管理模塊中看到
* @param string $media_id 圖文素材id
* @param array $data 消息結構{"articles":[{...}]}
* @param int $index 更新的文章在圖文素材的位置,第一篇爲0,僅多圖文使用
* @return boolean|array
*/
public function updateForeverArticles($media_id,$data,$index=0){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!isset($data['media_id'])) $data['media_id'] = $media_id;
if (!isset($data['index'])) $data['index'] = $index;
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取永久素材(認證後的訂閱號可用)
* 返回圖文消息數組或二進制數據,失敗返回false
* @param string $media_id 媒體文件id
* @param boolean $is_video 是否爲視頻文件,默認爲否
* @return boolean|array|raw data
*/
public function getForeverMedia($media_id,$is_video=false){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array('media_id' => $media_id);
//#TODO 暫不確定此接口是否需要讓視頻文件走http協議
//如果要獲取的素材是視頻文件時,不能使用https協議,必須更換成http協議
//$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_GET_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
if (is_string($result)) {
$json = json_decode($result,true);
if ($json) {
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
} else {
return $result;
}
}
return $result;
}
return false;
}
/**
* 刪除永久素材(認證後的訂閱號可用)
* @param string $media_id 媒體文件id
* @return boolean
*/
public function delForeverMedia($media_id){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array('media_id' => $media_id);
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_DEL_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 獲取永久素材列表(認證後的訂閱號可用)
* @param string $type 素材的類型,圖片(image)、視頻(video)、語音 (voice)、圖文(news)
* @param int $offset 全部素材的偏移位置,0表示從第一個素材
* @param int $count 返回素材的數量,取值在1到20之間
* @return boolean|array
* 返回數組格式:
* array(
* 'total_count'=>0, //該類型的素材的總數
* 'item_count'=>0, //本次調用獲取的素材的數量
* 'item'=>array() //素材列表數組,內容定義請參考官方文檔
* )
*/
public function getForeverList($type,$offset,$count){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'type' => $type,
'offset' => $offset,
'count' => $count,
);
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_BATCHGET_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取永久素材總數(認證後的訂閱號可用)
* @return boolean|array
* 返回數組格式:
* array(
* 'voice_count'=>0, //語音總數量
* 'video_count'=>0, //視頻總數量
* 'image_count'=>0, //圖片總數量
* 'news_count'=>0 //圖文總數量
* )
*/
public function getForeverCount(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_FOREVER_COUNT_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 上傳圖文消息素材,用於羣發(認證後的訂閱號可用)
* @param array $data 消息結構{"articles":[{...}]}
* @return boolean|array
*/
public function uploadArticles($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 上傳視頻素材(認證後的訂閱號可用)
* @param array $data 消息結構
* {
* "media_id"=>"", //通過上傳媒體接口得到的MediaId
* "title"=>"TITLE", //視頻標題
* "description"=>"Description" //視頻描述
* }
* @return boolean|array
* {
* "type":"video",
* "media_id":"mediaid",
* "created_at":1398848981
* }
*/
public function uploadMpVideo($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_VIDEO_UPLOAD.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 高級羣發消息, 根據OpenID列表羣發圖文消息(訂閱號不可用)
* 注意:視頻需要在調用uploadMedia()方法後,再使用 uploadMpVideo() 方法生成,
* 然後獲得的 mediaid 才能用於羣發,且消息類型爲 mpvideo 類型。
* @param array $data 消息結構
* {
* "touser"=>array(
* "OPENID1",
* "OPENID2"
* ),
* "msgtype"=>"mpvideo",
* // 在下面5種類型中選擇對應的參數內容
* // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
* // text => array ( "content" => "hello")
* }
* @return boolean|array
*/
public function sendMassMessage($data){
dump($data);
die;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 高級羣發消息, 根據羣組id羣發圖文消息(認證後的訂閱號可用)
* 注意:視頻需要在調用uploadMedia()方法後,再使用 uploadMpVideo() 方法生成,
* 然後獲得的 mediaid 才能用於羣發,且消息類型爲 mpvideo 類型。
* @param array $data 消息結構
* {
* "filter"=>array(
* "is_to_all"=>False, //是否羣發給所有用戶.True不用分組id,False需填寫分組id
* "group_id"=>"2" //羣發的分組id
* ),
* "msgtype"=>"mpvideo",
* // 在下面5種類型中選擇對應的參數內容
* // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
* // text => array ( "content" => "hello")
* }
* @return boolean|array
*/
public function sendGroupMassMessage($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 高級羣發消息, 刪除羣發圖文消息(認證後的訂閱號可用)
* @param int $msg_id 消息id
* @return boolean|array
*/
public function deleteMassMessage($msg_id){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MASS_DELETE_URL.'access_token='.$this->access_token,self::json_encode(array('msg_id'=>$msg_id)));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 高級羣發消息, 預覽羣發消息(認證後的訂閱號可用)
* 注意:視頻需要在調用uploadMedia()方法後,再使用 uploadMpVideo() 方法生成,
* 然後獲得的 mediaid 才能用於羣發,且消息類型爲 mpvideo 類型。
* @param array $data 消息結構
* {
* "touser"=>"OPENID",
* "msgtype"=>"mpvideo",
* // 在下面5種類型中選擇對應的參數內容
* // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
* // text => array ( "content" => "hello")
* }
* @return boolean|array
*/
public function previewMassMessage($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MASS_PREVIEW_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 高級羣發消息, 查詢羣發消息發送狀態(認證後的訂閱號可用)
* @param int $msg_id 消息id
* @return boolean|array
* {
* "msg_id":201053012, //羣發消息後返回的消息id
* "msg_status":"SEND_SUCCESS" //消息發送後的狀態,SENDING表示正在發送 SEND_SUCCESS表示發送成功
* }
*/
public function queryMassMessage($msg_id){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MASS_QUERY_URL.'access_token='.$this->access_token,self::json_encode(array('msg_id'=>$msg_id)));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 創建二維碼ticket
* @param int|string $scene_id 自定義追蹤id,臨時二維碼只能用數值型
* @param int $type 0:臨時二維碼;1:數值型永久二維碼(此時expire參數無效);2:字符串型永久二維碼(此時expire參數無效)
* @param int $expire 臨時二維碼有效期,最大爲604800秒
* @return array('ticket'=>'qrcode字串','expire_seconds'=>604800,'url'=>'二維碼圖片解析後的地址')
*/
public function getQRCode($scene_id,$type=0,$expire=604800){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!isset($scene_id)) return false;
switch ($type) {
case '0':
if (!is_numeric($scene_id))
return false;
$action_name = 'QR_SCENE';
$action_info = array('scene'=>(array('scene_id'=>$scene_id)));
break;
case '1':
if (!is_numeric($scene_id))
return false;
$action_name = 'QR_LIMIT_SCENE';
$action_info = array('scene'=>(array('scene_id'=>$scene_id)));
break;
case '2':
if (!is_string($scene_id))
return false;
$action_name = 'QR_LIMIT_STR_SCENE';
$action_info = array('scene'=>(array('scene_str'=>$scene_id)));
break;
default:
return false;
}
$data = array(
'action_name' => $action_name,
'expire_seconds' => $expire,
'action_info' => $action_info
);
if ($type) {
unset($data['expire_seconds']);
}
$result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result) {
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取二維碼圖片
* @param string $ticket 傳入由getQRCode方法生成的ticket參數
* @return string url 返回http地址
*/
public function getQRUrl($ticket) {
return self::QRCODE_IMG_URL.urlencode($ticket);
}
/**
* 長鏈接轉短鏈接接口
* @param string $long_url 傳入要轉換的長url
* @return boolean|string url 成功則返回轉換後的短url
*/
public function getShortUrl($long_url){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'action'=>'long2short',
'long_url'=>$long_url
);
$result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json['short_url'];
}
return false;
}
/**
* 獲取統計數據
* @param string $type 數據分類(user|article|upstreammsg|interface)分別爲(用戶分析|圖文分析|消息分析|接口分析)
* @param string $subtype 數據子分類,參考 DATACUBE_URL_ARR 常量定義部分 或者README.md說明文檔
* @param string $begin_date 開始時間
* @param string $end_date 結束時間
* @return boolean|array 成功返回查詢結果數組,其定義請看官方文檔
*/
public function getDatacube($type,$subtype,$begin_date,$end_date=''){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!isset(self::$DATACUBE_URL_ARR[$type]) || !isset(self::$DATACUBE_URL_ARR[$type][$subtype]))
return false;
$data = array(
'begin_date'=>$begin_date,
'end_date'=>$end_date?$end_date:$begin_date
);
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::$DATACUBE_URL_ARR[$type][$subtype].'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return isset($json['list'])?$json['list']:$json;
}
return false;
}
/**
* 批量獲取關注用戶列表
* @param unknown $next_openid
*/
public function getUserList($next_openid=''){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取關注者詳細信息
* @param string $openid
* @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
* 注意:unionid字段 只有在用戶將公衆號綁定到微信開放平臺賬號後,纔會出現。建議調用前用isset()檢測一下
*/
public function getUserInfo($openid){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 設置用戶備註名
* @param string $openid
* @param string $remark 備註名
* @return boolean|array
*/
public function updateUserRemark($openid,$remark){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'openid'=>$openid,
'remark'=>$remark
);
$result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取用戶分組列表
* @return boolean|array
*/
public function getGroup(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取用戶所在分組
* @param string $openid
* @return boolean|int 成功則返回用戶分組id
*/
public function getUserGroup($openid){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'openid'=>$openid
);
$result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
} else
if (isset($json['groupid'])) return $json['groupid'];
}
return false;
}
/**
* 新增自定分組
* @param string $name 分組名稱
* @return boolean|array
*/
public function createGroup($name){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'group'=>array('name'=>$name)
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 更改分組名稱
* @param int $groupid 分組id
* @param string $name 分組名稱
* @return boolean|array
*/
public function updateGroup($groupid,$name){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'group'=>array('id'=>$groupid,'name'=>$name)
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 移動用戶分組
* @param int $groupid 分組id
* @param string $openid 用戶openid
* @return boolean|array
*/
public function updateGroupMembers($groupid,$openid){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'openid'=>$openid,
'to_groupid'=>$groupid
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 批量移動用戶分組
* @param int $groupid 分組id
* @param string $openid_list 用戶openid數組,一次不能超過50個
* @return boolean|array
*/
public function batchUpdateGroupMembers($groupid,$openid_list){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'openid_list'=>$openid_list,
'to_groupid'=>$groupid
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_BATCHUPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 發送客服消息
* @param array $data 消息結構{"touser":"OPENID","msgtype":"news","news":{...}}
* @return boolean|array
*/
public function sendCustomMessage($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* oauth 授權跳轉接口
* @param string $callback 回調URI
* @return string
*/
public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
}
/**
* 通過code獲取Access Token
* @return array {access_token,expires_in,refresh_token,openid,scope}
*/
public function getOauthAccessToken(){
$code = isset($_GET['code'])?$_GET['code']:'';
if (!$code) return false;
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->user_token = $json['access_token'];
return $json;
}
return false;
}
/**
* 刷新access token並續期
* @param string $refresh_token
* @return boolean|mixed
*/
public function getOauthRefreshToken($refresh_token){
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->user_token = $json['access_token'];
return $json;
}
return false;
}
/**
* 獲取授權後的用戶資料
* @param string $access_token
* @param string $openid
* @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
* 注意:unionid字段 只有在用戶將公衆號綁定到微信開放平臺賬號後,纔會出現。建議調用前用isset()檢測一下
*/
public function getOauthUserinfo($access_token,$openid){
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 檢驗授權憑證是否有效
* @param string $access_token
* @param string $openid
* @return boolean 是否有效
*/
public function getOauthAuth($access_token,$openid){
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
} else
if ($json['errcode']==0) return true;
}
return false;
}
/**
* 模板消息 設置所屬行業
* @param int $id1 公衆號模板消息所屬行業編號,參看官方開發文檔 行業代碼
* @param int $id2 同$id1。但如果只有一個行業,此參數可省略
* @return boolean|array
*/
public function setTMIndustry($id1,$id2=''){
if ($id1) $data['industry_id1'] = $id1;
if ($id2) $data['industry_id2'] = $id2;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SET_INDUSTRY_URL.'access_token='.$this->access_token,self::json_encode($data));
if($result){
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 模板消息 添加消息模板
* 成功返回消息模板的調用id
* @param string $tpl_id 模板庫中模板的編號,有“TM**”和“OPENTMTM**”等形式
* @return boolean|string
*/
public function addTemplateMessage($tpl_id){
$data = array ('template_id_short' =>$tpl_id);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_ADD_TPL_URL.'access_token='.$this->access_token,self::json_encode($data));
if($result){
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json['template_id'];
}
return false;
}
/**
* 發送模板消息
* @param array $data 消息結構
* {
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"topcolor":"#FF0000",
"data":{
"參數名1": {
"value":"參數",
"color":"#173177" //參數顏色
},
"Date":{
"value":"06月07日 19時24分",
"color":"#173177"
},
"CardNumber":{
"value":"0426",
"color":"#173177"
},
"Type":{
"value":"消費",
"color":"#173177"
}
}
}
* @return boolean|array
*/
public function sendTemplateMessage($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
if($result){
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取多客服會話記錄
* @param array $data 數據結構{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
* @return boolean|array
*/
public function getCustomServiceMessage($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
public function transfer_customer_service($customer_account = '')
{
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'CreateTime'=>time(),
'MsgType'=>'transfer_customer_service',
);
if ($customer_account) {
$msg['TransInfo'] = array('KfAccount'=>$customer_account);
}
$this->Message($msg);
return $this;
}
/**
* 獲取多客服客服基本信息
*
* @return boolean|array
*/
public function getCustomServiceKFlist(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取多客服在線客服接待信息
*
* @return boolean|array {
"kf_online_list": [
{
"kf_account": "test1@test", //客服賬號@微信別名
"status": 1, //客服在線狀態 1:pc在線,2:手機在線,若pc和手機同時在線則爲 1+2=3
"kf_id": "1001", //客服工號
"auto_accept": 0, //客服設置的最大自動接入數
"accepted_case": 1 //客服當前正在接待的會話數
}
]
}
*/
public function getCustomServiceOnlineKFlist(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 創建指定多客服會話
* @tutorial 當用戶已被其他客服接待或指定客服不在線則會失敗
* @param string $openid //用戶openid
* @param string $kf_account //客服賬號
* @param string $text //附加信息,文本會展示在客服人員的多客服客戶端,可爲空
* @return boolean | array //成功返回json數組
* {
* "errcode": 0,
* "errmsg": "ok",
* }
*/
public function createKFSession($openid,$kf_account,$text=''){
$data=array(
"openid" =>$openid,
"kf_account" => $kf_account
);
if ($text) $data["text"] = $text;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CREATE.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 關閉指定多客服會話
* @tutorial 當用戶被其他客服接待時則會失敗
* @param string $openid //用戶openid
* @param string $kf_account //客服賬號
* @param string $text //附加信息,文本會展示在客服人員的多客服客戶端,可爲空
* @return boolean | array //成功返回json數組
* {
* "errcode": 0,
* "errmsg": "ok",
* }
*/
public function closeKFSession($openid,$kf_account,$text=''){
$data=array(
"openid" =>$openid,
"kf_account" => $kf_account
);
if ($text) $data["text"] = $text;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CLOSE .'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取用戶會話狀態
* @param string $openid //用戶openid
* @return boolean | array //成功返回json數組
* {
* "errcode" : 0,
* "errmsg" : "ok",
* "kf_account" : "test1@test", //正在接待的客服
* "createtime": 123456789, //會話接入時間
* }
*/
public function getKFSession($openid){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET .'access_token='.$this->access_token.'&openid='.$openid);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取指定客服的會話列表
* @param string $openid //用戶openid
* @return boolean | array //成功返回json數組
* array(
* 'sessionlist' => array (
* array (
* 'openid'=>'OPENID', //客戶 openid
* 'createtime'=>123456789, //會話創建時間,UNIX 時間戳
* ),
* array (
* 'openid'=>'OPENID', //客戶 openid
* 'createtime'=>123456789, //會話創建時間,UNIX 時間戳
* ),
* )
* )
*/
public function getKFSessionlist($kf_account){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_LIST .'access_token='.$this->access_token.'&kf_account='.$kf_account);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取未接入會話列表
* @param string $openid //用戶openid
* @return boolean | array //成功返回json數組
* array (
* 'count' => 150 , //未接入會話數量
* 'waitcaselist' => array (
* array (
* 'openid'=>'OPENID', //客戶 openid
* 'kf_account ' =>'', //指定接待的客服,爲空則未指定
* 'createtime'=>123456789, //會話創建時間,UNIX 時間戳
* ),
* array (
* 'openid'=>'OPENID', //客戶 openid
* 'kf_account ' =>'', //指定接待的客服,爲空則未指定
* 'createtime'=>123456789, //會話創建時間,UNIX 時間戳
* )
* )
* )
*/
public function getKFSessionWait(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_WAIT .'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 添加客服賬號
*
* @param string $account //完整客服賬號,格式爲:賬號前綴@公衆號微信號,賬號前綴最多10個字符,必須是英文或者數字字符
* @param string $nickname //客服暱稱,最長6個漢字或12個英文字符
* @param string $password //客服賬號明文登錄密碼,會自動加密
* @return boolean|array
* 成功返回結果
* {
* "errcode": 0,
* "errmsg": "ok",
* }
*/
public function addKFAccount($account,$nickname,$password){
$data=array(
"kf_account" =>$account,
"nickname" => $nickname,
"password" => md5($password)
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_ADD_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 修改客服賬號信息
*
* @param string $account //完整客服賬號,格式爲:賬號前綴@公衆號微信號,賬號前綴最多10個字符,必須是英文或者數字字符
* @param string $nickname //客服暱稱,最長6個漢字或12個英文字符
* @param string $password //客服賬號明文登錄密碼,會自動加密
* @return boolean|array
* 成功返回結果
* {
* "errcode": 0,
* "errmsg": "ok",
* }
*/
public function updateKFAccount($account,$nickname,$password){
$data=array(
"kf_account" =>$account,
"nickname" => $nickname,
"password" => md5($password)
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 刪除客服賬號
*
* @param string $account //完整客服賬號,格式爲:賬號前綴@公衆號微信號,賬號前綴最多10個字符,必須是英文或者數字字符
* @return boolean|array
* 成功返回結果
* {
* "errcode": 0,
* "errmsg": "ok",
* }
*/
public function deleteKFAccount($account){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_DEL_URL.'access_token='.$this->access_token.'&kf_account='.$account);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 上傳客服頭像
*
* @param string $account //完整客服賬號,格式爲:賬號前綴@公衆號微信號,賬號前綴最多10個字符,必須是英文或者數字字符
* @param string $imgfile //頭像文件完整路徑,如:'D:\user.jpg'。頭像文件必須JPG格式,像素建議640*640
* @return boolean|array
* 成功返回結果
* {
* "errcode": 0,
* "errmsg": "ok",
* }
*/
public function setKFHeadImg($account,$imgfile){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL.'access_token='.$this->access_token.'&kf_account='.$account,array('media'=>'@'.$imgfile),true);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 語義理解接口
* @param String $uid 用戶唯一id(非開發者id),用戶區分公衆號下的不同用戶(建議填入用戶openid)
* @param String $query 輸入文本串
* @param String $category 需要使用的服務類型,多個用“,”隔開,不能爲空
* @param Float $latitude 緯度座標,與經度同時傳入;與城市二選一傳入
* @param Float $longitude 經度座標,與緯度同時傳入;與城市二選一傳入
* @param String $city 城市名稱,與經緯度二選一傳入
* @param String $region 區域名稱,在城市存在的情況下可省略;與經緯度二選一傳入
* @return boolean|array
*/
public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
if (!$this->access_token && !$this->checkAuth()) return false;
$data=array(
'query' => $query,
'category' => $category,
'appid' => $this->appid,
'uid' => ''
);
//地理座標或城市名稱二選一
if ($latitude) {
$data['latitude'] = $latitude;
$data['longitude'] = $longitude;
} elseif ($city) {
$data['city'] = $city;
} elseif ($region) {
$data['region'] = $region;
}
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 創建卡券
* @param Array $data 卡券數據
* @return array|boolean 返回數組中card_id爲卡券ID
*/
public function createCard($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 更改卡券信息
* 調用該接口更新信息後會重新送審,卡券狀態變更爲待審覈。已被用戶領取的卡券會實時更新票面信息。
* @param string $data
* @return boolean
*/
public function updateCard($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 刪除卡券
* 允許商戶刪除任意一類卡券。刪除卡券後,該卡券對應已生成的領取用二維碼、添加到卡包 JS API 均會失效。
* 注意:刪除卡券不能刪除已被用戶領取,保存在微信客戶端中的卡券,已領取的卡券依舊有效。
* @param string $card_id 卡券ID
* @return boolean
*/
public function delCard($card_id) {
$data = array(
'card_id' => $card_id,
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 查詢卡券詳情
* @param string $card_id
* @return boolean|array 返回數組信息比較複雜,請參看卡券接口文檔
*/
public function getCardInfo($card_id) {
$data = array(
'card_id' => $card_id,
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_GET . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取顏色列表
* 獲得卡券的最新顏色列表,用於創建卡券
* @return boolean|array 返回數組請參看 微信卡券接口文檔 的json格式
*/
public function getCardColors() {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_BASE_URL_PREFIX . self::CARD_GETCOLORS . 'access_token=' . $this->access_token);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 拉取門店列表
* 獲取在公衆平臺上申請創建的門店列表
* @param int $offset 開始拉取的偏移,默認爲0從頭開始
* @param int $count 拉取的數量,默認爲0拉取全部
* @return boolean|array 返回數組請參看 微信卡券接口文檔 的json格式
*/
public function getCardLocations($offset=0,$count=0) {
$data=array(
'offset'=>$offset,
'count'=>$count
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 批量導入門店信息
* @tutorial 返回插入的門店id列表,以逗號分隔。如果有插入失敗的,則爲-1,請自行覈查是哪個插入失敗
* @param array $data 數組形式的json數據,由於內容較多,具體內容格式請查看 微信卡券接口文檔
* @return boolean|string 成功返回插入的門店id列表
*/
public function addCardLocations($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHADD . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 生成卡券二維碼
* 成功則直接返回ticket值,可以用 getQRUrl($ticket) 換取二維碼url
*
* @param string $cardid 卡券ID 必須
* @param string $code 指定卡券 code 碼,只能被領一次。use_custom_code 字段爲 true 的卡券必須填寫,非自定義 code 不必填寫。
* @param string $openid 指定領取者的 openid,只有該用戶能領取。bind_openid 字段爲 true 的卡券必須填寫,非自定義 openid 不必填寫。
* @param int $expire_seconds 指定二維碼的有效時間,範圍是 60 ~ 1800 秒。不填默認爲永久有效。
* @param boolean $is_unique_code 指定下發二維碼,生成的二維碼隨機分配一個 code,領取後不可再次掃描。填寫 true 或 false。默認 false。
* @param string $balance 紅包餘額,以分爲單位。紅包類型必填(LUCKY_MONEY),其他卡券類型不填。
* @return boolean|string
*/
public function createCardQrcode($card_id,$code='',$openid='',$expire_seconds=0,$is_unique_code=false,$balance='') {
$card = array(
'card_id' => $card_id
);
$data = array(
'action_name' => "QR_CARD"
);
if ($code)
$card['code'] = $code;
if ($openid)
$card['openid'] = $openid;
if ($is_unique_code)
$card['is_unique_code'] = $is_unique_code;
if ($balance)
$card['balance'] = $balance;
if ($expire_seconds)
$data['expire_seconds'] = $expire_seconds;
$data['action_info'] = array('card' => $card);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_QRCODE_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 消耗 code
* 自定義 code(use_custom_code 爲 true)的優惠券,在 code 被覈銷時,必須調用此接口。
*
* @param string $code 要消耗的序列號
* @param string $card_id 要消耗序列號所述的 card_id,創建卡券時use_custom_code 填寫 true 時必填。
* @return boolean|array
* {
* "errcode":0,
* "errmsg":"ok",
* "card":{"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"},
* "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA"
* }
*/
public function consumeCardCode($code,$card_id='') {
$data = array('code' => $code);
if ($card_id)
$data['card_id'] = $card_id;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_CONSUME . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* code 解碼
* @param string $encrypt_code 通過 choose_card_info 獲取的加密字符串
* @return boolean|array
* {
* "errcode":0,
* "errmsg":"ok",
* "code":"751234212312"
* }
*/
public function decryptCardCode($encrypt_code) {
$data = array(
'encrypt_code' => $encrypt_code,
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_DECRYPT . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 查詢 code 的有效性(非自定義 code)
* @param string $code
* @return boolean|array
* {
* "errcode":0,
* "errmsg":"ok",
* "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA", //用戶 openid
* "card":{
* "card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc",
* "begin_time": 1404205036, //起始使用時間
* "end_time": 1404205036, //結束時間
* }
* }
*/
public function checkCardCode($code) {
$data = array(
'code' => $code,
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_GET . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 批量查詢卡列表
* @param $offset 開始拉取的偏移,默認爲0從頭開始
* @param $count 需要查詢的卡片的數量(數量最大50,默認50)
* @return boolean|array
* {
* "errcode":0,
* "errmsg":"ok",
* "card_id_list":["ph_gmt7cUVrlRk8swPwx7aDyF-pg"], //卡 id 列表
* "total_num":1 //該商戶名下 card_id 總數
* }
*/
public function getCardIdList($offset=0,$count=50) {
if ($count>50)
$count = 50;
$data = array(
'offset' => $offset,
'count' => $count,
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 更改 code
* 爲確保轉贈後的安全性,微信允許自定義code的商戶對已下發的code進行更改。
* 注:爲避免用戶疑惑,建議僅在發生轉贈行爲後(發生轉贈後,微信會通過事件推送的方式告知商戶被轉贈的卡券code)對用戶的code進行更改。
* @param string $code 卡券的 code 編碼
* @param string $card_id 卡券 ID
* @param string $new_code 新的卡券 code 編碼
* @return boolean
*/
public function updateCardCode($code,$card_id,$new_code) {
$data = array(
'code' => $code,
'card_id' => $card_id,
'new_code' => $new_code,
);
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 設置卡券失效
* 設置卡券失效的操作不可逆
* @param string $code 需要設置爲失效的 code
* @param string $card_id 自定義 code 的卡券必填。非自定義 code 的卡券不填。
* @return boolean
*/
public function unavailableCardCode($code,$card_id='') {
$data = array(
'code' => $code,
);
if ($card_id)
$data['card_id'] = $card_id;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UNAVAILABLE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 庫存修改
* @param string $data
* @return boolean
*/
public function modifyCardStock($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MODIFY_STOCK . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 更新門票
* @param string $data
* @return boolean
*/
public function updateMeetingCard($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEETINGCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 激活/綁定會員卡
* @param string $data 具體結構請參看卡券開發文檔(6.1.1 激活/綁定會員卡)章節
* @return boolean
*/
public function activateMemberCard($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_ACTIVATE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 會員卡交易
* 會員卡交易後每次積分及餘額變更需通過接口通知微信,便於後續消息通知及其他擴展功能。
* @param string $data 具體結構請參看卡券開發文檔(6.1.2 會員卡交易)章節
* @return boolean|array
*/
public function updateMemberCard($data) {
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 更新紅包金額
* @param string $code 紅包的序列號
* @param $balance 紅包餘額
* @param string $card_id 自定義 code 的卡券必填。非自定義 code 可不填。
* @return boolean|array
*/
public function updateLuckyMoney($code,$balance,$card_id='') {
$data = array(
'code' => $code,
'balance' => $balance
);
if ($card_id)
$data['card_id'] = $card_id;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LUCKYMONEY_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 設置卡券測試白名單
* @param string $openid 測試的 openid 列表
* @param string $user 測試的微信號列表
* @return boolean
*/
public function setCardTestWhiteList($openid=array(),$user=array()) {
$data = array();
if (count($openid) > 0)
$data['openid'] = $openid;
if (count($user) > 0)
$data['username'] = $user;
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_TESTWHILELIST_SET . 'access_token=' . $this->access_token, self::json_encode($data));
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 申請設備ID
* [applyShakeAroundDevice 申請配置設備所需的UUID、Major、Minor。
* 若激活率小於50%,不能新增設備。單次新增設備超過500 個,需走人工審覈流程。
* 審覈通過後,可用迒回的批次ID 用“查詢設備列表”接口拉取本次申請的設備ID]
* @param array $data
* array(
* "quantity" => 3, //申請的設備ID 的數量,單次新增設備超過500 個,需走人工審覈流程(必填)
* "apply_reason" => "測試",//申請理由(必填)
* "comment" => "測試專用", //備註(非必填)
* "poi_id" => 1234 //設備關聯的門店ID(非必填)
* )
* @return boolean|mixed
* {
"data": {
"apply_id": 123,
"device_identifiers":[
{
"device_id":10100,
"uuid":"FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major":10001,
"minor":10002
}
]
},
"errcode": 0,
"errmsg": "success."
}
apply_id:申請的批次ID,可用在“查詢設備列表”接口按批次查詢本次申請成功的設備ID
device_identifiers:指定的設備ID 列表
device_id:設備編號
uuid、major、minor
audit_status:審覈狀態。0:審覈未通過、1:審覈中、2:審覈已通過;審覈會在三個工作日內完成
audit_comment:審覈備註,包括審覈不通過的原因
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午1:24:06
* @copyright Show More
*/
public function applyShakeAroundDevice($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_APPLYID . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 編輯設備信息
* [updateShakeAroundDevice 編輯設備的備註信息。可用設備ID或完整的UUID、Major、Minor指定設備,二者選其一。]
* @param array $data
* array(
* "device_identifier" => array(
* "device_id" => 10011, //當提供了device_id則不需要使用uuid、major、minor,反之亦然
* "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
* "major" => 1002,
* "minor" => 1223
* ),
* "comment" => "測試專用", //備註(非必填)
* )
* {
"data": {
},
"errcode": 0,
"errmsg": "success."
}
* @return boolean
* @author binsee<[email protected]>
* @version 2015-4-20 23:45:00
*/
public function updateShakeAroundDevice($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 查詢設備列表
* [searchShakeAroundDevice 查詢已有的設備ID、UUID、Major、Minor、激活狀態、備註信息、關聯門店、關聯頁面等信息。
* 可指定設備ID 或完整的UUID、Major、Minor 查詢,也可批量拉取設備信息列表。]
* @param array $data
* $data 三種格式:
* ①查詢指定設備時:$data = array(
* "device_identifiers" => array(
* array(
* "device_id" => 10100,
* "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
* "major" => 10001,
* "minor" => 10002
* )
* )
* );
* device_identifiers:指定的設備
* device_id:設備編號,若填了UUID、major、minor,則可不填設備編號,若二者都填,則以設備編號爲優先
* uuid、major、minor:三個信息需填寫完整,若填了設備編號,則可不填此信息
* +-------------------------------------------------------------------------------------------------------------
* ②需要分頁查詢或者指定範圍內的設備時: $data = array(
* "begin" => 0,
* "count" => 3
* );
* begin:設備列表的起始索引值
* count:待查詢的設備個數
* +-------------------------------------------------------------------------------------------------------------
* ③當需要根據批次ID 查詢時: $data = array(
* "apply_id" => 1231,
* "begin" => 0,
* "count" => 3
* );
* apply_id:批次ID
* +-------------------------------------------------------------------------------------------------------------
* @return boolean|mixed
*正確迒回JSON 數據示例:
*字段說明
{
"data": {
"devices": [ //指定的設備信息列表
{
"comment": "", //設備的備註信息
"device_id": 10097, //設備編號
"major": 10001,
"minor": 12102,
"page_ids": "15369", //與此設備關聯的頁面ID 列表,用逗號隔開
"status": 1, //激活狀態,0:未激活,1:已激活(但不活躍),2:活躍
"poi_id": 0, //門店ID
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"comment": "", //設備的備註信息
"device_id": 10098, //設備編號
"major": 10001,
"minor": 12103,
"page_ids": "15368", //與此設備關聯的頁面ID 列表,用逗號隔開
"status": 1, //激活狀態,0:未激活,1:已激活(但不活躍),2:活躍
"poi_id": 0, //門店ID
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 151 //商戶名下的設備總量
},
"errcode": 0,
"errmsg": "success."
}
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午1:45:42
* @copyright Show More
*/
public function searchShakeAroundDevice($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [bindLocationShakeAroundDevice 配置設備與門店的關聯關係]
* @param string $device_id 設備編號,若填了UUID、major、minor,則可不填設備編號,若二者都填,則以設備編號爲優先
* @param int $poi_id 待關聯的門店ID
* @param string $uuid UUID、major、minor,三個信息需填寫完整,若填了設備編號,則可不填此信息
* @param int $major
* @param int $minor
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": {
},
"errcode": 0,
"errmsg": "success."
}
* @access public
* @author polo<[email protected]>
* @version 2015-4-21 00:14:00
* @copyright Show More
*/
public function bindLocationShakeAroundDevice($device_id,$poi_id,$uuid='',$major=0,$minor=0){
if (!$this->access_token && !$this->checkAuth()) return false;
if(!$device_id){
if(!$uuid || !$major || !$minor){
return false;
}
$device_identifier = array(
'uuid' => $uuid,
'major' => $major,
'minor' => $minor
);
}else{
$device_identifier = array(
'device_id' => $device_id
);
}
$data = array(
'device_identifier' => $device_identifier,
'poi_id' => $poi_id
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDLOCATION . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json; //這個可以更改爲返回true
}
return false;
}
/**
* [bindPageShakeAroundDevice 配置設備與頁面的關聯關係。
* 支持建立或解除關聯關係,也支持新增頁面或覆蓋頁面等操作。
* 配置完成後,在此設備的信號範圍內,即可搖出關聯的頁面信息。
* 若設備配置多個頁面,則隨機出現頁面信息]
* @param string $device_id 設備編號,若填了UUID、major、minor,則可不填設備編號,若二者都填,則以設備編號爲優先
* @param array $page_ids 待關聯的頁面列表
* @param number $bind 關聯操作標誌位, 0 爲解除關聯關係,1 爲建立關聯關係
* @param number $append 新增操作標誌位, 0 爲覆蓋,1 爲新增
* @param string $uuid UUID、major、minor,三個信息需填寫完整,若填了設備編號,則可不填此信息
* @param int $major
* @param int $minor
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": {
},
"errcode": 0,
"errmsg": "success."
}
* @access public
* @author polo<[email protected]>
* @version 2015-4-21 00:31:00
* @copyright Show More
*/
public function bindPageShakeAroundDevice($device_id,$page_ids=array(),$bind=1,$append=1,$uuid='',$major=0,$minor=0){
if (!$this->access_token && !$this->checkAuth()) return false;
if(!$device_id){
if(!$uuid || !$major || !$minor){
return false;
}
$device_identifier = array(
'uuid' => $uuid,
'major' => $major,
'minor' => $minor
);
}else{
$device_identifier = array(
'device_id' => $device_id
);
}
$data = array(
'device_identifier' => $device_identifier,
'page_ids' => $page_ids,
'bind' => $bind,
'append' => $append
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDPAGE . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 上傳在搖一搖頁面展示的圖片素材
* 注意:數組的鍵值任意,但文件名前必須加@,使用單引號以避免本地路徑斜槓被轉義
* @param array $data {"media":'@Path\filename.jpg'} 格式限定爲:jpg,jpeg,png,gif,圖片大小建議120px*120 px,限制不超過200 px *200 px,圖片需爲正方形。
* @return boolean|array
* {
"data": {
"pic_url":"http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
},
"errcode": 0,
"errmsg": "success."
}
}
* @author binsee<[email protected]>
* @version 2015-4-21 00:51:00
*/
public function uploadShakeAroundMedia($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::SHAKEAROUND_MATERIAL_ADD.'access_token='.$this->access_token,$data,true);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [addShakeAroundPage 增加搖一搖出來的頁面信息,包括在搖一搖頁面出現的主標題、副標題、圖片和點擊進去的超鏈接。]
* @param string $title 在搖一搖頁面展示的主標題,不超過6 個字
* @param string $description 在搖一搖頁面展示的副標題,不超過7 個字
* @param sting $icon_url 在搖一搖頁面展示的圖片, 格式限定爲:jpg,jpeg,png,gif; 建議120*120 , 限制不超過200*200
* @param string $page_url 跳轉鏈接
* @param string $comment 頁面的備註信息,不超過15 個字,可不填
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": {
"page_id": 28840 //新增頁面的頁面id
}
"errcode": 0,
"errmsg": "success."
}
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午2:57:09
* @copyright Show More
*/
public function addShakeAroundPage($title,$description,$icon_url,$page_url,$comment=''){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
"title" => $title,
"description" => $description,
"icon_url" => $icon_url,
"page_url" => $page_url,
"comment" => $comment
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_ADD . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [updateShakeAroundPage 編輯搖一搖出來的頁面信息,包括在搖一搖頁面出現的主標題、副標題、圖片和點擊進去的超鏈接。]
* @param int $page_id
* @param string $title 在搖一搖頁面展示的主標題,不超過6 個字
* @param string $description 在搖一搖頁面展示的副標題,不超過7 個字
* @param sting $icon_url 在搖一搖頁面展示的圖片, 格式限定爲:jpg,jpeg,png,gif; 建議120*120 , 限制不超過200*200
* @param string $page_url 跳轉鏈接
* @param string $comment 頁面的備註信息,不超過15 個字,可不填
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": {
"page_id": 28840 //編輯頁面的頁面ID
}
"errcode": 0,
"errmsg": "success."
}
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午3:02:51
* @copyright Show More
*/
public function updateShakeAroundPage($page_id,$title,$description,$icon_url,$page_url,$comment=''){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
"page_id" => $page_id,
"title" => $title,
"description" => $description,
"icon_url" => $icon_url,
"page_url" => $page_url,
"comment" => $comment
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [searchShakeAroundPage 查詢已有的頁面,包括在搖一搖頁面出現的主標題、副標題、圖片和點擊進去的超鏈接。
* 提供兩種查詢方式,①可指定頁面ID 查詢,②也可批量拉取頁面列表。]
* @param array $page_ids
* @param int $begin
* @param int $count
* ①需要查詢指定頁面時:
* {
"page_ids":[12345, 23456, 34567]
}
* +-------------------------------------------------------------------------------------------------------------
* ②需要分頁查詢或者指定範圍內的頁面時:
* {
"begin": 0,
"count": 3
}
* +-------------------------------------------------------------------------------------------------------------
* @return boolean|mixed
* 正確返回JSON 數據示例:
{
"data": {
"pages": [
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1.png",
"page_id": 28840,
"page_url": "http://xw.qq.com/testapi1",
"title": "測試1"
},
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1.png",
"page_id": 28842,
"page_url": "http://xw.qq.com/testapi2",
"title": "測試2"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*字段說明:
*total_count 商戶名下的頁面總數
*page_id 搖周邊頁面唯一ID
*title 在搖一搖頁面展示的主標題
*description 在搖一搖頁面展示的副標題
*icon_url 在搖一搖頁面展示的圖片
*page_url 跳轉鏈接
*comment 頁面的備註信息
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午3:12:17
* @copyright Show More
*/
public function searchShakeAroundPage($page_ids=array(),$begin=0,$count=1){
if (!$this->access_token && !$this->checkAuth()) return false;
if(!empty($page_ids)){
$data = array(
'page_ids' => $page_ids
);
}else{
$data = array(
'begin' => $begin,
'count' => $count
);
}
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [deleteShakeAroundPage 刪除已有的頁面,包括在搖一搖頁面出現的主標題、副標題、圖片和點擊進去的超鏈接。
* 只有頁面與設備沒有關聯關係時,纔可被刪除。]
* @param array $page_ids
* {
"page_ids":[12345,23456,34567]
}
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": {
},
"errcode": 0,
"errmsg": "success."
}
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午3:23:00
* @copyright Show More
*/
public function deleteShakeAroundPage($page_ids=array()){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'page_ids' => $page_ids
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [getShakeInfoShakeAroundUser 獲取設備信息,包括UUID、major、minor,以及距離、openID 等信息。]
* @param string $ticket 搖周邊業務的ticket,可在搖到的URL 中得到,ticket生效時間爲30 分鐘
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": {
"page_id ": 14211,
"beacon_info": {
"distance": 55.00620700469034,
"major": 10001,
"minor": 19007,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
"openid": "oVDmXjp7y8aG2AlBuRpMZTb1-cmA"
},
"errcode": 0,
"errmsg": "success."
}
* 字段說明:
* beacon_info 設備信息,包括UUID、major、minor,以及距離
* UUID、major、minor UUID、major、minor
* distance Beacon 信號與手機的距離
* page_id 搖周邊頁面唯一ID
* openid 商戶AppID 下用戶的唯一標識
* poi_id 門店ID,有的話則返回,沒有的話不會在JSON 格式內
* @access public
* @author polo<[email protected]>
* @version 2015-3-25 下午3:28:20
* @copyright Show More
*/
public function getShakeInfoShakeAroundUser($ticket){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array('ticket' => $ticket);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_USER_GETSHAKEINFO . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [deviceShakeAroundStatistics 以設備爲維度的數據統計接口。
* 查詢單個設備進行搖周邊操作的人數、次數,點擊搖周邊消息的人數、次數;查詢的最長時間跨度爲30天。]
* @param int $device_id 設備編號,若填了UUID、major、minor,即可不填設備編號,二者選其一
* @param int $begin_date 起始日期時間戳,最長時間跨度爲30 天
* @param int $end_date 結束日期時間戳,最長時間跨度爲30 天
* @param string $uuid UUID、major、minor,三個信息需填寫完成,若填了設備編輯,即可不填此信息,二者選其一
* @param int $major
* @param int $minor
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
* 字段說明:
* ftime 當天0 點對應的時間戳
* click_pv 點擊搖周邊消息的次數
* click_uv 點擊搖周邊消息的人數
* shake_pv 搖周邊的次數
* shake_uv 搖周邊的人數
* @access public
* @author polo<[email protected]>
* @version 2015-4-21 00:39:00
* @copyright Show More
*/
public function deviceShakeAroundStatistics($device_id,$begin_date,$end_date,$uuid='',$major=0,$minor=0){
if (!$this->access_token && !$this->checkAuth()) return false;
if(!$device_id){
if(!$uuid || !$major || !$minor){
return false;
}
$device_identifier = array(
'uuid' => $uuid,
'major' => $major,
'minor' => $minor
);
}else{
$device_identifier = array(
'device_id' => $device_id
);
}
$data = array(
'device_identifier' => $device_identifier,
'begin_date' => $begin_date,
'end_date' => $end_date
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* [pageShakeAroundStatistics 以頁面爲維度的數據統計接口。
* 查詢單個頁面通過搖周邊搖出來的人數、次數,點擊搖周邊頁面的人數、次數;查詢的最長時間跨度爲30天。]
* @param int $page_id 指定頁面的ID
* @param int $begin_date 起始日期時間戳,最長時間跨度爲30 天
* @param int $end_date 結束日期時間戳,最長時間跨度爲30 天
* @return boolean|mixed
* 正確返回JSON 數據示例:
* {
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
* 字段說明:
* ftime 當天0 點對應的時間戳
* click_pv 點擊搖周邊消息的次數
* click_uv 點擊搖周邊消息的人數
* shake_pv 搖周邊的次數
* shake_uv 搖周邊的人數
* @author binsee<[email protected]>
* @version 2015-4-21 00:43:00
*/
public function pageShakeAroundStatistics($page_id,$begin_date,$end_date){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'page_id' => $page_id,
'begin_date' => $begin_date,
'end_date' => $end_date
);
$result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
$this->log($result);
if ($result) {
$json = json_decode($result, true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 根據訂單ID獲取訂單詳情
* @param string $order_id 訂單ID
* @return order array|bool
*/
public function getOrderByID($order_id){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!$order_id) return false;
$data = array(
'order_id'=>$order_id
);
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_GETBYID.'access_token='.$this->access_token, self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode']) && $json['errcode']) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json['order'];
}
return false;
}
/**
* 根據訂單狀態/創建時間獲取訂單詳情
* @param int $status 訂單狀態(不帶該字段-全部狀態, 2-待發貨, 3-已發貨, 5-已完成, 8-維權中, )
* @param int $begintime 訂單創建時間起始時間(不帶該字段則不按照時間做篩選)
* @param int $endtime 訂單創建時間終止時間(不帶該字段則不按照時間做篩選)
* @return order list array|bool
*/
public function getOrderByFilter($status = null, $begintime = null, $endtime = null){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array();
$valid_status = array(2, 3, 5, 8);
if (is_numeric($status) && in_array($status, $valid_status)) {
$data['status'] = $status;
}
if (is_numeric($begintime) && is_numeric($endtime)) {
$data['begintime'] = $begintime;
$data['endtime'] = $endtime;
}
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_GETBYFILTER.'access_token='.$this->access_token, self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode']) && $json['errcode']) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json['order_list'];
}
return false;
}
/**
* 設置訂單發貨信息
* @param string $order_id 訂單 ID
* @param int $need_delivery 商品是否需要物流(0-不需要,1-需要)
* @param string $delivery_company 物流公司 ID
* @param string $delivery_track_no 運單 ID
* @param int $is_others 是否爲 6.4.5 表之外的其它物流公司(0-否,1-是)
* @return bool
*/
public function setOrderDelivery($order_id, $need_delivery = 0, $delivery_company = null, $delivery_track_no = null, $is_others = 0){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!$order_id) return false;
$data = array();
$data['order_id'] = $order_id;
if ($need_delivery) {
$data['delivery_company'] = $delivery_company;
$data['delivery_track_no'] = $delivery_track_no;
$data['is_others'] = $is_others;
}
else {
$data['need_delivery'] = $need_delivery;
}
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_SETDELIVERY.'access_token='.$this->access_token, self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode']) && $json['errcode']) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 關閉訂單
* @param string $order_id 訂單 ID
* @return bool
*/
public function closeOrder($order_id){
if (!$this->access_token && !$this->checkAuth()) return false;
if (!$order_id) return false;
$data = array(
'order_id'=>$order_id
);
$result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_CLOSE.'access_token='.$this->access_token, self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode']) && $json['errcode']) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
private function parseSkuInfo($skuInfo) {
$skuInfo = str_replace("\$", "", $skuInfo);
$matches = explode(";", $skuInfo);
$result = array();
foreach ($matches as $matche) {
$arrs = explode(":", $matche);
$result[$arrs[0]] = $arrs[1];
}
return $result;
}
/**
* 獲取訂單SkuInfo - 訂單付款通知
* 當Event爲 merchant_order(訂單付款通知)
* @return array|boolean
*/
public function getRevOrderSkuInfo(){
if (isset($this->_receive['SkuInfo'])) //訂單 SkuInfo
return $this->parseSkuInfo($this->_receive['SkuInfo']);
else
return false;
}
}
/**
* PKCS7Encoder class
*
* 提供基於PKCS7算法的加解密接口.
*/
class PKCS7Encoder
{
public static $block_size = 32;
/**
* 對需要加密的明文進行填充補位
* @param $text 需要進行填充補位操作的明文
* @return 補齊明文字符串
*/
function encode($text)
{
$block_size = PKCS7Encoder::$block_size;
$text_length = strlen($text);
//計算需要填充的位數
$amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
if ($amount_to_pad == 0) {
$amount_to_pad = PKCS7Encoder::block_size;
}
//獲得補位所用的字符
$pad_chr = chr($amount_to_pad);
$tmp = "";
for ($index = 0; $index < $amount_to_pad; $index++) {
$tmp .= $pad_chr;
}
return $text . $tmp;
}
/**
* 對解密後的明文進行補位刪除
* @param decrypted 解密後的明文
* @return 刪除填充補位後的明文
*/
function decode($text)
{
$pad = ord(substr($text, -1));
if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}
}
/**
* Prpcrypt class
*
* 提供接收和推送給公衆平臺消息的加解密接口.
*/
class Prpcrypt
{
public $key;
function __construct($k) {
$this->key = base64_decode($k . "=");
}
/**
* 兼容老版本php構造函數,不能在 __construct() 方法前邊,否則報錯
*/
function Prpcrypt($k)
{
$this->key = base64_decode($k . "=");
}
/**
* 對明文進行加密
* @param string $text 需要加密的明文
* @return string 加密後的密文
*/
public function encrypt($text, $appid)
{
try {
//獲得16位隨機字符串,填充到明文之前
$random = $this->getRandomStr();//"aaaabbbbccccdddd";
$text = $random . pack("N", strlen($text)) . $text . $appid;
// 網絡字節序
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
//使用自定義的填充方式對明文進行補位填充
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
mcrypt_generic_init($module, $this->key, $iv);
//加密
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
// print(base64_encode($encrypted));
//使用BASE64對加密後的字符串進行編碼
return array(ErrorCode::$OK, base64_encode($encrypted));
} catch (Exception $e) {
//print $e;
return array(ErrorCode::$EncryptAESError, null);
}
}
/**
* 對密文進行解密
* @param string $encrypted 需要解密的密文
* @return string 解密得到的明文
*/
public function decrypt($encrypted, $appid)
{
try {
//使用BASE64對需要解密的字符串進行解碼
$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
mcrypt_generic_init($module, $this->key, $iv);
//解密
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
} catch (Exception $e) {
return array(ErrorCode::$DecryptAESError, null);
}
try {
//去除補位字符
$pkc_encoder = new PKCS7Encoder;
$result = $pkc_encoder->decode($decrypted);
//去除16位隨機字符串,網絡字節序和AppId
if (strlen($result) < 16)
return "";
$content = substr($result, 16, strlen($result));
$len_list = unpack("N", substr($content, 0, 4));
$xml_len = $len_list[1];
$xml_content = substr($content, 4, $xml_len);
$from_appid = substr($content, $xml_len + 4);
if (!$appid)
$appid = $from_appid;
//如果傳入的appid是空的,則認爲是訂閱號,使用數據中提取出來的appid
} catch (Exception $e) {
//print $e;
return array(ErrorCode::$IllegalBuffer, null);
}
if ($from_appid != $appid)
return array(ErrorCode::$ValidateAppidError, null);
//不註釋上邊兩行,避免傳入appid是錯誤的情況
return array(0, $xml_content, $from_appid); //增加appid,爲了解決後面加密回覆消息的時候沒有appid的訂閱號會無法回覆
}
/**
* 隨機生成16位字符串
* @return string 生成的字符串
*/
function getRandomStr()
{
$str = "";
$str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($str_pol) - 1;
for ($i = 0; $i < 16; $i++) {
$str .= $str_pol[mt_rand(0, $max)];
}
return $str;
}
}
/**
* error code
* 僅用作類內部使用,不用於官方API接口的errCode碼
*/
class ErrorCode
{
public static $OK = 0;
public static $ValidateSignatureError = 40001;
public static $ParseXmlError = 40002;
public static $ComputeSignatureError = 40003;
public static $IllegalAesKey = 40004;
public static $ValidateAppidError = 40005;
public static $EncryptAESError = 40006;
public static $DecryptAESError = 40007;
public static $IllegalBuffer = 40008;
public static $EncodeBase64Error = 40009;
public static $DecodeBase64Error = 40010;
public static $GenReturnXmlError = 40011;
public static $errCode=array(
'0' => '處理成功',
'40001' => '校驗簽名失敗',
'40002' => '解析xml失敗',
'40003' => '計算簽名失敗',
'40004' => '不合法的AESKey',
'40005' => '校驗AppID失敗',
'40006' => 'AES加密失敗',
'40007' => 'AES解密失敗',
'40008' => '公衆平臺發送的xml不合法',
'40009' => 'Base64編碼失敗',
'40010' => 'Base64解碼失敗',
'40011' => '公衆帳號生成回包xml失敗'
);
public static function getErrText($err) {
if (isset(self::$errCode[$err])) {
return self::$errCode[$err];
}else {
return false;
};
}
}