Wechat.class.php 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209
  1. <?php
  2. /**
  3. * 微信公众平台PHP-SDK
  4. * @author dodgepudding@gmail.com
  5. * @link https://github.com/dodgepudding/wechat-php-sdk
  6. * @version 1.2
  7. * usage:
  8. * $options = array(
  9. * 'token'=>'tokenaccesskey', //填写你设定的key
  10. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  11. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  12. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx' //填写高级调用功能的密钥
  13. * );
  14. * $weObj = new Wechat($options);
  15. * $weObj->valid();
  16. * $type = $weObj->getRev()->getRevType();
  17. * switch($type) {
  18. * case Wechat::MSGTYPE_TEXT:
  19. * $weObj->text("hello, I'm wechat")->reply();
  20. * exit;
  21. * break;
  22. * case Wechat::MSGTYPE_EVENT:
  23. * ....
  24. * break;
  25. * case Wechat::MSGTYPE_IMAGE:
  26. * ...
  27. * break;
  28. * default:
  29. * $weObj->text("help info")->reply();
  30. * }
  31. *
  32. * //获取菜单操作:
  33. * $menu = $weObj->getMenu();
  34. * //设置菜单
  35. * $newmenu = array(
  36. * "button"=>
  37. * array(
  38. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  39. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  40. * )
  41. * );
  42. * $result = $weObj->createMenu($newmenu);
  43. */
  44. class Wechat
  45. {
  46. const MSGTYPE_TEXT = 'text';
  47. const MSGTYPE_IMAGE = 'image';
  48. const MSGTYPE_LOCATION = 'location';
  49. const MSGTYPE_LINK = 'link';
  50. const MSGTYPE_EVENT = 'event';
  51. const MSGTYPE_MUSIC = 'music';
  52. const MSGTYPE_NEWS = 'news';
  53. const MSGTYPE_VOICE = 'voice';
  54. const MSGTYPE_VIDEO = 'video';
  55. const EVENT_SUBSCRIBE = 'subscribe'; //订阅
  56. const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消订阅
  57. const EVENT_SCAN = 'SCAN'; //扫描带参数二维码
  58. const EVENT_LOCATION = 'LOCATION'; //上报地理位置
  59. const EVENT_MENU_VIEW = 'VIEW'; //菜单 - 点击菜单跳转链接
  60. const EVENT_MENU_CLICK = 'CLICK'; //菜单 - 点击菜单拉取消息
  61. const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜单 - 扫码推事件(客户端跳URL)
  62. const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜单 - 扫码推事件(客户端不跳URL)
  63. const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜单 - 弹出系统拍照发图
  64. const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜单 - 弹出拍照或者相册发图
  65. const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜单 - 弹出微信相册发图器
  66. const EVENT_MENU_LOCATION = 'location_select'; //菜单 - 弹出地理位置选择器
  67. const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //发送结果 - 高级群发完成
  68. const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//发送结果 - 模板消息发送结果
  69. const EVENT_KF_SEESION_CREATE = 'kfcreatesession'; //多客服 - 接入会话
  70. const EVENT_KF_SEESION_CLOSE = 'kfclosesession'; //多客服 - 关闭会话
  71. const EVENT_KF_SEESION_SWITCH = 'kfswitchsession'; //多客服 - 转接会话
  72. const EVENT_CARD_PASS = 'card_pass_check'; //卡券 - 审核通过
  73. const EVENT_CARD_NOTPASS = 'card_not_pass_check'; //卡券 - 审核未通过
  74. const EVENT_CARD_USER_GET = 'user_get_card'; //卡券 - 用户领取卡券
  75. const EVENT_CARD_USER_DEL = 'user_del_card'; //卡券 - 用户删除卡券
  76. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  77. const AUTH_URL = '/token?grant_type=client_credential&';
  78. const MENU_CREATE_URL = '/menu/create?';
  79. const MENU_GET_URL = '/menu/get?';
  80. const MENU_DELETE_URL = '/menu/delete?';
  81. const GET_TICKET_URL = '/ticket/getticket?';
  82. const CALLBACKSERVER_GET_URL = '/getcallbackip?';
  83. const QRCODE_CREATE_URL='/qrcode/create?';
  84. const QR_SCENE = 0;
  85. const QR_LIMIT_SCENE = 1;
  86. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  87. const SHORT_URL='/shorturl?';
  88. const USER_GET_URL='/user/get?';
  89. const USER_INFO_URL='/user/info?';
  90. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  91. const GROUP_GET_URL='/groups/get?';
  92. const USER_GROUP_URL='/groups/getid?';
  93. const GROUP_CREATE_URL='/groups/create?';
  94. const GROUP_UPDATE_URL='/groups/update?';
  95. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  96. const CUSTOM_SEND_URL='/message/custom/send?';
  97. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  98. const MASS_SEND_URL = '/message/mass/send?';
  99. const TEMPLATE_SET_INDUSTRY_URL = '/message/template/api_set_industry?';
  100. const TEMPLATE_ADD_TPL_URL = '/message/template/api_add_template?';
  101. const TEMPLATE_SEND_URL = '/message/template/send?';
  102. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  103. const MASS_DELETE_URL = '/message/mass/delete?';
  104. const MASS_PREVIEW_URL = '/message/mass/preview?';
  105. const MASS_QUERY_URL = '/message/mass/get?';
  106. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  107. const MEDIA_UPLOAD = '/media/upload?';
  108. const MEDIA_GET_URL = '/media/get?';
  109. const MEDIA_VIDEO_UPLOAD = '/media/uploadvideo?';
  110. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  111. const OAUTH_AUTHORIZE_URL = '/authorize?';
  112. const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com'; //以下API接口URL需要使用此前缀
  113. const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
  114. const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
  115. const OAUTH_USERINFO_URL = '/sns/userinfo?';
  116. const OAUTH_AUTH_URL = '/sns/auth?';
  117. ///多客服相关地址
  118. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  119. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  120. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getonlinekflist?';
  121. const CUSTOM_SEESSION_CREATE = '/customservice/kfsession/create?';
  122. const CUSTOM_SEESSION_CLOSE = '/customservice/kfsession/close?';
  123. const CUSTOM_SEESSION_SWITCH = '/customservice/kfsession/switch?';
  124. const CUSTOM_SEESSION_GET = '/customservice/kfsession/getsession?';
  125. const CUSTOM_SEESSION_GET_LIST = '/customservice/kfsession/getsessionlist?';
  126. const CUSTOM_SEESSION_GET_WAIT = '/customservice/kfsession/getwaitcase?';
  127. const CS_KF_ACCOUNT_ADD_URL = '/customservice/kfaccount/add?';
  128. const CS_KF_ACCOUNT_UPDATE_URL = '/customservice/kfaccount/update?';
  129. const CS_KF_ACCOUNT_DEL_URL = '/customservice/kfaccount/del?';
  130. const CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL = '/customservice/kfaccount/uploadheadimg?';
  131. ///卡券相关地址
  132. const CARD_CREATE = '/card/create?';
  133. const CARD_DELETE = '/card/delete?';
  134. const CARD_UPDATE = '/card/update?';
  135. const CARD_GET = '/card/get?';
  136. const CARD_BATCHGET = '/card/batchget?';
  137. const CARD_MODIFY_STOCK = '/card/modifystock?';
  138. const CARD_LOCATION_BATCHADD = '/card/location/batchadd?';
  139. const CARD_LOCATION_BATCHGET = '/card/location/batchget?';
  140. const CARD_GETCOLORS = '/card/getcolors?';
  141. const CARD_QRCODE_CREATE = '/card/qrcode/create?';
  142. const CARD_CODE_CONSUME = '/card/code/consume?';
  143. const CARD_CODE_DECRYPT = '/card/code/decrypt?';
  144. const CARD_CODE_GET = '/card/code/get?';
  145. const CARD_CODE_UPDATE = '/card/code/update?';
  146. const CARD_CODE_UNAVAILABLE = '/card/code/unavailable?';
  147. const CARD_TESTWHILELIST_SET = '/card/testwhitelist/set?';
  148. const CARD_MEMBERCARD_ACTIVATE = '/card/membercard/activate?'; //激活会员卡
  149. const CARD_MEMBERCARD_UPDATEUSER = '/card/membercard/updateuser?'; //更新会员卡
  150. const CARD_MOVIETICKET_UPDATEUSER = '/card/movieticket/updateuser?'; //更新电影票(未加方法)
  151. const CARD_BOARDINGPASS_CHECKIN = '/card/boardingpass/checkin?'; //飞机票-在线选座(未加方法)
  152. const CARD_LUCKYMONEY_UPDATE = '/card/luckymoney/updateuserbalance?'; //更新红包金额
  153. const SEMANTIC_API_URL= '/semantic/semproxy/search?';
  154. private $token;
  155. private $encodingAesKey;
  156. private $encrypt_type;
  157. private $appid;
  158. private $appsecret;
  159. private $access_token;
  160. private $jsapi_ticket;
  161. private $user_token;
  162. private $partnerid;
  163. private $partnerkey;
  164. private $paysignkey;
  165. private $postxml;
  166. private $_msg;
  167. private $_funcflag = false;
  168. private $_receive;
  169. private $_text_filter = true;
  170. public $debug = false;
  171. public $errCode = 40001;
  172. public $errMsg = "no access";
  173. private $_logcallback;
  174. public function __construct($options)
  175. {
  176. $this->token = isset($options['token'])?$options['token']:'';
  177. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  178. $this->appid = isset($options['appid'])?$options['appid']:'';
  179. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  180. $this->debug = isset($options['debug'])?$options['debug']:false;
  181. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  182. }
  183. /**
  184. * For weixin server validation
  185. */
  186. private function checkSignature($str='')
  187. {
  188. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  189. $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密验证则用加密验证段
  190. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  191. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  192. $token = $this->token;
  193. $tmpArr = array($token, $timestamp, $nonce,$str);
  194. sort($tmpArr, SORT_STRING);
  195. $tmpStr = implode( $tmpArr );
  196. $tmpStr = sha1( $tmpStr );
  197. if( $tmpStr == $signature ){
  198. return true;
  199. }else{
  200. return false;
  201. }
  202. }
  203. /**
  204. * For weixin server validation
  205. * @param bool $return 是否返回
  206. */
  207. public function valid($return=false)
  208. {
  209. $encryptStr="";
  210. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  211. $postStr = file_get_contents("php://input");
  212. $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  213. $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"]: '';
  214. if ($this->encrypt_type == 'aes') { //aes加密
  215. $this->log($postStr);
  216. $encryptStr = $array['Encrypt'];
  217. $pc = new Prpcrypt($this->encodingAesKey);
  218. $array = $pc->decrypt($encryptStr,$this->appid);
  219. if (!isset($array[0]) || ($array[0] != 0)) {
  220. if (!$return) {
  221. die('decrypt error!');
  222. } else {
  223. return false;
  224. }
  225. }
  226. $this->postxml = $array[1];
  227. if (!$this->appid)
  228. $this->appid = $array[2];//为了没有appid的订阅号。
  229. } else {
  230. $this->postxml = $postStr;
  231. }
  232. } elseif (isset($_GET["echostr"])) {
  233. $echoStr = $_GET["echostr"];
  234. if ($return) {
  235. if ($this->checkSignature())
  236. return $echoStr;
  237. else
  238. return false;
  239. } else {
  240. if ($this->checkSignature())
  241. die($echoStr);
  242. else
  243. die('no access');
  244. }
  245. }
  246. if (!$this->checkSignature($encryptStr)) {
  247. if ($return)
  248. return false;
  249. else
  250. die('no access');
  251. }
  252. return true;
  253. }
  254. /**
  255. * 设置发送消息
  256. * @param array $msg 消息数组
  257. * @param bool $append 是否在原消息数组追加
  258. */
  259. public function Message($msg = '',$append = false){
  260. if (is_null($msg)) {
  261. $this->_msg =array();
  262. }elseif (is_array($msg)) {
  263. if ($append)
  264. $this->_msg = array_merge($this->_msg,$msg);
  265. else
  266. $this->_msg = $msg;
  267. return $this->_msg;
  268. } else {
  269. return $this->_msg;
  270. }
  271. }
  272. /**
  273. * 设置消息的星标标志,官方已取消对此功能的支持
  274. */
  275. public function setFuncFlag($flag) {
  276. $this->_funcflag = $flag;
  277. return $this;
  278. }
  279. private function log($log){
  280. if ($this->debug ) {
  281. if (function_exists($this->_logcallback)) {
  282. if (is_array($log)) $log = print_r($log,true);
  283. return call_user_func($this->_logcallback,$log);
  284. }elseif (class_exists('Log')) {
  285. Log::write('wechat:'.$log, Log::DEBUG);
  286. }
  287. }
  288. return false;
  289. }
  290. /**
  291. * 获取微信服务器发来的信息
  292. */
  293. public function getRev()
  294. {
  295. if ($this->_receive) return $this;
  296. $postStr = !empty($this->postxml)?$this->postxml:file_get_contents("php://input");
  297. //兼顾使用明文又不想调用valid()方法的情况
  298. $this->log($postStr);
  299. if (!empty($postStr)) {
  300. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  301. }
  302. return $this;
  303. }
  304. /**
  305. * 获取微信服务器发来的信息
  306. */
  307. public function getRevData()
  308. {
  309. return $this->_receive;
  310. }
  311. /**
  312. * 获取消息发送者
  313. */
  314. public function getRevFrom() {
  315. if (isset($this->_receive['FromUserName']))
  316. return $this->_receive['FromUserName'];
  317. else
  318. return false;
  319. }
  320. /**
  321. * 获取消息接受者
  322. */
  323. public function getRevTo() {
  324. if (isset($this->_receive['ToUserName']))
  325. return $this->_receive['ToUserName'];
  326. else
  327. return false;
  328. }
  329. /**
  330. * 获取接收消息的类型
  331. */
  332. public function getRevType() {
  333. if (isset($this->_receive['MsgType']))
  334. return $this->_receive['MsgType'];
  335. else
  336. return false;
  337. }
  338. /**
  339. * 获取消息ID
  340. */
  341. public function getRevID() {
  342. if (isset($this->_receive['MsgId']))
  343. return $this->_receive['MsgId'];
  344. else
  345. return false;
  346. }
  347. /**
  348. * 获取消息发送时间
  349. */
  350. public function getRevCtime() {
  351. if (isset($this->_receive['CreateTime']))
  352. return $this->_receive['CreateTime'];
  353. else
  354. return false;
  355. }
  356. /**
  357. * 获取接收消息内容正文
  358. */
  359. public function getRevContent(){
  360. if (isset($this->_receive['Content']))
  361. return $this->_receive['Content'];
  362. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  363. return $this->_receive['Recognition'];
  364. else
  365. return false;
  366. }
  367. /**
  368. * 获取接收消息图片
  369. */
  370. public function getRevPic(){
  371. if (isset($this->_receive['PicUrl']))
  372. return array(
  373. 'mediaid'=>$this->_receive['MediaId'],
  374. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  375. );
  376. else
  377. return false;
  378. }
  379. /**
  380. * 获取接收消息链接
  381. */
  382. public function getRevLink(){
  383. if (isset($this->_receive['Url'])){
  384. return array(
  385. 'url'=>$this->_receive['Url'],
  386. 'title'=>$this->_receive['Title'],
  387. 'description'=>$this->_receive['Description']
  388. );
  389. } else
  390. return false;
  391. }
  392. /**
  393. * 获取接收地理位置
  394. */
  395. public function getRevGeo(){
  396. if (isset($this->_receive['Location_X'])){
  397. return array(
  398. 'x'=>$this->_receive['Location_X'],
  399. 'y'=>$this->_receive['Location_Y'],
  400. 'scale'=>$this->_receive['Scale'],
  401. 'label'=>$this->_receive['Label']
  402. );
  403. } else
  404. return false;
  405. }
  406. /**
  407. * 获取上报地理位置事件
  408. */
  409. public function getRevEventGeo(){
  410. if (isset($this->_receive['Latitude'])){
  411. return array(
  412. 'x'=>$this->_receive['Latitude'],
  413. 'y'=>$this->_receive['Longitude'],
  414. 'precision'=>$this->_receive['Precision'],
  415. );
  416. } else
  417. return false;
  418. }
  419. /**
  420. * 获取接收事件推送
  421. */
  422. public function getRevEvent(){
  423. if (isset($this->_receive['Event'])){
  424. $array['event'] = $this->_receive['Event'];
  425. }
  426. if (isset($this->_receive['EventKey'])){
  427. $array['key'] = $this->_receive['EventKey'];
  428. }
  429. if (isset($array) && count($array) > 0) {
  430. return $array;
  431. } else {
  432. return false;
  433. }
  434. }
  435. /**
  436. * 获取自定义菜单的扫码推事件信息
  437. *
  438. * 事件类型为以下两种时则调用此方法有效
  439. * Event 事件类型,scancode_push
  440. * Event 事件类型,scancode_waitmsg
  441. *
  442. * @return: array | false
  443. * array (
  444. * 'ScanType'=>'qrcode',
  445. * 'ScanResult'=>'123123'
  446. * )
  447. */
  448. public function getRevScanInfo(){
  449. if (isset($this->_receive['ScanCodeInfo'])){
  450. if (!is_array($this->_receive['SendPicsInfo'])) {
  451. $array=(array)$this->_receive['ScanCodeInfo'];
  452. $this->_receive['ScanCodeInfo']=$array;
  453. }else {
  454. $array=$this->_receive['ScanCodeInfo'];
  455. }
  456. }
  457. if (isset($array) && count($array) > 0) {
  458. return $array;
  459. } else {
  460. return false;
  461. }
  462. }
  463. /**
  464. * 获取自定义菜单的图片发送事件信息
  465. *
  466. * 事件类型为以下三种时则调用此方法有效
  467. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  468. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  469. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  470. *
  471. * @return: array | false
  472. * array (
  473. * 'Count' => '2',
  474. * 'PicList' =>array (
  475. * 'item' =>array (
  476. * 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
  477. * 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
  478. * ),
  479. * ),
  480. * )
  481. *
  482. */
  483. public function getRevSendPicsInfo(){
  484. if (isset($this->_receive['SendPicsInfo'])){
  485. if (!is_array($this->_receive['SendPicsInfo'])) {
  486. $array=(array)$this->_receive['SendPicsInfo'];
  487. if (isset($array['PicList'])){
  488. $array['PicList']=(array)$array['PicList'];
  489. $item=$array['PicList']['item'];
  490. $array['PicList']['item']=array();
  491. foreach ( $item as $key => $value ){
  492. $array['PicList']['item'][$key]=(array)$value;
  493. }
  494. }
  495. $this->_receive['SendPicsInfo']=$array;
  496. } else {
  497. $array=$this->_receive['SendPicsInfo'];
  498. }
  499. }
  500. if (isset($array) && count($array) > 0) {
  501. return $array;
  502. } else {
  503. return false;
  504. }
  505. }
  506. /**
  507. * 获取自定义菜单的地理位置选择器事件推送
  508. *
  509. * 事件类型为以下时则可以调用此方法有效
  510. * Event 事件类型,location_select 弹出地理位置选择器的事件推送
  511. *
  512. * @return: array | false
  513. * array (
  514. * 'Location_X' => '33.731655000061',
  515. * 'Location_Y' => '113.29955200008047',
  516. * 'Scale' => '16',
  517. * 'Label' => '某某市某某区某某路',
  518. * 'Poiname' => '',
  519. * )
  520. *
  521. */
  522. public function getRevSendGeoInfo(){
  523. if (isset($this->_receive['SendLocationInfo'])){
  524. if (!is_array($this->_receive['SendLocationInfo'])) {
  525. $array=(array)$this->_receive['SendLocationInfo'];
  526. if (empty($array['Poiname'])) {
  527. $array['Poiname']="";
  528. }
  529. if (empty($array['Label'])) {
  530. $array['Label']="";
  531. }
  532. $this->_receive['SendLocationInfo']=$array;
  533. } else {
  534. $array=$this->_receive['SendLocationInfo'];
  535. }
  536. }
  537. if (isset($array) && count($array) > 0) {
  538. return $array;
  539. } else {
  540. return false;
  541. }
  542. }
  543. /**
  544. * 获取接收语音推送
  545. */
  546. public function getRevVoice(){
  547. if (isset($this->_receive['MediaId'])){
  548. return array(
  549. 'mediaid'=>$this->_receive['MediaId'],
  550. 'format'=>$this->_receive['Format'],
  551. );
  552. } else
  553. return false;
  554. }
  555. /**
  556. * 获取接收视频推送
  557. */
  558. public function getRevVideo(){
  559. if (isset($this->_receive['MediaId'])){
  560. return array(
  561. 'mediaid'=>$this->_receive['MediaId'],
  562. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  563. );
  564. } else
  565. return false;
  566. }
  567. /**
  568. * 获取接收TICKET
  569. */
  570. public function getRevTicket(){
  571. if (isset($this->_receive['Ticket'])){
  572. return $this->_receive['Ticket'];
  573. } else
  574. return false;
  575. }
  576. /**
  577. * 获取二维码的场景值
  578. */
  579. public function getRevSceneId (){
  580. if (isset($this->_receive['EventKey'])){
  581. return str_replace('qrscene_','',$this->_receive['EventKey']);
  582. } else{
  583. return false;
  584. }
  585. }
  586. /**
  587. * 获取主动推送的消息ID
  588. * 经过验证,这个和普通的消息MsgId不一样
  589. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH
  590. */
  591. public function getRevTplMsgID(){
  592. if (isset($this->_receive['MsgID'])){
  593. return $this->_receive['MsgID'];
  594. } else
  595. return false;
  596. }
  597. /**
  598. * 获取模板消息发送状态
  599. */
  600. public function getRevStatus(){
  601. if (isset($this->_receive['Status'])){
  602. return $this->_receive['Status'];
  603. } else
  604. return false;
  605. }
  606. /**
  607. * 获取群发或模板消息发送结果
  608. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH,即高级群发/模板消息
  609. */
  610. public function getRevResult(){
  611. if (isset($this->_receive['Status'])) //发送是否成功,具体的返回值请参考 高级群发/模板消息 的事件推送说明
  612. $array['Status'] = $this->_receive['Status'];
  613. if (isset($this->_receive['MsgID'])) //发送的消息id
  614. $array['MsgID'] = $this->_receive['MsgID'];
  615. //以下仅当群发消息时才会有的事件内容
  616. if (isset($this->_receive['TotalCount'])) //分组或openid列表内粉丝数量
  617. $array['TotalCount'] = $this->_receive['TotalCount'];
  618. if (isset($this->_receive['FilterCount'])) //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数
  619. $array['FilterCount'] = $this->_receive['FilterCount'];
  620. if (isset($this->_receive['SentCount'])) //发送成功的粉丝数
  621. $array['SentCount'] = $this->_receive['SentCount'];
  622. if (isset($this->_receive['ErrorCount'])) //发送失败的粉丝数
  623. $array['ErrorCount'] = $this->_receive['ErrorCount'];
  624. if (isset($array) && count($array) > 0) {
  625. return $array;
  626. } else {
  627. return false;
  628. }
  629. }
  630. /**
  631. * 获取多客服会话状态推送事件 - 接入会话
  632. * 当Event为 kfcreatesession 即接入会话
  633. * @return string | boolean 返回分配到的客服
  634. */
  635. public function getRevKFCreate(){
  636. if (isset($this->_receive['KfAccount'])){
  637. return $this->_receive['KfAccount'];
  638. } else
  639. return false;
  640. }
  641. /**
  642. * 获取多客服会话状态推送事件 - 关闭会话
  643. * 当Event为 kfclosesession 即关闭会话
  644. * @return string | boolean 返回分配到的客服
  645. */
  646. public function getRevKFClose(){
  647. if (isset($this->_receive['KfAccount'])){
  648. return $this->_receive['KfAccount'];
  649. } else
  650. return false;
  651. }
  652. /**
  653. * 获取多客服会话状态推送事件 - 转接会话
  654. * 当Event为 kfswitchsession 即转接会话
  655. * @return array | boolean 返回分配到的客服
  656. * {
  657. * 'FromKfAccount' => '', //原接入客服
  658. * 'ToKfAccount' => '' //转接到客服
  659. * }
  660. */
  661. public function getRevKFSwitch(){
  662. if (isset($this->_receive['FromKfAccount'])) //原接入客服
  663. $array['FromKfAccount'] = $this->_receive['FromKfAccount'];
  664. if (isset($this->_receive['ToKfAccount'])) //转接到客服
  665. $array['ToKfAccount'] = $this->_receive['ToKfAccount'];
  666. if (isset($array) && count($array) > 0) {
  667. return $array;
  668. } else {
  669. return false;
  670. }
  671. }
  672. /**
  673. * 获取卡券事件推送 - 卡卷审核是否通过
  674. * 当Event为 card_pass_check(审核通过) 或 card_not_pass_check(未通过)
  675. * @return string|boolean 返回卡券ID
  676. */
  677. public function getRevCardPass(){
  678. if (isset($this->_receive['CardId']))
  679. return $this->_receive['CardId'];
  680. else
  681. return false;
  682. }
  683. /**
  684. * 获取卡券事件推送 - 领取卡券
  685. * 当Event为 user_get_card(用户领取卡券)
  686. * @return array|boolean
  687. */
  688. public function getRevCardGet(){
  689. if (isset($this->_receive['CardId'])) //卡券 ID
  690. $array['CardId'] = $this->_receive['CardId'];
  691. if (isset($this->_receive['IsGiveByFriend'])) //是否为转赠,1 代表是,0 代表否。
  692. $array['IsGiveByFriend'] = $this->_receive['IsGiveByFriend'];
  693. if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列号。自定义 code 及非自定义 code的卡券被领取后都支持事件推送。
  694. $array['UserCardCode'] = $this->_receive['UserCardCode'];
  695. if (isset($array) && count($array) > 0) {
  696. return $array;
  697. } else {
  698. return false;
  699. }
  700. }
  701. /**
  702. * 获取卡券事件推送 - 删除卡券
  703. * 当Event为 user_del_card(用户删除卡券)
  704. * @return array|boolean
  705. */
  706. public function getRevCardDel(){
  707. if (isset($this->_receive['CardId'])) //卡券 ID
  708. $array['CardId'] = $this->_receive['CardId'];
  709. if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列号。自定义 code 及非自定义 code的卡券被领取后都支持事件推送。
  710. $array['UserCardCode'] = $this->_receive['UserCardCode'];
  711. if (isset($array) && count($array) > 0) {
  712. return $array;
  713. } else {
  714. return false;
  715. }
  716. }
  717. public static function xmlSafeStr($str)
  718. {
  719. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  720. }
  721. /**
  722. * 数据XML编码
  723. * @param mixed $data 数据
  724. * @return string
  725. */
  726. public static function data_to_xml($data) {
  727. $xml = '';
  728. foreach ($data as $key => $val) {
  729. is_numeric($key) && $key = "item id=\"$key\"";
  730. $xml .= "<$key>";
  731. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  732. list($key, ) = explode(' ', $key);
  733. $xml .= "</$key>";
  734. }
  735. return $xml;
  736. }
  737. /**
  738. * XML编码
  739. * @param mixed $data 数据
  740. * @param string $root 根节点名
  741. * @param string $item 数字索引的子节点名
  742. * @param string $attr 根节点属性
  743. * @param string $id 数字索引子节点key转换的属性名
  744. * @param string $encoding 数据编码
  745. * @return string
  746. */
  747. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  748. if(is_array($attr)){
  749. $_attr = array();
  750. foreach ($attr as $key => $value) {
  751. $_attr[] = "{$key}=\"{$value}\"";
  752. }
  753. $attr = implode(' ', $_attr);
  754. }
  755. $attr = trim($attr);
  756. $attr = empty($attr) ? '' : " {$attr}";
  757. $xml = "<{$root}{$attr}>";
  758. $xml .= self::data_to_xml($data, $item, $id);
  759. $xml .= "</{$root}>";
  760. return $xml;
  761. }
  762. /**
  763. * 过滤文字回复\r\n换行符
  764. * @param string $text
  765. * @return string|mixed
  766. */
  767. private function _auto_text_filter($text) {
  768. if (!$this->_text_filter) return $text;
  769. return str_replace("\r\n", "\n", $text);
  770. }
  771. /**
  772. * 设置回复消息
  773. * Example: $obj->text('hello')->reply();
  774. * @param string $text
  775. */
  776. public function text($text='')
  777. {
  778. $FuncFlag = $this->_funcflag ? 1 : 0;
  779. $msg = array(
  780. 'ToUserName' => $this->getRevFrom(),
  781. 'FromUserName'=>$this->getRevTo(),
  782. 'MsgType'=>self::MSGTYPE_TEXT,
  783. 'Content'=>$this->_auto_text_filter($text),
  784. 'CreateTime'=>time(),
  785. 'FuncFlag'=>$FuncFlag
  786. );
  787. $this->Message($msg);
  788. return $this;
  789. }
  790. /**
  791. * 设置回复消息
  792. * Example: $obj->image('media_id')->reply();
  793. * @param string $mediaid
  794. */
  795. public function image($mediaid='')
  796. {
  797. $FuncFlag = $this->_funcflag ? 1 : 0;
  798. $msg = array(
  799. 'ToUserName' => $this->getRevFrom(),
  800. 'FromUserName'=>$this->getRevTo(),
  801. 'MsgType'=>self::MSGTYPE_IMAGE,
  802. 'Image'=>array('MediaId'=>$mediaid),
  803. 'CreateTime'=>time(),
  804. 'FuncFlag'=>$FuncFlag
  805. );
  806. $this->Message($msg);
  807. return $this;
  808. }
  809. /**
  810. * 设置回复消息
  811. * Example: $obj->voice('media_id')->reply();
  812. * @param string $mediaid
  813. */
  814. public function voice($mediaid='')
  815. {
  816. $FuncFlag = $this->_funcflag ? 1 : 0;
  817. $msg = array(
  818. 'ToUserName' => $this->getRevFrom(),
  819. 'FromUserName'=>$this->getRevTo(),
  820. 'MsgType'=>self::MSGTYPE_VOICE,
  821. 'Voice'=>array('MediaId'=>$mediaid),
  822. 'CreateTime'=>time(),
  823. 'FuncFlag'=>$FuncFlag
  824. );
  825. $this->Message($msg);
  826. return $this;
  827. }
  828. /**
  829. * 设置回复消息
  830. * Example: $obj->video('media_id','title','description')->reply();
  831. * @param string $mediaid
  832. */
  833. public function video($mediaid='',$title='',$description='')
  834. {
  835. $FuncFlag = $this->_funcflag ? 1 : 0;
  836. $msg = array(
  837. 'ToUserName' => $this->getRevFrom(),
  838. 'FromUserName'=>$this->getRevTo(),
  839. 'MsgType'=>self::MSGTYPE_VIDEO,
  840. 'Video'=>array(
  841. 'MediaId'=>$mediaid,
  842. 'Title'=>$title,
  843. 'Description'=>$description
  844. ),
  845. 'CreateTime'=>time(),
  846. 'FuncFlag'=>$FuncFlag
  847. );
  848. $this->Message($msg);
  849. return $this;
  850. }
  851. /**
  852. * 设置回复音乐
  853. * @param string $title
  854. * @param string $desc
  855. * @param string $musicurl
  856. * @param string $hgmusicurl
  857. * @param string $thumbmediaid 音乐图片缩略图的媒体id,非必须
  858. */
  859. public function music($title,$desc,$musicurl,$hgmusicurl='',$thumbmediaid='') {
  860. $FuncFlag = $this->_funcflag ? 1 : 0;
  861. $msg = array(
  862. 'ToUserName' => $this->getRevFrom(),
  863. 'FromUserName'=>$this->getRevTo(),
  864. 'CreateTime'=>time(),
  865. 'MsgType'=>self::MSGTYPE_MUSIC,
  866. 'Music'=>array(
  867. 'Title'=>$title,
  868. 'Description'=>$desc,
  869. 'MusicUrl'=>$musicurl,
  870. 'HQMusicUrl'=>$hgmusicurl
  871. ),
  872. 'FuncFlag'=>$FuncFlag
  873. );
  874. if ($thumbmediaid) {
  875. $msg['Music']['ThumbMediaId'] = $thumbmediaid;
  876. }
  877. $this->Message($msg);
  878. return $this;
  879. }
  880. /**
  881. * 设置回复图文
  882. * @param array $newsData
  883. * 数组结构:
  884. * array(
  885. * "0"=>array(
  886. * 'Title'=>'msg title',
  887. * 'Description'=>'summary text',
  888. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  889. * 'Url'=>'http://www.domain.com/1.html'
  890. * ),
  891. * "1"=>....
  892. * )
  893. */
  894. public function news($newsData=array())
  895. {
  896. $FuncFlag = $this->_funcflag ? 1 : 0;
  897. $count = count($newsData);
  898. $msg = array(
  899. 'ToUserName' => $this->getRevFrom(),
  900. 'FromUserName'=>$this->getRevTo(),
  901. 'MsgType'=>self::MSGTYPE_NEWS,
  902. 'CreateTime'=>time(),
  903. 'ArticleCount'=>$count,
  904. 'Articles'=>$newsData,
  905. 'FuncFlag'=>$FuncFlag
  906. );
  907. $this->Message($msg);
  908. return $this;
  909. }
  910. /**
  911. *
  912. * 回复微信服务器, 此函数支持链式操作
  913. * Example: $this->text('msg tips')->reply();
  914. * @param string $msg 要发送的信息, 默认取$this->_msg
  915. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  916. */
  917. public function reply($msg=array(),$return = false)
  918. {
  919. if (empty($msg)) {
  920. if (empty($this->_msg)) //防止不先设置回复内容,直接调用reply方法导致异常
  921. return false;
  922. $msg = $this->_msg;
  923. }
  924. $xmldata= $this->xml_encode($msg);
  925. $this->log($xmldata);
  926. if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式
  927. $pc = new Prpcrypt($this->encodingAesKey);
  928. $array = $pc->encrypt($xmldata, $this->appid);
  929. $ret = $array[0];
  930. if ($ret != 0) {
  931. $this->log('encrypt err!');
  932. return false;
  933. }
  934. $timestamp = time();
  935. $nonce = rand(77,999)*rand(605,888)*rand(11,99);
  936. $encrypt = $array[1];
  937. $tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
  938. sort($tmpArr, SORT_STRING);
  939. $signature = implode($tmpArr);
  940. $signature = sha1($signature);
  941. $xmldata = $this->generate($encrypt, $signature, $timestamp, $nonce);
  942. $this->log($xmldata);
  943. }
  944. if ($return)
  945. return $xmldata;
  946. else
  947. echo $xmldata;
  948. }
  949. /**
  950. * xml格式加密,仅请求为加密方式时再用
  951. */
  952. private function generate($encrypt, $signature, $timestamp, $nonce)
  953. {
  954. //格式化加密信息
  955. $format = "<xml>
  956. <Encrypt><![CDATA[%s]]></Encrypt>
  957. <MsgSignature><![CDATA[%s]]></MsgSignature>
  958. <TimeStamp>%s</TimeStamp>
  959. <Nonce><![CDATA[%s]]></Nonce>
  960. </xml>";
  961. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  962. }
  963. /**
  964. * GET 请求
  965. * @param string $url
  966. */
  967. private function http_get($url){
  968. $oCurl = curl_init();
  969. if(stripos($url,"https://")!==FALSE){
  970. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  971. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  972. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  973. }
  974. curl_setopt($oCurl, CURLOPT_URL, $url);
  975. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  976. $sContent = curl_exec($oCurl);
  977. $aStatus = curl_getinfo($oCurl);
  978. curl_close($oCurl);
  979. if(intval($aStatus["http_code"])==200){
  980. return $sContent;
  981. }else{
  982. return false;
  983. }
  984. }
  985. /**
  986. * POST 请求
  987. * @param string $url
  988. * @param array $param
  989. * @param boolean $post_file 是否文件上传
  990. * @return string content
  991. */
  992. private function http_post($url,$param,$post_file=false){
  993. $oCurl = curl_init();
  994. if(stripos($url,"https://")!==FALSE){
  995. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  996. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  997. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  998. }
  999. if (is_string($param) || $post_file) {
  1000. $strPOST = $param;
  1001. } else {
  1002. $aPOST = array();
  1003. foreach($param as $key=>$val){
  1004. $aPOST[] = $key."=".urlencode($val);
  1005. }
  1006. $strPOST = join("&", $aPOST);
  1007. }
  1008. curl_setopt($oCurl, CURLOPT_URL, $url);
  1009. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  1010. curl_setopt($oCurl, CURLOPT_POST,true);
  1011. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  1012. $sContent = curl_exec($oCurl);
  1013. $aStatus = curl_getinfo($oCurl);
  1014. curl_close($oCurl);
  1015. if(intval($aStatus["http_code"])==200){
  1016. return $sContent;
  1017. }else{
  1018. return false;
  1019. }
  1020. }
  1021. /**
  1022. * 通用auth验证方法,获取access_token
  1023. * @param string $appid
  1024. * @param string $appsecret
  1025. * @param string $token 手动指定access_token,非必要情况不建议用
  1026. */
  1027. public function checkAuth($appid='',$appsecret='',$token=''){
  1028. if (!$appid || !$appsecret) {
  1029. $appid = $this->appid;
  1030. $appsecret = $this->appsecret;
  1031. }
  1032. $authname = 'wechat_access_token'.$appid;
  1033. if ($token) { //手动指定token,优先使用
  1034. $this->access_token=$token;
  1035. return $this->access_token;
  1036. }
  1037. if ($rs = S($authname)) {
  1038. $this->access_token = $rs;
  1039. return $rs;
  1040. }
  1041. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  1042. if ($result)
  1043. {
  1044. $json = json_decode($result,true);
  1045. if (!$json || isset($json['errcode'])) {
  1046. $this->errCode = $json['errcode'];
  1047. $this->errMsg = $json['errmsg'];
  1048. return false;
  1049. }
  1050. $this->access_token = $json['access_token'];
  1051. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1052. S($authname,$this->access_token,$expire);
  1053. return $this->access_token;
  1054. }
  1055. return false;
  1056. }
  1057. /**
  1058. * 删除验证数据
  1059. * @param string $appid
  1060. */
  1061. public function resetAuth($appid=''){
  1062. if (!$appid) $appid = $this->appid;
  1063. $this->access_token = '';
  1064. $authname = 'wechat_access_token'.$appid;
  1065. S($authname,null);
  1066. return true;
  1067. }
  1068. /**
  1069. * 删除JSAPI授权TICKET
  1070. * @param string $appid 用于多个appid时使用
  1071. */
  1072. public function resetJsTicket($appid=''){
  1073. if (!$appid) $appid = $this->appid;
  1074. $this->jsapi_ticket = '';
  1075. $authname = 'wechat_jsapi_ticket'.$appid;
  1076. S($authname,null);
  1077. return true;
  1078. }
  1079. /**
  1080. * 获取JSAPI授权TICKET
  1081. * @param string $appid 用于多个appid时使用,可空
  1082. * @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
  1083. */
  1084. public function getJsTicket($appid='',$jsapi_ticket=''){
  1085. if (!$this->access_token && !$this->checkAuth()) return false;
  1086. if ($jsapi_ticket) { //手动指定token,优先使用
  1087. $this->jsapi_ticket = $jsapi_ticket;
  1088. return $this->access_token;
  1089. }
  1090. $authname = 'wechat_jsapi_ticket'.$appid;
  1091. if ($rs = S($authname)) {
  1092. $this->jsapi_ticket = $rs;
  1093. return $rs;
  1094. }
  1095. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=jsapi');
  1096. if ($result)
  1097. {
  1098. $json = json_decode($result,true);
  1099. if (!$json || !empty($json['errcode'])) {
  1100. $this->errCode = $json['errcode'];
  1101. $this->errMsg = $json['errmsg'];
  1102. return false;
  1103. }
  1104. $this->jsapi_ticket = $json['ticket'];
  1105. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1106. S($authname,$this->access_token,$expire);
  1107. return $this->jsapi_ticket;
  1108. }
  1109. return false;
  1110. }
  1111. /**
  1112. * 获取JsApi使用签名
  1113. * @param string $url 网页的URL,不包含#及其后面部分
  1114. * @param string $timeStamp 当前时间戳(需与JS输出的一致)
  1115. * @param string $nonceStr 随机串(需与JS输出的一致)
  1116. * @param string $appid 用于多个appid时使用,可空
  1117. * @return string 返回签名字串
  1118. */
  1119. public function getJsSign($url, $timeStamp, $nonceStr, $appid=''){
  1120. if (!$this->jsapi_ticket && !$this->getJsTicket($appid)) return false;
  1121. $ret = strpos($url,'#');
  1122. if ($ret)
  1123. $url = substr($url,0,$ret);
  1124. $url = trim($url);
  1125. if (empty($url))
  1126. return false;
  1127. $arrdata = array("timestamp" => $timeStamp, "noncestr" => $nonceStr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
  1128. return $this->getSignature($arrdata);
  1129. }
  1130. /**
  1131. * 微信api不支持中文转义的json结构
  1132. * @param array $arr
  1133. */
  1134. static function json_encode($arr) {
  1135. $parts = array ();
  1136. $is_list = false;
  1137. //Find out if the given array is a numerical array
  1138. $keys = array_keys ( $arr );
  1139. $max_length = count ( $arr ) - 1;
  1140. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  1141. $is_list = true;
  1142. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  1143. if ($i != $keys [$i]) { //A key fails at position check.
  1144. $is_list = false; //It is an associative array.
  1145. break;
  1146. }
  1147. }
  1148. }
  1149. foreach ( $arr as $key => $value ) {
  1150. if (is_array ( $value )) { //Custom handling for arrays
  1151. if ($is_list)
  1152. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  1153. else
  1154. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  1155. } else {
  1156. $str = '';
  1157. if (! $is_list)
  1158. $str = '"' . $key . '":';
  1159. //Custom handling for multiple data types
  1160. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  1161. $str .= $value; //Numbers
  1162. elseif ($value === false)
  1163. $str .= 'false'; //The booleans
  1164. elseif ($value === true)
  1165. $str .= 'true';
  1166. else
  1167. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  1168. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  1169. $parts [] = $str;
  1170. }
  1171. }
  1172. $json = implode ( ',', $parts );
  1173. if ($is_list)
  1174. return '[' . $json . ']'; //Return numerical JSON
  1175. return '{' . $json . '}'; //Return associative JSON
  1176. }
  1177. /**
  1178. * 获取签名
  1179. * @param array $arrdata 签名数组
  1180. * @param string $method 签名方法
  1181. * @return boolean|string 签名值
  1182. */
  1183. public function getSignature($arrdata,$method="sha1") {
  1184. if (!function_exists($method)) return false;
  1185. ksort($arrdata);
  1186. $paramstring = "";
  1187. foreach($arrdata as $key => $value)
  1188. {
  1189. if(strlen($paramstring) == 0)
  1190. $paramstring .= $key . "=" . $value;
  1191. else
  1192. $paramstring .= "&" . $key . "=" . $value;
  1193. }
  1194. $paySign = $method($paramstring);
  1195. return $paySign;
  1196. }
  1197. /**
  1198. * 获取微信服务器IP地址列表
  1199. * @return array('127.0.0.1','127.0.0.1')
  1200. */
  1201. public function getServerIp(){
  1202. if (!$this->access_token && !$this->checkAuth()) return false;
  1203. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1204. if ($result)
  1205. {
  1206. $json = json_decode($result,true);
  1207. if (!$json || isset($json['errcode'])) {
  1208. $this->errCode = $json['errcode'];
  1209. $this->errMsg = $json['errmsg'];
  1210. return false;
  1211. }
  1212. return $json['ip_list'];
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * 创建菜单(认证后的订阅号可用)
  1218. * @param array $data 菜单数组数据
  1219. * example:
  1220. * array (
  1221. * 'button' => array (
  1222. * 0 => array (
  1223. * 'name' => '扫码',
  1224. * 'sub_button' => array (
  1225. * 0 => array (
  1226. * 'type' => 'scancode_waitmsg',
  1227. * 'name' => '扫码带提示',
  1228. * 'key' => 'rselfmenu_0_0',
  1229. * ),
  1230. * 1 => array (
  1231. * 'type' => 'scancode_push',
  1232. * 'name' => '扫码推事件',
  1233. * 'key' => 'rselfmenu_0_1',
  1234. * ),
  1235. * ),
  1236. * ),
  1237. * 1 => array (
  1238. * 'name' => '发图',
  1239. * 'sub_button' => array (
  1240. * 0 => array (
  1241. * 'type' => 'pic_sysphoto',
  1242. * 'name' => '系统拍照发图',
  1243. * 'key' => 'rselfmenu_1_0',
  1244. * ),
  1245. * 1 => array (
  1246. * 'type' => 'pic_photo_or_album',
  1247. * 'name' => '拍照或者相册发图',
  1248. * 'key' => 'rselfmenu_1_1',
  1249. * )
  1250. * ),
  1251. * ),
  1252. * 2 => array (
  1253. * 'type' => 'location_select',
  1254. * 'name' => '发送位置',
  1255. * 'key' => 'rselfmenu_2_0'
  1256. * ),
  1257. * ),
  1258. * )
  1259. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  1260. * 1、click:点击推事件
  1261. * 2、view:跳转URL
  1262. * 3、scancode_push:扫码推事件
  1263. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1264. * 5、pic_sysphoto:弹出系统拍照发图
  1265. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1266. * 7、pic_weixin:弹出微信相册发图器
  1267. * 8、location_select:弹出地理位置选择器
  1268. */
  1269. public function createMenu($data){
  1270. if (!$this->access_token && !$this->checkAuth()) return false;
  1271. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1272. if ($result)
  1273. {
  1274. $json = json_decode($result,true);
  1275. if (!$json || !empty($json['errcode'])) {
  1276. $this->errCode = $json['errcode'];
  1277. $this->errMsg = $json['errmsg'];
  1278. return false;
  1279. }
  1280. return true;
  1281. }
  1282. return false;
  1283. }
  1284. /**
  1285. * 获取菜单(认证后的订阅号可用)
  1286. * @return array('menu'=>array(....s))
  1287. */
  1288. public function getMenu(){
  1289. if (!$this->access_token && !$this->checkAuth()) return false;
  1290. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  1291. if ($result)
  1292. {
  1293. $json = json_decode($result,true);
  1294. if (!$json || isset($json['errcode'])) {
  1295. $this->errCode = $json['errcode'];
  1296. $this->errMsg = $json['errmsg'];
  1297. return false;
  1298. }
  1299. return $json;
  1300. }
  1301. return false;
  1302. }
  1303. /**
  1304. * 删除菜单(认证后的订阅号可用)
  1305. * @return boolean
  1306. */
  1307. public function deleteMenu(){
  1308. if (!$this->access_token && !$this->checkAuth()) return false;
  1309. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  1310. if ($result)
  1311. {
  1312. $json = json_decode($result,true);
  1313. if (!$json || !empty($json['errcode'])) {
  1314. $this->errCode = $json['errcode'];
  1315. $this->errMsg = $json['errmsg'];
  1316. return false;
  1317. }
  1318. return true;
  1319. }
  1320. return false;
  1321. }
  1322. /**
  1323. * 上传多媒体文件(认证后的订阅号可用)
  1324. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1325. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1326. * @param array $data {"media":'@Path\filename.jpg'}
  1327. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1328. * @return boolean|array
  1329. */
  1330. public function uploadMedia($data, $type){
  1331. if (!$this->access_token && !$this->checkAuth()) return false;
  1332. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1333. if ($result)
  1334. {
  1335. $json = json_decode($result,true);
  1336. if (!$json || !empty($json['errcode'])) {
  1337. $this->errCode = $json['errcode'];
  1338. $this->errMsg = $json['errmsg'];
  1339. return false;
  1340. }
  1341. return $json;
  1342. }
  1343. return false;
  1344. }
  1345. /**
  1346. * 根据媒体文件ID获取媒体文件(认证后的订阅号可用)
  1347. * @param string $media_id 媒体文件id
  1348. * @return raw data
  1349. */
  1350. public function getMedia($media_id){
  1351. if (!$this->access_token && !$this->checkAuth()) return false;
  1352. $result = $this->http_get(self::UPLOAD_MEDIA_URL.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1353. if ($result)
  1354. {
  1355. $json = json_decode($result,true);
  1356. if (isset($json['errcode'])) {
  1357. $this->errCode = $json['errcode'];
  1358. $this->errMsg = $json['errmsg'];
  1359. return false;
  1360. }
  1361. return $result;
  1362. }
  1363. return false;
  1364. }
  1365. /**
  1366. * 上传图文消息素材(认证后的订阅号可用)
  1367. * @param array $data 消息结构{"articles":[{...}]}
  1368. * @return boolean|array
  1369. */
  1370. public function uploadArticles($data){
  1371. if (!$this->access_token && !$this->checkAuth()) return false;
  1372. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1373. if ($result)
  1374. {
  1375. $json = json_decode($result,true);
  1376. if (!$json || !empty($json['errcode'])) {
  1377. $this->errCode = $json['errcode'];
  1378. $this->errMsg = $json['errmsg'];
  1379. return false;
  1380. }
  1381. return $json;
  1382. }
  1383. return false;
  1384. }
  1385. /**
  1386. * 上传视频素材(认证后的订阅号可用)
  1387. * @param array $data 消息结构
  1388. * {
  1389. * "media_id"=>"", //通过上传媒体接口得到的MediaId
  1390. * "title"=>"TITLE", //视频标题
  1391. * "description"=>"Description" //视频描述
  1392. * }
  1393. * @return boolean|array
  1394. * {
  1395. * "type":"video",
  1396. * "media_id":"mediaid",
  1397. * "created_at":1398848981
  1398. * }
  1399. */
  1400. public function uploadMpVideo($data){
  1401. if (!$this->access_token && !$this->checkAuth()) return false;
  1402. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_VIDEO_UPLOAD.'access_token='.$this->access_token,self::json_encode($data));
  1403. if ($result)
  1404. {
  1405. $json = json_decode($result,true);
  1406. if (!$json || !empty($json['errcode'])) {
  1407. $this->errCode = $json['errcode'];
  1408. $this->errMsg = $json['errmsg'];
  1409. return false;
  1410. }
  1411. return $json;
  1412. }
  1413. return false;
  1414. }
  1415. /**
  1416. * 高级群发消息, 根据OpenID列表群发图文消息(订阅号不可用)
  1417. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1418. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1419. * @param array $data 消息结构
  1420. * {
  1421. * "touser"=>array(
  1422. * "OPENID1",
  1423. * "OPENID2"
  1424. * ),
  1425. * "msgtype"=>"mpvideo",
  1426. * // 在下面5种类型中选择对应的参数内容
  1427. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1428. * // text => array ( "content" => "hello")
  1429. * }
  1430. * @return boolean|array
  1431. */
  1432. public function sendMassMessage($data){
  1433. if (!$this->access_token && !$this->checkAuth()) return false;
  1434. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1435. if ($result)
  1436. {
  1437. $json = json_decode($result,true);
  1438. if (!$json || !empty($json['errcode'])) {
  1439. $this->errCode = $json['errcode'];
  1440. $this->errMsg = $json['errmsg'];
  1441. return false;
  1442. }
  1443. return $json;
  1444. }
  1445. return false;
  1446. }
  1447. /**
  1448. * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用)
  1449. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1450. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1451. * @param array $data 消息结构
  1452. * {
  1453. * "filter"=>array(
  1454. * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id
  1455. * "group_id"=>"2" //群发的分组id
  1456. * ),
  1457. * "msgtype"=>"mpvideo",
  1458. * // 在下面5种类型中选择对应的参数内容
  1459. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1460. * // text => array ( "content" => "hello")
  1461. * }
  1462. * @return boolean|array
  1463. */
  1464. public function sendGroupMassMessage($data){
  1465. if (!$this->access_token && !$this->checkAuth()) return false;
  1466. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1467. if ($result)
  1468. {
  1469. $json = json_decode($result,true);
  1470. if (!$json || !empty($json['errcode'])) {
  1471. $this->errCode = $json['errcode'];
  1472. $this->errMsg = $json['errmsg'];
  1473. return false;
  1474. }
  1475. return $json;
  1476. }
  1477. return false;
  1478. }
  1479. /**
  1480. * 高级群发消息, 删除群发图文消息(认证后的订阅号可用)
  1481. * @param int $msg_id 消息id
  1482. * @return boolean|array
  1483. */
  1484. public function deleteMassMessage($msg_id){
  1485. if (!$this->access_token && !$this->checkAuth()) return false;
  1486. $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)));
  1487. if ($result)
  1488. {
  1489. $json = json_decode($result,true);
  1490. if (!$json || !empty($json['errcode'])) {
  1491. $this->errCode = $json['errcode'];
  1492. $this->errMsg = $json['errmsg'];
  1493. return false;
  1494. }
  1495. return true;
  1496. }
  1497. return false;
  1498. }
  1499. /**
  1500. * 高级群发消息, 预览群发消息(认证后的订阅号可用)
  1501. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1502. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1503. * @param array $data 消息结构
  1504. * {
  1505. * "touser"=>"OPENID",
  1506. * "msgtype"=>"mpvideo",
  1507. * // 在下面5种类型中选择对应的参数内容
  1508. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1509. * // text => array ( "content" => "hello")
  1510. * }
  1511. * @return boolean|array
  1512. */
  1513. public function previewMassMessage($data){
  1514. if (!$this->access_token && !$this->checkAuth()) return false;
  1515. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_PREVIEW_URL.'access_token='.$this->access_token,self::json_encode($data));
  1516. if ($result)
  1517. {
  1518. $json = json_decode($result,true);
  1519. if (!$json || !empty($json['errcode'])) {
  1520. $this->errCode = $json['errcode'];
  1521. $this->errMsg = $json['errmsg'];
  1522. return false;
  1523. }
  1524. return $json;
  1525. }
  1526. return false;
  1527. }
  1528. /**
  1529. * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用)
  1530. * @param int $msg_id 消息id
  1531. * @return boolean|array
  1532. * {
  1533. * "msg_id":201053012, //群发消息后返回的消息id
  1534. * "msg_status":"SEND_SUCCESS" //消息发送后的状态,SENDING表示正在发送 SEND_SUCCESS表示发送成功
  1535. * }
  1536. */
  1537. public function queryMassMessage($msg_id){
  1538. if (!$this->access_token && !$this->checkAuth()) return false;
  1539. $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)));
  1540. if ($result)
  1541. {
  1542. $json = json_decode($result,true);
  1543. if (!$json || !empty($json['errcode'])) {
  1544. $this->errCode = $json['errcode'];
  1545. $this->errMsg = $json['errmsg'];
  1546. return false;
  1547. }
  1548. return $json;
  1549. }
  1550. return false;
  1551. }
  1552. /**
  1553. * 创建二维码ticket
  1554. * @param int $scene_id 自定义追踪id
  1555. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
  1556. * @param int $expire 临时二维码有效期,最大为1800秒
  1557. * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800,'url'=>'二维码图片解析后的地址')
  1558. */
  1559. public function getQRCode($scene_id,$type=0,$expire=1800){
  1560. if (!$this->access_token && !$this->checkAuth()) return false;
  1561. $data = array(
  1562. 'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
  1563. 'expire_seconds'=>$expire,
  1564. 'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
  1565. );
  1566. if ($type == 1) {
  1567. unset($data['expire_seconds']);
  1568. }
  1569. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1570. if ($result)
  1571. {
  1572. $json = json_decode($result,true);
  1573. if (!$json || !empty($json['errcode'])) {
  1574. $this->errCode = $json['errcode'];
  1575. $this->errMsg = $json['errmsg'];
  1576. return false;
  1577. }
  1578. return $json;
  1579. }
  1580. return false;
  1581. }
  1582. /**
  1583. * 获取二维码图片
  1584. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  1585. * @return string url 返回http地址
  1586. */
  1587. public function getQRUrl($ticket) {
  1588. return self::QRCODE_IMG_URL.$ticket;
  1589. }
  1590. /**
  1591. * 长链接转短链接接口
  1592. * @param string $long_url 传入要转换的长url
  1593. * @return boolean|string url 成功则返回转换后的短url
  1594. */
  1595. public function getShortUrl($long_url){
  1596. if (!$this->access_token && !$this->checkAuth()) return false;
  1597. $data = array(
  1598. 'action'=>'long2short',
  1599. 'long_url'=>$long_url
  1600. );
  1601. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  1602. if ($result)
  1603. {
  1604. $json = json_decode($result,true);
  1605. if (!$json || !empty($json['errcode'])) {
  1606. $this->errCode = $json['errcode'];
  1607. $this->errMsg = $json['errmsg'];
  1608. return false;
  1609. }
  1610. return $json['short_url'];
  1611. }
  1612. return false;
  1613. }
  1614. /**
  1615. * 批量获取关注用户列表
  1616. * @param unknown $next_openid
  1617. */
  1618. public function getUserList($next_openid=''){
  1619. if (!$this->access_token && !$this->checkAuth()) return false;
  1620. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  1621. if ($result)
  1622. {
  1623. $json = json_decode($result,true);
  1624. if (isset($json['errcode'])) {
  1625. $this->errCode = $json['errcode'];
  1626. $this->errMsg = $json['errmsg'];
  1627. return false;
  1628. }
  1629. return $json;
  1630. }
  1631. return false;
  1632. }
  1633. /**
  1634. * 获取关注者详细信息
  1635. * @param string $openid
  1636. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  1637. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1638. */
  1639. public function getUserInfo($openid){
  1640. if (!$this->access_token && !$this->checkAuth()) return false;
  1641. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  1642. if ($result)
  1643. {
  1644. $json = json_decode($result,true);
  1645. if (isset($json['errcode'])) {
  1646. $this->errCode = $json['errcode'];
  1647. $this->errMsg = $json['errmsg'];
  1648. return false;
  1649. }
  1650. return $json;
  1651. }
  1652. return false;
  1653. }
  1654. /**
  1655. * 设置用户备注名
  1656. * @param string $openid
  1657. * @param string $remark 备注名
  1658. * @return boolean|array
  1659. */
  1660. public function updateUserRemark($openid,$remark){
  1661. if (!$this->access_token && !$this->checkAuth()) return false;
  1662. $data = array(
  1663. 'openid'=>$openid,
  1664. 'remark'=>$remark
  1665. );
  1666. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
  1667. if ($result)
  1668. {
  1669. $json = json_decode($result,true);
  1670. if (!$json || !empty($json['errcode'])) {
  1671. $this->errCode = $json['errcode'];
  1672. $this->errMsg = $json['errmsg'];
  1673. return false;
  1674. }
  1675. return $json;
  1676. }
  1677. return false;
  1678. }
  1679. /**
  1680. * 获取用户分组列表
  1681. * @return boolean|array
  1682. */
  1683. public function getGroup(){
  1684. if (!$this->access_token && !$this->checkAuth()) return false;
  1685. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  1686. if ($result)
  1687. {
  1688. $json = json_decode($result,true);
  1689. if (isset($json['errcode'])) {
  1690. $this->errCode = $json['errcode'];
  1691. $this->errMsg = $json['errmsg'];
  1692. return false;
  1693. }
  1694. return $json;
  1695. }
  1696. return false;
  1697. }
  1698. /**
  1699. * 获取用户所在分组
  1700. * @param string $openid
  1701. * @return boolean|int 成功则返回用户分组id
  1702. */
  1703. public function getUserGroup($openid){
  1704. if (!$this->access_token && !$this->checkAuth()) return false;
  1705. $data = array(
  1706. 'openid'=>$openid
  1707. );
  1708. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1709. if ($result)
  1710. {
  1711. $json = json_decode($result,true);
  1712. if (!$json || !empty($json['errcode'])) {
  1713. $this->errCode = $json['errcode'];
  1714. $this->errMsg = $json['errmsg'];
  1715. return false;
  1716. } else
  1717. if (isset($json['groupid'])) return $json['groupid'];
  1718. }
  1719. return false;
  1720. }
  1721. /**
  1722. * 新增自定分组
  1723. * @param string $name 分组名称
  1724. * @return boolean|array
  1725. */
  1726. public function createGroup($name){
  1727. if (!$this->access_token && !$this->checkAuth()) return false;
  1728. $data = array(
  1729. 'group'=>array('name'=>$name)
  1730. );
  1731. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1732. if ($result)
  1733. {
  1734. $json = json_decode($result,true);
  1735. if (!$json || !empty($json['errcode'])) {
  1736. $this->errCode = $json['errcode'];
  1737. $this->errMsg = $json['errmsg'];
  1738. return false;
  1739. }
  1740. return $json;
  1741. }
  1742. return false;
  1743. }
  1744. /**
  1745. * 更改分组名称
  1746. * @param int $groupid 分组id
  1747. * @param string $name 分组名称
  1748. * @return boolean|array
  1749. */
  1750. public function updateGroup($groupid,$name){
  1751. if (!$this->access_token && !$this->checkAuth()) return false;
  1752. $data = array(
  1753. 'group'=>array('id'=>$groupid,'name'=>$name)
  1754. );
  1755. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1756. if ($result)
  1757. {
  1758. $json = json_decode($result,true);
  1759. if (!$json || !empty($json['errcode'])) {
  1760. $this->errCode = $json['errcode'];
  1761. $this->errMsg = $json['errmsg'];
  1762. return false;
  1763. }
  1764. return $json;
  1765. }
  1766. return false;
  1767. }
  1768. /**
  1769. * 移动用户分组
  1770. * @param int $groupid 分组id
  1771. * @param string $openid 用户openid
  1772. * @return boolean|array
  1773. */
  1774. public function updateGroupMembers($groupid,$openid){
  1775. if (!$this->access_token && !$this->checkAuth()) return false;
  1776. $data = array(
  1777. 'openid'=>$openid,
  1778. 'to_groupid'=>$groupid
  1779. );
  1780. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1781. if ($result)
  1782. {
  1783. $json = json_decode($result,true);
  1784. if (!$json || !empty($json['errcode'])) {
  1785. $this->errCode = $json['errcode'];
  1786. $this->errMsg = $json['errmsg'];
  1787. return false;
  1788. }
  1789. return $json;
  1790. }
  1791. return false;
  1792. }
  1793. /**
  1794. * 发送客服消息
  1795. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  1796. * @return boolean|array
  1797. */
  1798. public function sendCustomMessage($data){
  1799. if (!$this->access_token && !$this->checkAuth()) return false;
  1800. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1801. if ($result)
  1802. {
  1803. $json = json_decode($result,true);
  1804. if (!$json || !empty($json['errcode'])) {
  1805. $this->errCode = $json['errcode'];
  1806. $this->errMsg = $json['errmsg'];
  1807. return false;
  1808. }
  1809. return $json;
  1810. }
  1811. return false;
  1812. }
  1813. /**
  1814. * oauth 授权跳转接口
  1815. * @param string $callback 回调URI
  1816. * @return string
  1817. */
  1818. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  1819. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1820. }
  1821. /**
  1822. * 通过code获取Access Token
  1823. * @return array {access_token,expires_in,refresh_token,openid,scope}
  1824. */
  1825. public function getOauthAccessToken(){
  1826. $code = isset($_GET['code'])?$_GET['code']:'';
  1827. if (!$code) return false;
  1828. $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');
  1829. if ($result)
  1830. {
  1831. $json = json_decode($result,true);
  1832. if (!$json || !empty($json['errcode'])) {
  1833. $this->errCode = $json['errcode'];
  1834. $this->errMsg = $json['errmsg'];
  1835. return false;
  1836. }
  1837. $this->user_token = $json['access_token'];
  1838. return $json;
  1839. }
  1840. return false;
  1841. }
  1842. /**
  1843. * 刷新access token并续期
  1844. * @param string $refresh_token
  1845. * @return boolean|mixed
  1846. */
  1847. public function getOauthRefreshToken($refresh_token){
  1848. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  1849. if ($result)
  1850. {
  1851. $json = json_decode($result,true);
  1852. if (!$json || !empty($json['errcode'])) {
  1853. $this->errCode = $json['errcode'];
  1854. $this->errMsg = $json['errmsg'];
  1855. return false;
  1856. }
  1857. $this->user_token = $json['access_token'];
  1858. return $json;
  1859. }
  1860. return false;
  1861. }
  1862. /**
  1863. * 获取授权后的用户资料
  1864. * @param string $access_token
  1865. * @param string $openid
  1866. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  1867. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1868. */
  1869. public function getOauthUserinfo($access_token,$openid){
  1870. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  1871. if ($result)
  1872. {
  1873. $json = json_decode($result,true);
  1874. if (!$json || !empty($json['errcode'])) {
  1875. $this->errCode = $json['errcode'];
  1876. $this->errMsg = $json['errmsg'];
  1877. return false;
  1878. }
  1879. return $json;
  1880. }
  1881. return false;
  1882. }
  1883. /**
  1884. * 检验授权凭证是否有效
  1885. * @param string $access_token
  1886. * @param string $openid
  1887. * @return boolean 是否有效
  1888. */
  1889. public function getOauthAuth($access_token,$openid){
  1890. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  1891. if ($result)
  1892. {
  1893. $json = json_decode($result,true);
  1894. if (!$json || !empty($json['errcode'])) {
  1895. $this->errCode = $json['errcode'];
  1896. $this->errMsg = $json['errmsg'];
  1897. return false;
  1898. } else
  1899. if ($json['errcode']==0) return true;
  1900. }
  1901. return false;
  1902. }
  1903. /**
  1904. * 模板消息 设置所属行业
  1905. * @param int $id1 公众号模板消息所属行业编号,参看官方开发文档 行业代码
  1906. * @param int $id2 同$id1。但如果只有一个行业,此参数可省略
  1907. * @return boolean|array
  1908. */
  1909. public function setTMIndustry($id1,$id2=''){
  1910. if ($id1) $data['industry_id1'] = $id1;
  1911. if ($id2) $data['industry_id2'] = $id2;
  1912. if (!$this->access_token && !$this->checkAuth()) return false;
  1913. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SET_INDUSTRY_URL.'access_token='.$this->access_token,self::json_encode($data));
  1914. if($result){
  1915. $json = json_decode($result,true);
  1916. if (!$json || !empty($json['errcode'])) {
  1917. $this->errCode = $json['errcode'];
  1918. $this->errMsg = $json['errmsg'];
  1919. return false;
  1920. }
  1921. return $json;
  1922. }
  1923. return false;
  1924. }
  1925. /**
  1926. * 模板消息 添加消息模板
  1927. * 成功返回消息模板的调用id
  1928. * @param string $tpl_id 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
  1929. * @return boolean|string
  1930. */
  1931. public function addTemplateMessage($tpl_id){
  1932. $data = array ('template_id_short' =>$tpl_id);
  1933. if (!$this->access_token && !$this->checkAuth()) return false;
  1934. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_ADD_TPL_URL.'access_token='.$this->access_token,self::json_encode($data));
  1935. if($result){
  1936. $json = json_decode($result,true);
  1937. if (!$json || !empty($json['errcode'])) {
  1938. $this->errCode = $json['errcode'];
  1939. $this->errMsg = $json['errmsg'];
  1940. return false;
  1941. }
  1942. return $json['template_id'];
  1943. }
  1944. return false;
  1945. }
  1946. /**
  1947. * 发送模板消息
  1948. * @param array $data 消息结构
  1949. * {
  1950. "touser":"OPENID",
  1951. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  1952. "url":"http://weixin.qq.com/download",
  1953. "topcolor":"#FF0000",
  1954. "data":{
  1955. "参数名1": {
  1956. "value":"参数",
  1957. "color":"#173177" //参数颜色
  1958. },
  1959. "Date":{
  1960. "value":"06月07日 19时24分",
  1961. "color":"#173177"
  1962. },
  1963. "CardNumber":{
  1964. "value":"0426",
  1965. "color":"#173177"
  1966. },
  1967. "Type":{
  1968. "value":"消费",
  1969. "color":"#173177"
  1970. }
  1971. }
  1972. }
  1973. * @return boolean|array
  1974. */
  1975. public function sendTemplateMessage($data){
  1976. if (!$this->access_token && !$this->checkAuth()) return false;
  1977. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1978. if($result){
  1979. $json = json_decode($result,true);
  1980. if (!$json || !empty($json['errcode'])) {
  1981. $this->errCode = $json['errcode'];
  1982. $this->errMsg = $json['errmsg'];
  1983. return false;
  1984. }
  1985. return $json;
  1986. }
  1987. return false;
  1988. }
  1989. /**
  1990. * 获取多客服会话记录
  1991. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  1992. * @return boolean|array
  1993. */
  1994. public function getCustomServiceMessage($data){
  1995. if (!$this->access_token && !$this->checkAuth()) return false;
  1996. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  1997. if ($result)
  1998. {
  1999. $json = json_decode($result,true);
  2000. if (!$json || !empty($json['errcode'])) {
  2001. $this->errCode = $json['errcode'];
  2002. $this->errMsg = $json['errmsg'];
  2003. return false;
  2004. }
  2005. return $json;
  2006. }
  2007. return false;
  2008. }
  2009. /**
  2010. * 转发多客服消息
  2011. * Example: $obj->transfer_customer_service($customer_account)->reply();
  2012. * @param string $customer_account 转发到指定客服帐号:test1@test
  2013. */
  2014. public function transfer_customer_service($customer_account = '')
  2015. {
  2016. $msg = array(
  2017. 'ToUserName' => $this->getRevFrom(),
  2018. 'FromUserName'=>$this->getRevTo(),
  2019. 'CreateTime'=>time(),
  2020. 'MsgType'=>'transfer_customer_service',
  2021. );
  2022. if (!$customer_account) {
  2023. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  2024. }
  2025. $this->Message($msg);
  2026. return $this;
  2027. }
  2028. /**
  2029. * 获取多客服客服基本信息
  2030. *
  2031. * @return boolean|array
  2032. */
  2033. public function getCustomServiceKFlist(){
  2034. if (!$this->access_token && !$this->checkAuth()) return false;
  2035. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  2036. if ($result)
  2037. {
  2038. $json = json_decode($result,true);
  2039. if (!$json || !empty($json['errcode'])) {
  2040. $this->errCode = $json['errcode'];
  2041. $this->errMsg = $json['errmsg'];
  2042. return false;
  2043. }
  2044. return $json;
  2045. }
  2046. return false;
  2047. }
  2048. /**
  2049. * 获取多客服在线客服接待信息
  2050. *
  2051. * @return boolean|array {
  2052. "kf_online_list": [
  2053. {
  2054. "kf_account": "test1@test", //客服账号@微信别名
  2055. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  2056. "kf_id": "1001", //客服工号
  2057. "auto_accept": 0, //客服设置的最大自动接入数
  2058. "accepted_case": 1 //客服当前正在接待的会话数
  2059. }
  2060. ]
  2061. }
  2062. */
  2063. public function getCustomServiceOnlineKFlist(){
  2064. if (!$this->access_token && !$this->checkAuth()) return false;
  2065. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  2066. if ($result)
  2067. {
  2068. $json = json_decode($result,true);
  2069. if (!$json || !empty($json['errcode'])) {
  2070. $this->errCode = $json['errcode'];
  2071. $this->errMsg = $json['errmsg'];
  2072. return false;
  2073. }
  2074. return $json;
  2075. }
  2076. return false;
  2077. }
  2078. /**
  2079. * 创建指定多客服会话
  2080. * @tutorial 当用户已被其他客服接待或指定客服不在线则会失败
  2081. * @param string $openid //用户openid
  2082. * @param string $kf_account //客服账号
  2083. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2084. * @return boolean | array //成功返回json数组
  2085. * {
  2086. * "errcode": 0,
  2087. * "errmsg": "ok",
  2088. * }
  2089. */
  2090. public function createKFSession($openid,$kf_account,$text=''){
  2091. $data=array(
  2092. "openid" =>$openid,
  2093. "nickname" => $kf_account
  2094. );
  2095. if ($text) $data["text"] = $text;
  2096. if (!$this->access_token && !$this->checkAuth()) return false;
  2097. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEESSION_CREATE.'access_token='.$this->access_token,self::json_encode($data));
  2098. if ($result)
  2099. {
  2100. $json = json_decode($result,true);
  2101. if (!$json || !empty($json['errcode'])) {
  2102. $this->errCode = $json['errcode'];
  2103. $this->errMsg = $json['errmsg'];
  2104. return false;
  2105. }
  2106. return $json;
  2107. }
  2108. return false;
  2109. }
  2110. /**
  2111. * 关闭指定多客服会话
  2112. * @tutorial 当用户被其他客服接待时则会失败
  2113. * @param string $openid //用户openid
  2114. * @param string $kf_account //客服账号
  2115. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2116. * @return boolean | array //成功返回json数组
  2117. * {
  2118. * "errcode": 0,
  2119. * "errmsg": "ok",
  2120. * }
  2121. */
  2122. public function closeKFSession($openid,$kf_account,$text=''){
  2123. $data=array(
  2124. "openid" =>$openid,
  2125. "nickname" => $kf_account
  2126. );
  2127. if ($text) $data["text"] = $text;
  2128. if (!$this->access_token && !$this->checkAuth()) return false;
  2129. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEESSION_CLOSE .'access_token='.$this->access_token,self::json_encode($data));
  2130. if ($result)
  2131. {
  2132. $json = json_decode($result,true);
  2133. if (!$json || !empty($json['errcode'])) {
  2134. $this->errCode = $json['errcode'];
  2135. $this->errMsg = $json['errmsg'];
  2136. return false;
  2137. }
  2138. return $json;
  2139. }
  2140. return false;
  2141. }
  2142. /**
  2143. * 获取用户会话状态
  2144. * @param string $openid //用户openid
  2145. * @return boolean | array //成功返回json数组
  2146. * {
  2147. * "errcode" : 0,
  2148. * "errmsg" : "ok",
  2149. * "kf_account" : "test1@test", //正在接待的客服
  2150. * "createtime": 123456789, //会话接入时间
  2151. * }
  2152. */
  2153. public function getKFSession($openid){
  2154. if (!$this->access_token && !$this->checkAuth()) return false;
  2155. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SEESSION_GET .'access_token='.$this->access_token.'&openid='.$openid);
  2156. if ($result)
  2157. {
  2158. $json = json_decode($result,true);
  2159. if (!$json || !empty($json['errcode'])) {
  2160. $this->errCode = $json['errcode'];
  2161. $this->errMsg = $json['errmsg'];
  2162. return false;
  2163. }
  2164. return $json;
  2165. }
  2166. return false;
  2167. }
  2168. /**
  2169. * 获取指定客服的会话列表
  2170. * @param string $openid //用户openid
  2171. * @return boolean | array //成功返回json数组
  2172. * array(
  2173. * 'sessionlist' => array (
  2174. * array (
  2175. * 'openid'=>'OPENID', //客户 openid
  2176. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2177. * ),
  2178. * array (
  2179. * 'openid'=>'OPENID', //客户 openid
  2180. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2181. * ),
  2182. * )
  2183. * )
  2184. */
  2185. public function getKFSessionlist($kf_account){
  2186. if (!$this->access_token && !$this->checkAuth()) return false;
  2187. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SEESSION_GET_LIST .'access_token='.$this->access_token.'&kf_account='.$kf_account);
  2188. if ($result)
  2189. {
  2190. $json = json_decode($result,true);
  2191. if (!$json || !empty($json['errcode'])) {
  2192. $this->errCode = $json['errcode'];
  2193. $this->errMsg = $json['errmsg'];
  2194. return false;
  2195. }
  2196. return $json;
  2197. }
  2198. return false;
  2199. }
  2200. /**
  2201. * 获取未接入会话列表
  2202. * @param string $openid //用户openid
  2203. * @return boolean | array //成功返回json数组
  2204. * array (
  2205. * 'count' => 150 , //未接入会话数量
  2206. * 'waitcaselist' => array (
  2207. * array (
  2208. * 'openid'=>'OPENID', //客户 openid
  2209. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2210. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2211. * ),
  2212. * array (
  2213. * 'openid'=>'OPENID', //客户 openid
  2214. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2215. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2216. * )
  2217. * )
  2218. * )
  2219. */
  2220. public function getKFSessionWait(){
  2221. if (!$this->access_token && !$this->checkAuth()) return false;
  2222. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SEESSION_GET_WAIT .'access_token='.$this->access_token);
  2223. if ($result)
  2224. {
  2225. $json = json_decode($result,true);
  2226. if (!$json || !empty($json['errcode'])) {
  2227. $this->errCode = $json['errcode'];
  2228. $this->errMsg = $json['errmsg'];
  2229. return false;
  2230. }
  2231. return $json;
  2232. }
  2233. return false;
  2234. }
  2235. /**
  2236. * 添加客服账号
  2237. *
  2238. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2239. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2240. * @param string $password //客服账号明文登录密码,会自动加密
  2241. * @return boolean|array
  2242. * 成功返回结果
  2243. * {
  2244. * "errcode": 0,
  2245. * "errmsg": "ok",
  2246. * }
  2247. */
  2248. public function addKFAccount($account,$nickname,$password){
  2249. $data=array(
  2250. "kf_account" =>$account,
  2251. "nickname" => $nickname,
  2252. "password" => md5($password)
  2253. );
  2254. if (!$this->access_token && !$this->checkAuth()) return false;
  2255. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_ADD_URL.'access_token='.$this->access_token,self::json_encode($data));
  2256. if ($result)
  2257. {
  2258. $json = json_decode($result,true);
  2259. if (!$json || !empty($json['errcode'])) {
  2260. $this->errCode = $json['errcode'];
  2261. $this->errMsg = $json['errmsg'];
  2262. return false;
  2263. }
  2264. return $json;
  2265. }
  2266. return false;
  2267. }
  2268. /**
  2269. * 修改客服账号信息
  2270. *
  2271. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2272. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2273. * @param string $password //客服账号明文登录密码,会自动加密
  2274. * @return boolean|array
  2275. * 成功返回结果
  2276. * {
  2277. * "errcode": 0,
  2278. * "errmsg": "ok",
  2279. * }
  2280. */
  2281. public function updateKFAccount($account,$nickname,$password){
  2282. $data=array(
  2283. "kf_account" =>$account,
  2284. "nickname" => $nickname,
  2285. "password" => md5($password)
  2286. );
  2287. if (!$this->access_token && !$this->checkAuth()) return false;
  2288. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2289. if ($result)
  2290. {
  2291. $json = json_decode($result,true);
  2292. if (!$json || !empty($json['errcode'])) {
  2293. $this->errCode = $json['errcode'];
  2294. $this->errMsg = $json['errmsg'];
  2295. return false;
  2296. }
  2297. return $json;
  2298. }
  2299. return false;
  2300. }
  2301. /**
  2302. * 删除客服账号
  2303. *
  2304. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2305. * @return boolean|array
  2306. * 成功返回结果
  2307. * {
  2308. * "errcode": 0,
  2309. * "errmsg": "ok",
  2310. * }
  2311. */
  2312. public function deleteKFAccount($account){
  2313. if (!$this->access_token && !$this->checkAuth()) return false;
  2314. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_DEL_URL.'access_token='.$this->access_token.'&kf_account='.$account);
  2315. if ($result)
  2316. {
  2317. $json = json_decode($result,true);
  2318. if (!$json || !empty($json['errcode'])) {
  2319. $this->errCode = $json['errcode'];
  2320. $this->errMsg = $json['errmsg'];
  2321. return false;
  2322. }
  2323. return $json;
  2324. }
  2325. return false;
  2326. }
  2327. /**
  2328. * 上传客服头像
  2329. *
  2330. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2331. * @param string $imgfile //头像文件完整路径,如:'D:\user.jpg'。头像文件必须JPG格式,像素建议640*640
  2332. * @return boolean|array
  2333. * 成功返回结果
  2334. * {
  2335. * "errcode": 0,
  2336. * "errmsg": "ok",
  2337. * }
  2338. */
  2339. public function setKFHeadImg($account,$imgfile){
  2340. if (!$this->access_token && !$this->checkAuth()) return false;
  2341. $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);
  2342. if ($result)
  2343. {
  2344. $json = json_decode($result,true);
  2345. if (!$json || !empty($json['errcode'])) {
  2346. $this->errCode = $json['errcode'];
  2347. $this->errMsg = $json['errmsg'];
  2348. return false;
  2349. }
  2350. return $json;
  2351. }
  2352. return false;
  2353. }
  2354. /**
  2355. * 语义理解接口
  2356. * @param String $uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
  2357. * @param String $query 输入文本串
  2358. * @param String $category 需要使用的服务类型,多个用“,”隔开,不能为空
  2359. * @param Float $latitude 纬度坐标,与经度同时传入;与城市二选一传入
  2360. * @param Float $longitude 经度坐标,与纬度同时传入;与城市二选一传入
  2361. * @param String $city 城市名称,与经纬度二选一传入
  2362. * @param String $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入
  2363. * @return boolean|array
  2364. */
  2365. public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
  2366. if (!$this->access_token && !$this->checkAuth()) return false;
  2367. $data=array(
  2368. 'query' => $query,
  2369. 'category' => $category,
  2370. 'appid' => $this->appid,
  2371. 'uid' => ''
  2372. );
  2373. //地理坐标或城市名称二选一
  2374. if ($latitude) {
  2375. $data['latitude'] = $latitude;
  2376. $data['longitude'] = $longitude;
  2377. } elseif ($city) {
  2378. $data['city'] = $city;
  2379. } elseif ($region) {
  2380. $data['region'] = $region;
  2381. }
  2382. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
  2383. if ($result)
  2384. {
  2385. $json = json_decode($result,true);
  2386. if (!$json || !empty($json['errcode'])) {
  2387. $this->errCode = $json['errcode'];
  2388. $this->errMsg = $json['errmsg'];
  2389. return false;
  2390. }
  2391. return $json;
  2392. }
  2393. return false;
  2394. }
  2395. /**
  2396. * 创建卡券
  2397. * @param Array $data 卡券数据
  2398. * @return array|boolean 返回数组中card_id为卡券ID
  2399. */
  2400. public function createCard($data) {
  2401. if (!$this->access_token && !$this->checkAuth()) return false;
  2402. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2403. if ($result) {
  2404. $json = json_decode($result, true);
  2405. if (!$json || !empty($json['errcode'])) {
  2406. $this->errCode = $json['errcode'];
  2407. $this->errMsg = $json['errmsg'];
  2408. return false;
  2409. }
  2410. return $json;
  2411. }
  2412. return false;
  2413. }
  2414. /**
  2415. * 更改卡券信息
  2416. * 调用该接口更新信息后会重新送审,卡券状态变更为待审核。已被用户领取的卡券会实时更新票面信息。
  2417. * @param string $data
  2418. * @return boolean
  2419. */
  2420. public function updateCard($data) {
  2421. if (!$this->access_token && !$this->checkAuth()) return false;
  2422. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2423. if ($result) {
  2424. $json = json_decode($result, true);
  2425. if (!$json || !empty($json['errcode'])) {
  2426. $this->errCode = $json['errcode'];
  2427. $this->errMsg = $json['errmsg'];
  2428. return false;
  2429. }
  2430. return true;
  2431. }
  2432. return false;
  2433. }
  2434. /**
  2435. * 删除卡券
  2436. * 允许商户删除任意一类卡券。删除卡券后,该卡券对应已生成的领取用二维码、添加到卡包 JS API 均会失效。
  2437. * 注意:删除卡券不能删除已被用户领取,保存在微信客户端中的卡券,已领取的卡券依旧有效。
  2438. * @param string $card_id 卡券ID
  2439. * @return boolean
  2440. */
  2441. public function delCard($card_id) {
  2442. $data = array(
  2443. 'card_id' => $card_id,
  2444. );
  2445. if (!$this->access_token && !$this->checkAuth()) return false;
  2446. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  2447. if ($result) {
  2448. $json = json_decode($result, true);
  2449. if (!$json || !empty($json['errcode'])) {
  2450. $this->errCode = $json['errcode'];
  2451. $this->errMsg = $json['errmsg'];
  2452. return false;
  2453. }
  2454. return true;
  2455. }
  2456. return false;
  2457. }
  2458. /**
  2459. * 查询卡券详情
  2460. * @param string $card_id
  2461. * @return boolean|array 返回数组信息比较复杂,请参看卡券接口文档
  2462. */
  2463. public function getCardInfo($card_id) {
  2464. $data = array(
  2465. 'card_id' => $card_id,
  2466. );
  2467. if (!$this->access_token && !$this->checkAuth()) return false;
  2468. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  2469. if ($result) {
  2470. $json = json_decode($result, true);
  2471. if (!$json || !empty($json['errcode'])) {
  2472. $this->errCode = $json['errcode'];
  2473. $this->errMsg = $json['errmsg'];
  2474. return false;
  2475. }
  2476. return $json;
  2477. }
  2478. return false;
  2479. }
  2480. /**
  2481. * 获取颜色列表
  2482. * 获得卡券的最新颜色列表,用于创建卡券
  2483. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  2484. */
  2485. public function getCardColors() {
  2486. if (!$this->access_token && !$this->checkAuth()) return false;
  2487. $result = $this->http_get(self::API_BASE_URL_PREFIX . self::CARD_GETCOLORS . 'access_token=' . $this->access_token);
  2488. if ($result) {
  2489. $json = json_decode($result, true);
  2490. if (!$json || !empty($json['errcode'])) {
  2491. $this->errCode = $json['errcode'];
  2492. $this->errMsg = $json['errmsg'];
  2493. return false;
  2494. }
  2495. return $json;
  2496. }
  2497. return false;
  2498. }
  2499. /**
  2500. * 拉取门店列表
  2501. * 获取在公众平台上申请创建的门店列表
  2502. * @param int $offset 开始拉取的偏移,默认为0从头开始
  2503. * @param int $count 拉取的数量,默认为0拉取全部
  2504. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  2505. */
  2506. public function getCardLocations($offset=0,$count=0) {
  2507. $data=array(
  2508. 'offset'=>$offset,
  2509. 'count'=>$count
  2510. );
  2511. if (!$this->access_token && !$this->checkAuth()) return false;
  2512. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  2513. if ($result) {
  2514. $json = json_decode($result, true);
  2515. if (!$json || !empty($json['errcode'])) {
  2516. $this->errCode = $json['errcode'];
  2517. $this->errMsg = $json['errmsg'];
  2518. return false;
  2519. }
  2520. return $json;
  2521. }
  2522. return false;
  2523. }
  2524. /**
  2525. * 批量导入门店信息
  2526. * @tutorial 返回插入的门店id列表,以逗号分隔。如果有插入失败的,则为-1,请自行核查是哪个插入失败
  2527. * @param array $data 数组形式的json数据,由于内容较多,具体内容格式请查看 微信卡券接口文档
  2528. * @return boolean|string 成功返回插入的门店id列表
  2529. */
  2530. public function addCardLocations($data) {
  2531. if (!$this->access_token && !$this->checkAuth()) return false;
  2532. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHADD . 'access_token=' . $this->access_token, self::json_encode($data));
  2533. if ($result) {
  2534. $json = json_decode($result, true);
  2535. if (!$json || !empty($json['errcode'])) {
  2536. $this->errCode = $json['errcode'];
  2537. $this->errMsg = $json['errmsg'];
  2538. return false;
  2539. }
  2540. return $json;
  2541. }
  2542. return false;
  2543. }
  2544. /**
  2545. * 生成卡券二维码
  2546. * 成功则直接返回ticket值,可以用 getQRUrl($ticket) 换取二维码url
  2547. *
  2548. * @param string $cardid 卡券ID 必须
  2549. * @param string $code 指定卡券 code 码,只能被领一次。use_custom_code 字段为 true 的卡券必须填写,非自定义 code 不必填写。
  2550. * @param string $openid 指定领取者的 openid,只有该用户能领取。bind_openid 字段为 true 的卡券必须填写,非自定义 openid 不必填写。
  2551. * @param int $expire_seconds 指定二维码的有效时间,范围是 60 ~ 1800 秒。不填默认为永久有效。
  2552. * @param boolean $is_unique_code 指定下发二维码,生成的二维码随机分配一个 code,领取后不可再次扫描。填写 true 或 false。默认 false。
  2553. * @param string $balance 红包余额,以分为单位。红包类型必填(LUCKY_MONEY),其他卡券类型不填。
  2554. * @return boolean|string
  2555. */
  2556. public function createCardQrcode($card_id,$code='',$openid='',$expire_seconds=0,$is_unique_code=false,$balance='') {
  2557. $card = array(
  2558. 'card_id' => $card_id
  2559. );
  2560. if ($code)
  2561. $card['code'] = $code;
  2562. if ($openid)
  2563. $card['openid'] = $openid;
  2564. if ($expire_seconds)
  2565. $card['expire_seconds'] = $expire_seconds;
  2566. if ($is_unique_code)
  2567. $card['is_unique_code'] = $is_unique_code;
  2568. if ($balance)
  2569. $card['balance'] = $balance;
  2570. $data = array(
  2571. 'action_name' => "QR_CARD",
  2572. 'action_info' => array('card' => $card)
  2573. );
  2574. if (!$this->access_token && !$this->checkAuth()) return false;
  2575. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_QRCODE_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2576. if ($result) {
  2577. $json = json_decode($result, true);
  2578. if (!$json || !empty($json['errcode'])) {
  2579. $this->errCode = $json['errcode'];
  2580. $this->errMsg = $json['errmsg'];
  2581. return false;
  2582. }
  2583. return $json;
  2584. }
  2585. return false;
  2586. }
  2587. /**
  2588. * 消耗 code
  2589. * 自定义 code(use_custom_code 为 true)的优惠券,在 code 被核销时,必须调用此接口。
  2590. *
  2591. * @param string $code 要消耗的序列号
  2592. * @param string $code_id 要消耗序列号所述的 card_id,创建卡券时use_custom_code 填写 true 时必填。
  2593. * @return boolean|array
  2594. * {
  2595. * "errcode":0,
  2596. * "errmsg":"ok",
  2597. * "card":{"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"},
  2598. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA"
  2599. * }
  2600. */
  2601. public function consumeCardCode($code,$card_id='') {
  2602. $data = array('code' => $code);
  2603. if ($card_id)
  2604. $data['card_id'] = $card_id;
  2605. if (!$this->access_token && !$this->checkAuth()) return false;
  2606. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_CONSUME . 'access_token=' . $this->access_token, self::json_encode($data));
  2607. if ($result) {
  2608. $json = json_decode($result, true);
  2609. if (!$json || !empty($json['errcode'])) {
  2610. $this->errCode = $json['errcode'];
  2611. $this->errMsg = $json['errmsg'];
  2612. return false;
  2613. }
  2614. return $json;
  2615. }
  2616. return false;
  2617. }
  2618. /**
  2619. * code 解码
  2620. * @param string $encrypt_code 通过 choose_card_info 获取的加密字符串
  2621. * @return boolean|array
  2622. * {
  2623. * "errcode":0,
  2624. * "errmsg":"ok",
  2625. * "code":"751234212312"
  2626. * }
  2627. */
  2628. public function decryptCardCode($encrypt_code) {
  2629. $data = array(
  2630. 'encrypt_code' => $encrypt_code,
  2631. );
  2632. if (!$this->access_token && !$this->checkAuth()) return false;
  2633. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_DECRYPT . 'access_token=' . $this->access_token, self::json_encode($data));
  2634. if ($result) {
  2635. $json = json_decode($result, true);
  2636. if (!$json || !empty($json['errcode'])) {
  2637. $this->errCode = $json['errcode'];
  2638. $this->errMsg = $json['errmsg'];
  2639. return false;
  2640. }
  2641. return $json;
  2642. }
  2643. return false;
  2644. }
  2645. /**
  2646. * 查询 code 的有效性(非自定义 code)
  2647. * @param string $code
  2648. * @return boolean|array
  2649. * {
  2650. * "errcode":0,
  2651. * "errmsg":"ok",
  2652. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA", //用户 openid
  2653. * "card":{
  2654. * "card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc",
  2655. * "begin_time": 1404205036, //起始使用时间
  2656. * "end_time": 1404205036, //结束时间
  2657. * }
  2658. * }
  2659. */
  2660. public function checkCardCode($code) {
  2661. $data = array(
  2662. 'code' => $code,
  2663. );
  2664. if (!$this->access_token && !$this->checkAuth()) return false;
  2665. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  2666. if ($result) {
  2667. $json = json_decode($result, true);
  2668. if (!$json || !empty($json['errcode'])) {
  2669. $this->errCode = $json['errcode'];
  2670. $this->errMsg = $json['errmsg'];
  2671. return false;
  2672. }
  2673. return $json;
  2674. }
  2675. return false;
  2676. }
  2677. /**
  2678. * 批量查询卡列表
  2679. * @param $offset 开始拉取的偏移,默认为0从头开始
  2680. * @param $count 需要查询的卡片的数量(数量最大50,默认50)
  2681. * @return boolean|array
  2682. * {
  2683. * "errcode":0,
  2684. * "errmsg":"ok",
  2685. * "card_id_list":["ph_gmt7cUVrlRk8swPwx7aDyF-pg"], //卡 id 列表
  2686. * "total_num":1 //该商户名下 card_id 总数
  2687. * }
  2688. */
  2689. public function getCardIdList($offset=0,$count=50) {
  2690. if ($count>50)
  2691. $count = 50;
  2692. $data = array(
  2693. 'offset' => $offset,
  2694. 'count' => $count,
  2695. );
  2696. if (!$this->access_token && !$this->checkAuth()) return false;
  2697. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  2698. if ($result) {
  2699. $json = json_decode($result, true);
  2700. if (!$json || !empty($json['errcode'])) {
  2701. $this->errCode = $json['errcode'];
  2702. $this->errMsg = $json['errmsg'];
  2703. return false;
  2704. }
  2705. return $json;
  2706. }
  2707. return false;
  2708. }
  2709. /**
  2710. * 更改 code
  2711. * 为确保转赠后的安全性,微信允许自定义code的商户对已下发的code进行更改。
  2712. * 注:为避免用户疑惑,建议仅在发生转赠行为后(发生转赠后,微信会通过事件推送的方式告知商户被转赠的卡券code)对用户的code进行更改。
  2713. * @param string $code 卡券的 code 编码
  2714. * @param string $code_id 卡券 ID
  2715. * @param string $new_code 新的卡券 code 编码
  2716. * @return boolean
  2717. */
  2718. public function updateCardCode($code,$code_id,$new_code) {
  2719. $data = array(
  2720. 'code' => $card,
  2721. 'card_id' => $card_id,
  2722. 'new_code' => $new_code,
  2723. );
  2724. if (!$this->access_token && !$this->checkAuth()) return false;
  2725. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2726. if ($result) {
  2727. $json = json_decode($result, true);
  2728. if (!$json || !empty($json['errcode'])) {
  2729. $this->errCode = $json['errcode'];
  2730. $this->errMsg = $json['errmsg'];
  2731. return false;
  2732. }
  2733. return true;
  2734. }
  2735. return false;
  2736. }
  2737. /**
  2738. * 设置卡券失效
  2739. * 设置卡券失效的操作不可逆
  2740. * @param string $code 需要设置为失效的 code
  2741. * @param string $code 自定义 code 的卡券必填。非自定义 code 的卡券不填。
  2742. * @return boolean
  2743. */
  2744. public function unavailableCardCode($code,$code_id='') {
  2745. $data = array(
  2746. 'code' => $code,
  2747. );
  2748. if ($code_id)
  2749. $data['code_id'] = $code_id;
  2750. if (!$this->access_token && !$this->checkAuth()) return false;
  2751. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UNAVAILABLE . 'access_token=' . $this->access_token, self::json_encode($data));
  2752. if ($result) {
  2753. $json = json_decode($result, true);
  2754. if (!$json || !empty($json['errcode'])) {
  2755. $this->errCode = $json['errcode'];
  2756. $this->errMsg = $json['errmsg'];
  2757. return false;
  2758. }
  2759. return true;
  2760. }
  2761. return false;
  2762. }
  2763. /**
  2764. * 库存修改
  2765. * @param string $data
  2766. * @return boolean
  2767. */
  2768. public function modifyCardStock($data) {
  2769. if (!$this->access_token && !$this->checkAuth()) return false;
  2770. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MODIFY_STOCK . 'access_token=' . $this->access_token, self::json_encode($data));
  2771. if ($result) {
  2772. $json = json_decode($result, true);
  2773. if (!$json || !empty($json['errcode'])) {
  2774. $this->errCode = $json['errcode'];
  2775. $this->errMsg = $json['errmsg'];
  2776. return false;
  2777. }
  2778. return true;
  2779. }
  2780. return false;
  2781. }
  2782. /**
  2783. * 激活/绑定会员卡
  2784. * @param string $data 具体结构请参看卡券开发文档(6.1.1 激活/绑定会员卡)章节
  2785. * @return boolean
  2786. */
  2787. public function activateMemberCard($data) {
  2788. if (!$this->access_token && !$this->checkAuth()) return false;
  2789. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_ACTIVATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2790. if ($result) {
  2791. $json = json_decode($result, true);
  2792. if (!$json || !empty($json['errcode'])) {
  2793. $this->errCode = $json['errcode'];
  2794. $this->errMsg = $json['errmsg'];
  2795. return false;
  2796. }
  2797. return true;
  2798. }
  2799. return false;
  2800. }
  2801. /**
  2802. * 会员卡交易
  2803. * 会员卡交易后每次积分及余额变更需通过接口通知微信,便于后续消息通知及其他扩展功能。
  2804. * @param string $data 具体结构请参看卡券开发文档(6.1.2 会员卡交易)章节
  2805. * @return boolean|array
  2806. */
  2807. public function updateMemberCard($data) {
  2808. if (!$this->access_token && !$this->checkAuth()) return false;
  2809. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  2810. if ($result) {
  2811. $json = json_decode($result, true);
  2812. if (!$json || !empty($json['errcode'])) {
  2813. $this->errCode = $json['errcode'];
  2814. $this->errMsg = $json['errmsg'];
  2815. return false;
  2816. }
  2817. return $json;
  2818. }
  2819. return false;
  2820. }
  2821. /**
  2822. * 更新红包金额
  2823. * @param string $code 红包的序列号
  2824. * @param $balance 红包余额
  2825. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 可不填。
  2826. * @return boolean|array
  2827. */
  2828. public function updateLuckyMoney($code,$balance,$card_id='') {
  2829. $data = array(
  2830. 'code' => $code,
  2831. 'balance' => $balance
  2832. );
  2833. if ($card_id)
  2834. $data['card_id'] = $card_id;
  2835. if (!$this->access_token && !$this->checkAuth()) return false;
  2836. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LUCKYMONEY_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2837. if ($result) {
  2838. $json = json_decode($result, true);
  2839. if (!$json || !empty($json['errcode'])) {
  2840. $this->errCode = $json['errcode'];
  2841. $this->errMsg = $json['errmsg'];
  2842. return false;
  2843. }
  2844. return true;
  2845. }
  2846. return false;
  2847. }
  2848. /**
  2849. * 设置卡券测试白名单
  2850. * @param string $openid 测试的 openid 列表
  2851. * @param string $user 测试的微信号列表
  2852. * @return boolean
  2853. */
  2854. public function setCardTestWhiteList($openid=array(),$user=array()) {
  2855. $data = array();
  2856. if (count($openid) > 0)
  2857. $data['openid'] = $openid;
  2858. if (count($user) > 0)
  2859. $data['username'] = $user;
  2860. if (!$this->access_token && !$this->checkAuth()) return false;
  2861. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_TESTWHILELIST_SET . 'access_token=' . $this->access_token, self::json_encode($data));
  2862. if ($result) {
  2863. $json = json_decode($result, true);
  2864. if (!$json || !empty($json['errcode'])) {
  2865. $this->errCode = $json['errcode'];
  2866. $this->errMsg = $json['errmsg'];
  2867. return false;
  2868. }
  2869. return true;
  2870. }
  2871. return false;
  2872. }
  2873. }
  2874. /**
  2875. * PKCS7Encoder class
  2876. *
  2877. * 提供基于PKCS7算法的加解密接口.
  2878. */
  2879. class PKCS7Encoder
  2880. {
  2881. public static $block_size = 32;
  2882. /**
  2883. * 对需要加密的明文进行填充补位
  2884. * @param $text 需要进行填充补位操作的明文
  2885. * @return 补齐明文字符串
  2886. */
  2887. function encode($text)
  2888. {
  2889. $block_size = PKCS7Encoder::$block_size;
  2890. $text_length = strlen($text);
  2891. //计算需要填充的位数
  2892. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  2893. if ($amount_to_pad == 0) {
  2894. $amount_to_pad = PKCS7Encoder::block_size;
  2895. }
  2896. //获得补位所用的字符
  2897. $pad_chr = chr($amount_to_pad);
  2898. $tmp = "";
  2899. for ($index = 0; $index < $amount_to_pad; $index++) {
  2900. $tmp .= $pad_chr;
  2901. }
  2902. return $text . $tmp;
  2903. }
  2904. /**
  2905. * 对解密后的明文进行补位删除
  2906. * @param decrypted 解密后的明文
  2907. * @return 删除填充补位后的明文
  2908. */
  2909. function decode($text)
  2910. {
  2911. $pad = ord(substr($text, -1));
  2912. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  2913. $pad = 0;
  2914. }
  2915. return substr($text, 0, (strlen($text) - $pad));
  2916. }
  2917. }
  2918. /**
  2919. * Prpcrypt class
  2920. *
  2921. * 提供接收和推送给公众平台消息的加解密接口.
  2922. */
  2923. class Prpcrypt
  2924. {
  2925. public $key;
  2926. function Prpcrypt($k)
  2927. {
  2928. $this->key = base64_decode($k . "=");
  2929. }
  2930. /**
  2931. * 对明文进行加密
  2932. * @param string $text 需要加密的明文
  2933. * @return string 加密后的密文
  2934. */
  2935. public function encrypt($text, $appid)
  2936. {
  2937. try {
  2938. //获得16位随机字符串,填充到明文之前
  2939. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  2940. $text = $random . pack("N", strlen($text)) . $text . $appid;
  2941. // 网络字节序
  2942. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  2943. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2944. $iv = substr($this->key, 0, 16);
  2945. //使用自定义的填充方式对明文进行补位填充
  2946. $pkc_encoder = new PKCS7Encoder;
  2947. $text = $pkc_encoder->encode($text);
  2948. mcrypt_generic_init($module, $this->key, $iv);
  2949. //加密
  2950. $encrypted = mcrypt_generic($module, $text);
  2951. mcrypt_generic_deinit($module);
  2952. mcrypt_module_close($module);
  2953. // print(base64_encode($encrypted));
  2954. //使用BASE64对加密后的字符串进行编码
  2955. return array(ErrorCode::$OK, base64_encode($encrypted));
  2956. } catch (Exception $e) {
  2957. //print $e;
  2958. return array(ErrorCode::$EncryptAESError, null);
  2959. }
  2960. }
  2961. /**
  2962. * 对密文进行解密
  2963. * @param string $encrypted 需要解密的密文
  2964. * @return string 解密得到的明文
  2965. */
  2966. public function decrypt($encrypted, $appid)
  2967. {
  2968. try {
  2969. //使用BASE64对需要解密的字符串进行解码
  2970. $ciphertext_dec = base64_decode($encrypted);
  2971. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2972. $iv = substr($this->key, 0, 16);
  2973. mcrypt_generic_init($module, $this->key, $iv);
  2974. //解密
  2975. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  2976. mcrypt_generic_deinit($module);
  2977. mcrypt_module_close($module);
  2978. } catch (Exception $e) {
  2979. return array(ErrorCode::$DecryptAESError, null);
  2980. }
  2981. try {
  2982. //去除补位字符
  2983. $pkc_encoder = new PKCS7Encoder;
  2984. $result = $pkc_encoder->decode($decrypted);
  2985. //去除16位随机字符串,网络字节序和AppId
  2986. if (strlen($result) < 16)
  2987. return "";
  2988. $content = substr($result, 16, strlen($result));
  2989. $len_list = unpack("N", substr($content, 0, 4));
  2990. $xml_len = $len_list[1];
  2991. $xml_content = substr($content, 4, $xml_len);
  2992. $from_appid = substr($content, $xml_len + 4);
  2993. if (!$appid)
  2994. $appid = $from_appid;
  2995. //如果传入的appid是空的,则认为是订阅号,使用数据中提取出来的appid
  2996. } catch (Exception $e) {
  2997. //print $e;
  2998. return array(ErrorCode::$IllegalBuffer, null);
  2999. }
  3000. if ($from_appid != $appid)
  3001. return array(ErrorCode::$ValidateAppidError, null);
  3002. //不注释上边两行,避免传入appid是错误的情况
  3003. return array(0, $xml_content, $from_appid); //增加appid,为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
  3004. }
  3005. /**
  3006. * 随机生成16位字符串
  3007. * @return string 生成的字符串
  3008. */
  3009. function getRandomStr()
  3010. {
  3011. $str = "";
  3012. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  3013. $max = strlen($str_pol) - 1;
  3014. for ($i = 0; $i < 16; $i++) {
  3015. $str .= $str_pol[mt_rand(0, $max)];
  3016. }
  3017. return $str;
  3018. }
  3019. }
  3020. /**
  3021. * error code
  3022. * 仅用作类内部使用,不用于官方API接口的errCode码
  3023. */
  3024. class ErrorCode
  3025. {
  3026. public static $OK = 0;
  3027. public static $ValidateSignatureError = 40001;
  3028. public static $ParseXmlError = 40002;
  3029. public static $ComputeSignatureError = 40003;
  3030. public static $IllegalAesKey = 40004;
  3031. public static $ValidateAppidError = 40005;
  3032. public static $EncryptAESError = 40006;
  3033. public static $DecryptAESError = 40007;
  3034. public static $IllegalBuffer = 40008;
  3035. public static $EncodeBase64Error = 40009;
  3036. public static $DecodeBase64Error = 40010;
  3037. public static $GenReturnXmlError = 40011;
  3038. public static $errCode=array(
  3039. '0' => '处理成功',
  3040. '40001' => '校验签名失败',
  3041. '40002' => '解析xml失败',
  3042. '40003' => '计算签名失败',
  3043. '40004' => '不合法的AESKey',
  3044. '40005' => '校验AppID失败',
  3045. '40006' => 'AES加密失败',
  3046. '40007' => 'AES解密失败',
  3047. '40008' => '公众平台发送的xml不合法',
  3048. '40009' => 'Base64编码失败',
  3049. '40010' => 'Base64解码失败',
  3050. '40011' => '公众帐号生成回包xml失败'
  3051. );
  3052. public static function getErrText($err) {
  3053. if (isset(self::$errCode[$err])) {
  3054. return self::$errCode[$err];
  3055. }else {
  3056. return false;
  3057. };
  3058. }
  3059. }