wechat.class.php 109 KB

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