wechat.class.php 110 KB

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