Wechat.class.php 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628
  1. <?php
  2. namespace Org\Util;
  3. use Common\Cache\RedisCache;
  4. /**
  5. * 微信公众平台PHP-SDK, 官方API部分
  6. * @author dodge <dodgepudding@gmail.com>
  7. * @link https://github.com/dodgepudding/wechat-php-sdk
  8. * @version 1.2
  9. * usage:
  10. * $options = array(
  11. * 'token'=>'tokenaccesskey', //填写你设定的key
  12. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  13. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  14. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx' //填写高级调用功能的密钥
  15. * );
  16. * $weObj = new Wechat($options);
  17. * $weObj->valid();
  18. * $type = $weObj->getRev()->getRevType();
  19. * switch($type) {
  20. * case Wechat::MSGTYPE_TEXT:
  21. * $weObj->text("hello, I'm wechat")->reply();
  22. * exit;
  23. * break;
  24. * case Wechat::MSGTYPE_EVENT:
  25. * ....
  26. * break;
  27. * case Wechat::MSGTYPE_IMAGE:
  28. * ...
  29. * break;
  30. * default:
  31. * $weObj->text("help info")->reply();
  32. * }
  33. *
  34. * //获取菜单操作:
  35. * $menu = $weObj->getMenu();
  36. * //设置菜单
  37. * $newmenu = array(
  38. * "button"=>
  39. * array(
  40. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  41. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  42. * )
  43. * );
  44. * $result = $weObj->createMenu($newmenu);
  45. */
  46. class Wechat
  47. {
  48. const MSGTYPE_TEXT = 'text';
  49. const MSGTYPE_IMAGE = 'image';
  50. const MSGTYPE_LOCATION = 'location';
  51. const MSGTYPE_LINK = 'link';
  52. const MSGTYPE_EVENT = 'event';
  53. const MSGTYPE_MUSIC = 'music';
  54. const MSGTYPE_NEWS = 'news';
  55. const MSGTYPE_VOICE = 'voice';
  56. const MSGTYPE_VIDEO = 'video';
  57. const EVENT_SUBSCRIBE = 'subscribe'; //订阅
  58. const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消订阅
  59. const EVENT_SCAN = 'SCAN'; //扫描带参数二维码
  60. const EVENT_LOCATION = 'LOCATION'; //上报地理位置
  61. const EVENT_MENU_VIEW = 'VIEW'; //菜单 - 点击菜单跳转链接
  62. const EVENT_MENU_CLICK = 'CLICK'; //菜单 - 点击菜单拉取消息
  63. const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜单 - 扫码推事件(客户端跳URL)
  64. const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜单 - 扫码推事件(客户端不跳URL)
  65. const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜单 - 弹出系统拍照发图
  66. const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜单 - 弹出拍照或者相册发图
  67. const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜单 - 弹出微信相册发图器
  68. const EVENT_MENU_LOCATION = 'location_select'; //菜单 - 弹出地理位置选择器
  69. const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //发送结果 - 高级群发完成
  70. const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//发送结果 - 模板消息发送结果
  71. const EVENT_KF_SEESION_CREATE = 'kfcreatesession'; //多客服 - 接入会话
  72. const EVENT_KF_SEESION_CLOSE = 'kfclosesession'; //多客服 - 关闭会话
  73. const EVENT_KF_SEESION_SWITCH = 'kfswitchsession'; //多客服 - 转接会话
  74. const EVENT_CARD_PASS = 'card_pass_check'; //卡券 - 审核通过
  75. const EVENT_CARD_NOTPASS = 'card_not_pass_check'; //卡券 - 审核未通过
  76. const EVENT_CARD_USER_GET = 'user_get_card'; //卡券 - 用户领取卡券
  77. const EVENT_CARD_USER_DEL = 'user_del_card'; //卡券 - 用户删除卡券
  78. const EVENT_MERCHANT_ORDER = 'merchant_order'; //微信小店 - 订单付款通知
  79. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  80. const AUTH_URL = '/token?grant_type=client_credential&';
  81. const MENU_CREATE_URL = '/menu/create?';
  82. const MENU_GET_URL = '/menu/get?';
  83. const MENU_DELETE_URL = '/menu/delete?';
  84. const GET_TICKET_URL = '/ticket/getticket?';
  85. const CALLBACKSERVER_GET_URL = '/getcallbackip?';
  86. const QRCODE_CREATE_URL='/qrcode/create?';
  87. const QR_SCENE = 0;
  88. const QR_LIMIT_SCENE = 1;
  89. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  90. const SHORT_URL='/shorturl?';
  91. const USER_GET_URL='/user/get?';
  92. const USER_INFO_URL='/user/info?';
  93. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  94. const GROUP_GET_URL='/groups/get?';
  95. const USER_GROUP_URL='/groups/getid?';
  96. const GROUP_CREATE_URL='/groups/create?';
  97. const GROUP_UPDATE_URL='/groups/update?';
  98. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  99. const GROUP_MEMBER_BATCHUPDATE_URL='/groups/members/batchupdate?';
  100. const CUSTOM_SEND_URL='/message/custom/send?';
  101. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  102. const MASS_SEND_URL = '/message/mass/send?';
  103. const TEMPLATE_SET_INDUSTRY_URL = '/message/template/api_set_industry?';
  104. const TEMPLATE_ADD_TPL_URL = '/message/template/api_add_template?';
  105. const TEMPLATE_SEND_URL = '/message/template/send?';
  106. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  107. const MASS_DELETE_URL = '/message/mass/delete?';
  108. const MASS_PREVIEW_URL = '/message/mass/preview?';
  109. const MASS_QUERY_URL = '/message/mass/get?';
  110. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  111. const MEDIA_UPLOAD_URL = '/media/upload?';
  112. const MEDIA_UPLOADIMG_URL = '/media/uploadimg?';//图片上传接口
  113. const MEDIA_GET_URL = '/media/get?';
  114. const MEDIA_VIDEO_UPLOAD = '/media/uploadvideo?';
  115. const MEDIA_FOREVER_UPLOAD_URL = '/material/add_material?';
  116. const MEDIA_FOREVER_NEWS_UPLOAD_URL = '/material/add_news?';
  117. const MEDIA_FOREVER_NEWS_UPDATE_URL = '/material/update_news?';
  118. const MEDIA_FOREVER_GET_URL = '/material/get_material?';
  119. const MEDIA_FOREVER_DEL_URL = '/material/del_material?';
  120. const MEDIA_FOREVER_COUNT_URL = '/material/get_materialcount?';
  121. const MEDIA_FOREVER_BATCHGET_URL = '/material/batchget_material?';
  122. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  123. const OAUTH_AUTHORIZE_URL = '/authorize?';
  124. ///多客服相关地址
  125. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  126. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  127. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getonlinekflist?';
  128. const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com'; //以下API接口URL需要使用此前缀
  129. const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
  130. const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
  131. const OAUTH_USERINFO_URL = '/sns/userinfo?';
  132. const OAUTH_AUTH_URL = '/sns/auth?';
  133. ///多客服相关地址
  134. const CUSTOM_SESSION_CREATE = '/customservice/kfsession/create?';
  135. const CUSTOM_SESSION_CLOSE = '/customservice/kfsession/close?';
  136. const CUSTOM_SESSION_SWITCH = '/customservice/kfsession/switch?';
  137. const CUSTOM_SESSION_GET = '/customservice/kfsession/getsession?';
  138. const CUSTOM_SESSION_GET_LIST = '/customservice/kfsession/getsessionlist?';
  139. const CUSTOM_SESSION_GET_WAIT = '/customservice/kfsession/getwaitcase?';
  140. const CS_KF_ACCOUNT_ADD_URL = '/customservice/kfaccount/add?';
  141. const CS_KF_ACCOUNT_UPDATE_URL = '/customservice/kfaccount/update?';
  142. const CS_KF_ACCOUNT_DEL_URL = '/customservice/kfaccount/del?';
  143. const CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL = '/customservice/kfaccount/uploadheadimg?';
  144. ///卡券相关地址
  145. const CARD_CREATE = '/card/create?';
  146. const CARD_DELETE = '/card/delete?';
  147. const CARD_UPDATE = '/card/update?';
  148. const CARD_GET = '/card/get?';
  149. const CARD_BATCHGET = '/card/batchget?';
  150. const CARD_MODIFY_STOCK = '/card/modifystock?';
  151. const CARD_LOCATION_BATCHADD = '/card/location/batchadd?';
  152. const CARD_LOCATION_BATCHGET = '/card/location/batchget?';
  153. const CARD_GETCOLORS = '/card/getcolors?';
  154. const CARD_QRCODE_CREATE = '/card/qrcode/create?';
  155. const CARD_CODE_CONSUME = '/card/code/consume?';
  156. const CARD_CODE_DECRYPT = '/card/code/decrypt?';
  157. const CARD_CODE_GET = '/card/code/get?';
  158. const CARD_CODE_UPDATE = '/card/code/update?';
  159. const CARD_CODE_UNAVAILABLE = '/card/code/unavailable?';
  160. const CARD_TESTWHILELIST_SET = '/card/testwhitelist/set?';
  161. const CARD_MEETINGCARD_UPDATEUSER = '/card/meetingticket/updateuser?'; //更新会议门票
  162. const CARD_MEMBERCARD_ACTIVATE = '/card/membercard/activate?'; //激活会员卡
  163. const CARD_MEMBERCARD_UPDATEUSER = '/card/membercard/updateuser?'; //更新会员卡
  164. const CARD_MOVIETICKET_UPDATEUSER = '/card/movieticket/updateuser?'; //更新电影票(未加方法)
  165. const CARD_BOARDINGPASS_CHECKIN = '/card/boardingpass/checkin?'; //飞机票-在线选座(未加方法)
  166. const CARD_LUCKYMONEY_UPDATE = '/card/luckymoney/updateuserbalance?'; //更新红包金额
  167. const SEMANTIC_API_URL = '/semantic/semproxy/search?'; //语义理解
  168. ///数据分析接口
  169. static $DATACUBE_URL_ARR = array( //用户分析
  170. 'user' => array(
  171. 'summary' => '/datacube/getusersummary?', //获取用户增减数据(getusersummary)
  172. 'cumulate' => '/datacube/getusercumulate?', //获取累计用户数据(getusercumulate)
  173. ),
  174. 'article' => array( //图文分析
  175. 'summary' => '/datacube/getarticlesummary?', //获取图文群发每日数据(getarticlesummary)
  176. 'total' => '/datacube/getarticletotal?', //获取图文群发总数据(getarticletotal)
  177. 'read' => '/datacube/getuserread?', //获取图文统计数据(getuserread)
  178. 'readhour' => '/datacube/getuserreadhour?', //获取图文统计分时数据(getuserreadhour)
  179. 'share' => '/datacube/getusershare?', //获取图文分享转发数据(getusershare)
  180. 'sharehour' => '/datacube/getusersharehour?', //获取图文分享转发分时数据(getusersharehour)
  181. ),
  182. 'upstreammsg' => array( //消息分析
  183. 'summary' => '/datacube/getupstreammsg?', //获取消息发送概况数据(getupstreammsg)
  184. 'hour' => '/datacube/getupstreammsghour?', //获取消息分送分时数据(getupstreammsghour)
  185. 'week' => '/datacube/getupstreammsgweek?', //获取消息发送周数据(getupstreammsgweek)
  186. 'month' => '/datacube/getupstreammsgmonth?', //获取消息发送月数据(getupstreammsgmonth)
  187. 'dist' => '/datacube/getupstreammsgdist?', //获取消息发送分布数据(getupstreammsgdist)
  188. 'distweek' => '/datacube/getupstreammsgdistweek?', //获取消息发送分布周数据(getupstreammsgdistweek)
  189. 'distmonth' => '/datacube/getupstreammsgdistmonth?', //获取消息发送分布月数据(getupstreammsgdistmonth)
  190. ),
  191. 'interface' => array( //接口分析
  192. 'summary' => '/datacube/getinterfacesummary?', //获取接口分析数据(getinterfacesummary)
  193. 'summaryhour' => '/datacube/getinterfacesummaryhour?', //获取接口分析分时数据(getinterfacesummaryhour)
  194. )
  195. );
  196. ///微信摇一摇周边
  197. const SHAKEAROUND_DEVICE_APPLYID = '/shakearound/device/applyid?';//申请设备ID
  198. const SHAKEAROUND_DEVICE_UPDATE = '/shakearound/device/update?';//编辑设备信息
  199. const SHAKEAROUND_DEVICE_SEARCH = '/shakearound/device/search?';//查询设备列表
  200. const SHAKEAROUND_DEVICE_BINDLOCATION = '/shakearound/device/bindlocation?';//配置设备与门店ID的关系
  201. const SHAKEAROUND_DEVICE_BINDPAGE = '/shakearound/device/bindpage?';//配置设备与页面的绑定关系
  202. const SHAKEAROUND_MATERIAL_ADD = '/shakearound/material/add?';//上传摇一摇图片素材
  203. const SHAKEAROUND_PAGE_ADD = '/shakearound/page/add?';//增加页面
  204. const SHAKEAROUND_PAGE_UPDATE = '/shakearound/page/update?';//编辑页面
  205. const SHAKEAROUND_PAGE_SEARCH = '/shakearound/page/search?';//查询页面列表
  206. const SHAKEAROUND_PAGE_DELETE = '/shakearound/page/delete?';//删除页面
  207. const SHAKEAROUND_USER_GETSHAKEINFO = '/shakearound/user/getshakeinfo?';//获取摇周边的设备及用户信息
  208. const SHAKEAROUND_STATISTICS_DEVICE = '/shakearound/statistics/device?';//以设备为维度的数据统计接口
  209. const SHAKEAROUND_STATISTICS_PAGE = '/shakearound/statistics/page?';//以页面为维度的数据统计接口
  210. ///微信小店相关接口
  211. const MERCHANT_ORDER_GETBYID = '/merchant/order/getbyid?';//根据订单ID获取订单详情
  212. const MERCHANT_ORDER_GETBYFILTER = '/merchant/order/getbyfilter?';//根据订单状态/创建时间获取订单详情
  213. const MERCHANT_ORDER_SETDELIVERY = '/merchant/order/setdelivery?';//设置订单发货信息
  214. const MERCHANT_ORDER_CLOSE = '/merchant/order/close?';//关闭订单
  215. private $token;
  216. private $encodingAesKey;
  217. private $encrypt_type;
  218. private $appid;
  219. private $appsecret;
  220. private $access_token;
  221. private $jsapi_ticket;
  222. private $api_ticket;
  223. private $user_token;
  224. private $partnerid;
  225. private $partnerkey;
  226. private $paysignkey;
  227. private $postxml;
  228. private $_msg;
  229. private $_funcflag = false;
  230. private $_receive;
  231. private $_text_filter = true;
  232. public $debug = false;
  233. public $errCode = 40001;
  234. public $errMsg = "no access";
  235. public $logcallback;
  236. public function __construct($options)
  237. {
  238. $this->token = isset($options['token'])?$options['token']:'';
  239. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  240. $this->appid = isset($options['appid'])?$options['appid']:'';
  241. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  242. $this->debug = isset($options['debug'])?$options['debug']:false;
  243. $this->logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  244. }
  245. /**
  246. * For weixin server validation
  247. */
  248. private function checkSignature($str='')
  249. {
  250. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  251. $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密验证则用加密验证段
  252. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  253. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  254. $token = $this->token;
  255. $tmpArr = array($token, $timestamp, $nonce,$str);
  256. sort($tmpArr, SORT_STRING);
  257. $tmpStr = implode( $tmpArr );
  258. $tmpStr = sha1( $tmpStr );
  259. if( $tmpStr == $signature ){
  260. return true;
  261. }else{
  262. return false;
  263. }
  264. }
  265. /**
  266. * For weixin server validation
  267. * @param bool $return 是否返回
  268. */
  269. public function valid($return=false)
  270. {
  271. $encryptStr="";
  272. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  273. $postStr = file_get_contents("php://input");
  274. $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  275. $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"]: '';
  276. if ($this->encrypt_type == 'aes') { //aes加密
  277. $this->log($postStr);
  278. $encryptStr = $array['Encrypt'];
  279. $pc = new Prpcrypt($this->encodingAesKey);
  280. $array = $pc->decrypt($encryptStr,$this->appid);
  281. if (!isset($array[0]) || ($array[0] != 0)) {
  282. if (!$return) {
  283. die('decrypt error!');
  284. } else {
  285. return false;
  286. }
  287. }
  288. $this->postxml = $array[1];
  289. if (!$this->appid)
  290. $this->appid = $array[2];//为了没有appid的订阅号。
  291. } else {
  292. $this->postxml = $postStr;
  293. }
  294. } elseif (isset($_GET["echostr"])) {
  295. $echoStr = $_GET["echostr"];
  296. if ($return) {
  297. if ($this->checkSignature())
  298. return $echoStr;
  299. else
  300. return false;
  301. } else {
  302. if ($this->checkSignature())
  303. die($echoStr);
  304. else
  305. die('no access');
  306. }
  307. }
  308. if (!$this->checkSignature($encryptStr)) {
  309. if ($return)
  310. return false;
  311. else
  312. die('no access');
  313. }
  314. return true;
  315. }
  316. /**
  317. * 设置发送消息
  318. * @param array $msg 消息数组
  319. * @param bool $append 是否在原消息数组追加
  320. */
  321. public function Message($msg = '',$append = false){
  322. if (is_null($msg)) {
  323. $this->_msg =array();
  324. }elseif (is_array($msg)) {
  325. if ($append)
  326. $this->_msg = array_merge($this->_msg,$msg);
  327. else
  328. $this->_msg = $msg;
  329. return $this->_msg;
  330. } else {
  331. return $this->_msg;
  332. }
  333. }
  334. /**
  335. * 设置消息的星标标志,官方已取消对此功能的支持
  336. */
  337. public function setFuncFlag($flag) {
  338. $this->_funcflag = $flag;
  339. return $this;
  340. }
  341. /**
  342. * 日志记录,可被重载。
  343. * @param mixed $log 输入日志
  344. * @return mixed
  345. */
  346. public function log($log){
  347. if ($this->debug && function_exists($this->logcallback)) {
  348. if (is_array($log)) $log = print_r($log,true);
  349. return call_user_func($this->logcallback,$log,'INFO');
  350. }
  351. }
  352. /**
  353. * 获取微信服务器发来的信息
  354. */
  355. public function getRev()
  356. {
  357. if ($this->_receive) return $this;
  358. $postStr = !empty($this->postxml)?$this->postxml:file_get_contents("php://input");
  359. //兼顾使用明文又不想调用valid()方法的情况
  360. $this->log($postStr);
  361. if (!empty($postStr)) {
  362. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  363. }
  364. return $this;
  365. }
  366. /**
  367. * 获取微信服务器发来的信息
  368. */
  369. public function getRevData()
  370. {
  371. return $this->_receive;
  372. }
  373. /**
  374. * 获取消息发送者
  375. */
  376. public function getRevFrom() {
  377. if (isset($this->_receive['FromUserName']))
  378. return $this->_receive['FromUserName'];
  379. else
  380. return false;
  381. }
  382. /**
  383. * 获取消息接受者
  384. */
  385. public function getRevTo() {
  386. if (isset($this->_receive['ToUserName']))
  387. return $this->_receive['ToUserName'];
  388. else
  389. return false;
  390. }
  391. /**
  392. * 获取接收消息的类型
  393. */
  394. public function getRevType() {
  395. if (isset($this->_receive['MsgType']))
  396. return $this->_receive['MsgType'];
  397. else
  398. return false;
  399. }
  400. /**
  401. * 获取消息ID
  402. */
  403. public function getRevID() {
  404. if (isset($this->_receive['MsgId']))
  405. return $this->_receive['MsgId'];
  406. else
  407. return false;
  408. }
  409. /**
  410. * 获取消息发送时间
  411. */
  412. public function getRevCtime() {
  413. if (isset($this->_receive['CreateTime']))
  414. return $this->_receive['CreateTime'];
  415. else
  416. return false;
  417. }
  418. /**
  419. * 获取接收消息内容正文
  420. */
  421. public function getRevContent(){
  422. if (isset($this->_receive['Content']))
  423. return $this->_receive['Content'];
  424. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  425. return $this->_receive['Recognition'];
  426. else
  427. return false;
  428. }
  429. /**
  430. * 获取接收消息图片
  431. */
  432. public function getRevPic(){
  433. if (isset($this->_receive['PicUrl']))
  434. return array(
  435. 'mediaid'=>$this->_receive['MediaId'],
  436. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  437. );
  438. else
  439. return false;
  440. }
  441. /**
  442. * 获取接收消息链接
  443. */
  444. public function getRevLink(){
  445. if (isset($this->_receive['Url'])){
  446. return array(
  447. 'url'=>$this->_receive['Url'],
  448. 'title'=>$this->_receive['Title'],
  449. 'description'=>$this->_receive['Description']
  450. );
  451. } else
  452. return false;
  453. }
  454. /**
  455. * 获取接收地理位置
  456. */
  457. public function getRevGeo(){
  458. if (isset($this->_receive['Location_X'])){
  459. return array(
  460. 'x'=>$this->_receive['Location_X'],
  461. 'y'=>$this->_receive['Location_Y'],
  462. 'scale'=>$this->_receive['Scale'],
  463. 'label'=>$this->_receive['Label']
  464. );
  465. } else
  466. return false;
  467. }
  468. /**
  469. * 获取上报地理位置事件
  470. */
  471. public function getRevEventGeo(){
  472. if (isset($this->_receive['Latitude'])){
  473. return array(
  474. 'x'=>$this->_receive['Latitude'],
  475. 'y'=>$this->_receive['Longitude'],
  476. 'precision'=>$this->_receive['Precision'],
  477. );
  478. } else
  479. return false;
  480. }
  481. /**
  482. * 获取接收事件推送
  483. */
  484. public function getRevEvent(){
  485. if (isset($this->_receive['Event'])){
  486. $array['event'] = $this->_receive['Event'];
  487. }
  488. if (isset($this->_receive['EventKey'])){
  489. $array['key'] = $this->_receive['EventKey'];
  490. }
  491. if (isset($array) && count($array) > 0) {
  492. return $array;
  493. } else {
  494. return false;
  495. }
  496. }
  497. /**
  498. * 获取自定义菜单的扫码推事件信息
  499. *
  500. * 事件类型为以下两种时则调用此方法有效
  501. * Event 事件类型,scancode_push
  502. * Event 事件类型,scancode_waitmsg
  503. *
  504. * @return: array | false
  505. * array (
  506. * 'ScanType'=>'qrcode',
  507. * 'ScanResult'=>'123123'
  508. * )
  509. */
  510. public function getRevScanInfo(){
  511. if (isset($this->_receive['ScanCodeInfo'])){
  512. if (!is_array($this->_receive['ScanCodeInfo'])) {
  513. $array=(array)$this->_receive['ScanCodeInfo'];
  514. $this->_receive['ScanCodeInfo']=$array;
  515. }else {
  516. $array=$this->_receive['ScanCodeInfo'];
  517. }
  518. }
  519. if (isset($array) && count($array) > 0) {
  520. return $array;
  521. } else {
  522. return false;
  523. }
  524. }
  525. /**
  526. * 获取自定义菜单的图片发送事件信息
  527. *
  528. * 事件类型为以下三种时则调用此方法有效
  529. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  530. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  531. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  532. *
  533. * @return: array | false
  534. * array (
  535. * 'Count' => '2',
  536. * 'PicList' =>array (
  537. * 'item' =>array (
  538. * 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
  539. * 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
  540. * ),
  541. * ),
  542. * )
  543. *
  544. */
  545. public function getRevSendPicsInfo(){
  546. if (isset($this->_receive['SendPicsInfo'])){
  547. if (!is_array($this->_receive['SendPicsInfo'])) {
  548. $array=(array)$this->_receive['SendPicsInfo'];
  549. if (isset($array['PicList'])){
  550. $array['PicList']=(array)$array['PicList'];
  551. $item=$array['PicList']['item'];
  552. $array['PicList']['item']=array();
  553. foreach ( $item as $key => $value ){
  554. $array['PicList']['item'][$key]=(array)$value;
  555. }
  556. }
  557. $this->_receive['SendPicsInfo']=$array;
  558. } else {
  559. $array=$this->_receive['SendPicsInfo'];
  560. }
  561. }
  562. if (isset($array) && count($array) > 0) {
  563. return $array;
  564. } else {
  565. return false;
  566. }
  567. }
  568. /**
  569. * 获取自定义菜单的地理位置选择器事件推送
  570. *
  571. * 事件类型为以下时则可以调用此方法有效
  572. * Event 事件类型,location_select 弹出地理位置选择器的事件推送
  573. *
  574. * @return: array | false
  575. * array (
  576. * 'Location_X' => '33.731655000061',
  577. * 'Location_Y' => '113.29955200008047',
  578. * 'Scale' => '16',
  579. * 'Label' => '某某市某某区某某路',
  580. * 'Poiname' => '',
  581. * )
  582. *
  583. */
  584. public function getRevSendGeoInfo(){
  585. if (isset($this->_receive['SendLocationInfo'])){
  586. if (!is_array($this->_receive['SendLocationInfo'])) {
  587. $array=(array)$this->_receive['SendLocationInfo'];
  588. if (empty($array['Poiname'])) {
  589. $array['Poiname']="";
  590. }
  591. if (empty($array['Label'])) {
  592. $array['Label']="";
  593. }
  594. $this->_receive['SendLocationInfo']=$array;
  595. } else {
  596. $array=$this->_receive['SendLocationInfo'];
  597. }
  598. }
  599. if (isset($array) && count($array) > 0) {
  600. return $array;
  601. } else {
  602. return false;
  603. }
  604. }
  605. /**
  606. * 获取接收语音推送
  607. */
  608. public function getRevVoice(){
  609. if (isset($this->_receive['MediaId'])){
  610. return array(
  611. 'mediaid'=>$this->_receive['MediaId'],
  612. 'format'=>$this->_receive['Format'],
  613. );
  614. } else
  615. return false;
  616. }
  617. /**
  618. * 获取接收视频推送
  619. */
  620. public function getRevVideo(){
  621. if (isset($this->_receive['MediaId'])){
  622. return array(
  623. 'mediaid'=>$this->_receive['MediaId'],
  624. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  625. );
  626. } else
  627. return false;
  628. }
  629. /**
  630. * 获取接收TICKET
  631. */
  632. public function getRevTicket(){
  633. if (isset($this->_receive['Ticket'])){
  634. return $this->_receive['Ticket'];
  635. } else
  636. return false;
  637. }
  638. /**
  639. * 获取二维码的场景值
  640. */
  641. public function getRevSceneId (){
  642. if (isset($this->_receive['EventKey'])){
  643. return str_replace('qrscene_','',$this->_receive['EventKey']);
  644. } else{
  645. return false;
  646. }
  647. }
  648. /**
  649. * 获取主动推送的消息ID
  650. * 经过验证,这个和普通的消息MsgId不一样
  651. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH
  652. */
  653. public function getRevTplMsgID(){
  654. if (isset($this->_receive['MsgID'])){
  655. return $this->_receive['MsgID'];
  656. } else
  657. return false;
  658. }
  659. /**
  660. * 获取模板消息发送状态
  661. */
  662. public function getRevStatus(){
  663. if (isset($this->_receive['Status'])){
  664. return $this->_receive['Status'];
  665. } else
  666. return false;
  667. }
  668. /**
  669. * 获取群发或模板消息发送结果
  670. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH,即高级群发/模板消息
  671. */
  672. public function getRevResult(){
  673. if (isset($this->_receive['Status'])) //发送是否成功,具体的返回值请参考 高级群发/模板消息 的事件推送说明
  674. $array['Status'] = $this->_receive['Status'];
  675. if (isset($this->_receive['MsgID'])) //发送的消息id
  676. $array['MsgID'] = $this->_receive['MsgID'];
  677. //以下仅当群发消息时才会有的事件内容
  678. if (isset($this->_receive['TotalCount'])) //分组或openid列表内粉丝数量
  679. $array['TotalCount'] = $this->_receive['TotalCount'];
  680. if (isset($this->_receive['FilterCount'])) //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数
  681. $array['FilterCount'] = $this->_receive['FilterCount'];
  682. if (isset($this->_receive['SentCount'])) //发送成功的粉丝数
  683. $array['SentCount'] = $this->_receive['SentCount'];
  684. if (isset($this->_receive['ErrorCount'])) //发送失败的粉丝数
  685. $array['ErrorCount'] = $this->_receive['ErrorCount'];
  686. if (isset($array) && count($array) > 0) {
  687. return $array;
  688. } else {
  689. return false;
  690. }
  691. }
  692. /**
  693. * 获取多客服会话状态推送事件 - 接入会话
  694. * 当Event为 kfcreatesession 即接入会话
  695. * @return string | boolean 返回分配到的客服
  696. */
  697. public function getRevKFCreate(){
  698. if (isset($this->_receive['KfAccount'])){
  699. return $this->_receive['KfAccount'];
  700. } else
  701. return false;
  702. }
  703. /**
  704. * 获取多客服会话状态推送事件 - 关闭会话
  705. * 当Event为 kfclosesession 即关闭会话
  706. * @return string | boolean 返回分配到的客服
  707. */
  708. public function getRevKFClose(){
  709. if (isset($this->_receive['KfAccount'])){
  710. return $this->_receive['KfAccount'];
  711. } else
  712. return false;
  713. }
  714. /**
  715. * 获取多客服会话状态推送事件 - 转接会话
  716. * 当Event为 kfswitchsession 即转接会话
  717. * @return array | boolean 返回分配到的客服
  718. * {
  719. * 'FromKfAccount' => '', //原接入客服
  720. * 'ToKfAccount' => '' //转接到客服
  721. * }
  722. */
  723. public function getRevKFSwitch(){
  724. if (isset($this->_receive['FromKfAccount'])) //原接入客服
  725. $array['FromKfAccount'] = $this->_receive['FromKfAccount'];
  726. if (isset($this->_receive['ToKfAccount'])) //转接到客服
  727. $array['ToKfAccount'] = $this->_receive['ToKfAccount'];
  728. if (isset($array) && count($array) > 0) {
  729. return $array;
  730. } else {
  731. return false;
  732. }
  733. }
  734. /**
  735. * 获取卡券事件推送 - 卡卷审核是否通过
  736. * 当Event为 card_pass_check(审核通过) 或 card_not_pass_check(未通过)
  737. * @return string|boolean 返回卡券ID
  738. */
  739. public function getRevCardPass(){
  740. if (isset($this->_receive['CardId']))
  741. return $this->_receive['CardId'];
  742. else
  743. return false;
  744. }
  745. /**
  746. * 获取卡券事件推送 - 领取卡券
  747. * 当Event为 user_get_card(用户领取卡券)
  748. * @return array|boolean
  749. */
  750. public function getRevCardGet(){
  751. if (isset($this->_receive['CardId'])) //卡券 ID
  752. $array['CardId'] = $this->_receive['CardId'];
  753. if (isset($this->_receive['IsGiveByFriend'])) //是否为转赠,1 代表是,0 代表否。
  754. $array['IsGiveByFriend'] = $this->_receive['IsGiveByFriend'];
  755. $array['OldUserCardCode'] = $this->_receive['OldUserCardCode'];
  756. if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列号。自定义 code 及非自定义 code的卡券被领取后都支持事件推送。
  757. $array['UserCardCode'] = $this->_receive['UserCardCode'];
  758. if (isset($array) && count($array) > 0) {
  759. return $array;
  760. } else {
  761. return false;
  762. }
  763. }
  764. /**
  765. * 获取卡券事件推送 - 删除卡券
  766. * 当Event为 user_del_card(用户删除卡券)
  767. * @return array|boolean
  768. */
  769. public function getRevCardDel(){
  770. if (isset($this->_receive['CardId'])) //卡券 ID
  771. $array['CardId'] = $this->_receive['CardId'];
  772. if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列号。自定义 code 及非自定义 code的卡券被领取后都支持事件推送。
  773. $array['UserCardCode'] = $this->_receive['UserCardCode'];
  774. if (isset($array) && count($array) > 0) {
  775. return $array;
  776. } else {
  777. return false;
  778. }
  779. }
  780. /**
  781. * 获取订单ID - 订单付款通知
  782. * 当Event为 merchant_order(订单付款通知)
  783. * @return orderId|boolean
  784. */
  785. public function getRevOrderId(){
  786. if (isset($this->_receive['OrderId'])) //订单 ID
  787. return $this->_receive['OrderId'];
  788. else
  789. return false;
  790. }
  791. public static function xmlSafeStr($str)
  792. {
  793. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  794. }
  795. /**
  796. * 数据XML编码
  797. * @param mixed $data 数据
  798. * @return string
  799. */
  800. public static function data_to_xml($data) {
  801. $xml = '';
  802. foreach ($data as $key => $val) {
  803. is_numeric($key) && $key = "item id=\"$key\"";
  804. $xml .= "<$key>";
  805. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  806. list($key, ) = explode(' ', $key);
  807. $xml .= "</$key>";
  808. }
  809. return $xml;
  810. }
  811. /**
  812. * XML编码
  813. * @param mixed $data 数据
  814. * @param string $root 根节点名
  815. * @param string $item 数字索引的子节点名
  816. * @param string $attr 根节点属性
  817. * @param string $id 数字索引子节点key转换的属性名
  818. * @param string $encoding 数据编码
  819. * @return string
  820. */
  821. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  822. if(is_array($attr)){
  823. $_attr = array();
  824. foreach ($attr as $key => $value) {
  825. $_attr[] = "{$key}=\"{$value}\"";
  826. }
  827. $attr = implode(' ', $_attr);
  828. }
  829. $attr = trim($attr);
  830. $attr = empty($attr) ? '' : " {$attr}";
  831. $xml = "<{$root}{$attr}>";
  832. $xml .= self::data_to_xml($data, $item, $id);
  833. $xml .= "</{$root}>";
  834. return $xml;
  835. }
  836. /**
  837. * 过滤文字回复\r\n换行符
  838. * @param string $text
  839. * @return string|mixed
  840. */
  841. private function _auto_text_filter($text) {
  842. if (!$this->_text_filter) return $text;
  843. return str_replace("\r\n", "\n", $text);
  844. }
  845. /**
  846. * 设置回复消息
  847. * Example: $obj->text('hello')->reply();
  848. * @param string $text
  849. */
  850. public function text($text='')
  851. {
  852. $FuncFlag = $this->_funcflag ? 1 : 0;
  853. $msg = array(
  854. 'ToUserName' => $this->getRevFrom(),
  855. 'FromUserName'=>$this->getRevTo(),
  856. 'MsgType'=>self::MSGTYPE_TEXT,
  857. 'Content'=>$this->_auto_text_filter($text),
  858. 'CreateTime'=>time(),
  859. 'FuncFlag'=>$FuncFlag
  860. );
  861. $this->Message($msg);
  862. return $this;
  863. }
  864. /**
  865. * 设置回复消息
  866. * Example: $obj->image('media_id')->reply();
  867. * @param string $mediaid
  868. */
  869. public function image($mediaid='')
  870. {
  871. $FuncFlag = $this->_funcflag ? 1 : 0;
  872. $msg = array(
  873. 'ToUserName' => $this->getRevFrom(),
  874. 'FromUserName'=>$this->getRevTo(),
  875. 'MsgType'=>self::MSGTYPE_IMAGE,
  876. 'Image'=>array('MediaId'=>$mediaid),
  877. 'CreateTime'=>time(),
  878. 'FuncFlag'=>$FuncFlag
  879. );
  880. $this->Message($msg);
  881. return $this;
  882. }
  883. /**
  884. * 设置回复消息
  885. * Example: $obj->voice('media_id')->reply();
  886. * @param string $mediaid
  887. */
  888. public function voice($mediaid='')
  889. {
  890. $FuncFlag = $this->_funcflag ? 1 : 0;
  891. $msg = array(
  892. 'ToUserName' => $this->getRevFrom(),
  893. 'FromUserName'=>$this->getRevTo(),
  894. 'MsgType'=>self::MSGTYPE_VOICE,
  895. 'Voice'=>array('MediaId'=>$mediaid),
  896. 'CreateTime'=>time(),
  897. 'FuncFlag'=>$FuncFlag
  898. );
  899. $this->Message($msg);
  900. return $this;
  901. }
  902. /**
  903. * 设置回复消息
  904. * Example: $obj->video('media_id','title','description')->reply();
  905. * @param string $mediaid
  906. */
  907. public function video($mediaid='',$title='',$description='')
  908. {
  909. $FuncFlag = $this->_funcflag ? 1 : 0;
  910. $msg = array(
  911. 'ToUserName' => $this->getRevFrom(),
  912. 'FromUserName'=>$this->getRevTo(),
  913. 'MsgType'=>self::MSGTYPE_VIDEO,
  914. 'Video'=>array(
  915. 'MediaId'=>$mediaid,
  916. 'Title'=>$title,
  917. 'Description'=>$description
  918. ),
  919. 'CreateTime'=>time(),
  920. 'FuncFlag'=>$FuncFlag
  921. );
  922. $this->Message($msg);
  923. return $this;
  924. }
  925. /**
  926. * 设置回复音乐
  927. * @param string $title
  928. * @param string $desc
  929. * @param string $musicurl
  930. * @param string $hgmusicurl
  931. * @param string $thumbmediaid 音乐图片缩略图的媒体id,非必须
  932. */
  933. public function music($title,$desc,$musicurl,$hgmusicurl='',$thumbmediaid='') {
  934. $FuncFlag = $this->_funcflag ? 1 : 0;
  935. $msg = array(
  936. 'ToUserName' => $this->getRevFrom(),
  937. 'FromUserName'=>$this->getRevTo(),
  938. 'CreateTime'=>time(),
  939. 'MsgType'=>self::MSGTYPE_MUSIC,
  940. 'Music'=>array(
  941. 'Title'=>$title,
  942. 'Description'=>$desc,
  943. 'MusicUrl'=>$musicurl,
  944. 'HQMusicUrl'=>$hgmusicurl
  945. ),
  946. 'FuncFlag'=>$FuncFlag
  947. );
  948. if ($thumbmediaid) {
  949. $msg['Music']['ThumbMediaId'] = $thumbmediaid;
  950. }
  951. $this->Message($msg);
  952. return $this;
  953. }
  954. /**
  955. * 设置回复图文
  956. * @param array $newsData
  957. * 数组结构:
  958. * array(
  959. * "0"=>array(
  960. * 'Title'=>'msg title',
  961. * 'Description'=>'summary text',
  962. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  963. * 'Url'=>'http://www.domain.com/1.html'
  964. * ),
  965. * "1"=>....
  966. * )
  967. */
  968. public function news($newsData=array())
  969. {
  970. $FuncFlag = $this->_funcflag ? 1 : 0;
  971. $count = count($newsData);
  972. $msg = array(
  973. 'ToUserName' => $this->getRevFrom(),
  974. 'FromUserName'=>$this->getRevTo(),
  975. 'MsgType'=>self::MSGTYPE_NEWS,
  976. 'CreateTime'=>time(),
  977. 'ArticleCount'=>$count,
  978. 'Articles'=>$newsData,
  979. 'FuncFlag'=>$FuncFlag
  980. );
  981. $this->Message($msg);
  982. return $this;
  983. }
  984. /**
  985. *
  986. * 回复微信服务器, 此函数支持链式操作
  987. * Example: $this->text('msg tips')->reply();
  988. * @param string $msg 要发送的信息, 默认取$this->_msg
  989. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  990. */
  991. public function reply($msg=array(),$return = false)
  992. {
  993. if (empty($msg)) {
  994. if (empty($this->_msg)) //防止不先设置回复内容,直接调用reply方法导致异常
  995. return false;
  996. $msg = $this->_msg;
  997. }
  998. $xmldata= $this->xml_encode($msg);
  999. $this->log($xmldata);
  1000. if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式
  1001. $pc = new Prpcrypt($this->encodingAesKey);
  1002. $array = $pc->encrypt($xmldata, $this->appid);
  1003. $ret = $array[0];
  1004. if ($ret != 0) {
  1005. $this->log('encrypt err!');
  1006. return false;
  1007. }
  1008. $timestamp = time();
  1009. $nonce = rand(77,999)*rand(605,888)*rand(11,99);
  1010. $encrypt = $array[1];
  1011. $tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
  1012. sort($tmpArr, SORT_STRING);
  1013. $signature = implode($tmpArr);
  1014. $signature = sha1($signature);
  1015. $xmldata = $this->generate($encrypt, $signature, $timestamp, $nonce);
  1016. $this->log($xmldata);
  1017. }
  1018. if ($return)
  1019. return $xmldata;
  1020. else
  1021. echo $xmldata;
  1022. }
  1023. /**
  1024. * xml格式加密,仅请求为加密方式时再用
  1025. */
  1026. private function generate($encrypt, $signature, $timestamp, $nonce)
  1027. {
  1028. //格式化加密信息
  1029. $format = "<xml>
  1030. <Encrypt><![CDATA[%s]]></Encrypt>
  1031. <MsgSignature><![CDATA[%s]]></MsgSignature>
  1032. <TimeStamp>%s</TimeStamp>
  1033. <Nonce><![CDATA[%s]]></Nonce>
  1034. </xml>";
  1035. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  1036. }
  1037. /**
  1038. * GET 请求
  1039. * @param string $url
  1040. */
  1041. private function http_get($url){
  1042. $oCurl = curl_init();
  1043. $this_header = array(
  1044. "content-type: application/x-www-form-urlencoded; charset=UTF-8"
  1045. );
  1046. curl_setopt($oCurl,CURLOPT_HTTPHEADER,$this_header);
  1047. if(stripos($url,"https://")!==FALSE){
  1048. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  1049. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  1050. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  1051. }
  1052. curl_setopt($oCurl, CURLOPT_URL, $url);
  1053. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  1054. $sContent = curl_exec($oCurl);
  1055. $aStatus = curl_getinfo($oCurl);
  1056. curl_close($oCurl);
  1057. if(intval($aStatus["http_code"])==200){
  1058. return $sContent;
  1059. }else{
  1060. return false;
  1061. }
  1062. }
  1063. /**
  1064. * POST 请求
  1065. * @param string $url
  1066. * @param array $param
  1067. * @param boolean $post_file 是否文件上传
  1068. * @return string content
  1069. */
  1070. private function http_post($url,$param,$post_file=false){
  1071. $oCurl = curl_init();
  1072. $this_header = array(
  1073. "content-type: application/x-www-form-urlencoded; charset=UTF-8"
  1074. );
  1075. curl_setopt($oCurl,CURLOPT_HTTPHEADER,$this_header);
  1076. if(stripos($url,"https://")!==FALSE){
  1077. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  1078. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  1079. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  1080. }
  1081. if (is_string($param) || $post_file) {
  1082. $strPOST = $param;
  1083. } else {
  1084. $aPOST = array();
  1085. foreach($param as $key=>$val){
  1086. $aPOST[] = $key."=".urlencode($val);
  1087. }
  1088. $strPOST = join("&", $aPOST);
  1089. }
  1090. curl_setopt($oCurl, CURLOPT_URL, $url);
  1091. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  1092. curl_setopt($oCurl, CURLOPT_POST,true);
  1093. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  1094. $sContent = curl_exec($oCurl);
  1095. $aStatus = curl_getinfo($oCurl);
  1096. curl_close($oCurl);
  1097. if(intval($aStatus["http_code"])==200){
  1098. return $sContent;
  1099. }else{
  1100. return false;
  1101. }
  1102. }
  1103. /**
  1104. * 设置缓存,按需重载
  1105. * @param string $cachename
  1106. * @param mixed $value
  1107. * @param int $expired
  1108. * @return boolean
  1109. */
  1110. public function setCache($cachename,$value,$expired){
  1111. $redis_cache = new RedisCache();
  1112. $redis_cache->set($cachename,$value,$expired);
  1113. }
  1114. /**
  1115. * 获取缓存,按需重载
  1116. * @param string $cachename
  1117. * @return mixed
  1118. */
  1119. public function getCache($cachename){
  1120. $redis_cache = new RedisCache();
  1121. return $redis_cache->get($cachename);
  1122. }
  1123. /**
  1124. * 清除缓存,按需重载
  1125. * @param string $cachename
  1126. * @return boolean
  1127. */
  1128. public function removeCache($cachename){
  1129. $redis_cache = new RedisCache();
  1130. return $redis_cache->rm($cachename);
  1131. }
  1132. /**
  1133. * 获取access_token
  1134. * @param string $appid 如在类初始化时已提供,则可为空
  1135. * @param string $appsecret 如在类初始化时已提供,则可为空
  1136. * @param string $token 手动指定access_token,非必要情况不建议用
  1137. */
  1138. public function checkAuth($appid='',$appsecret='',$token=''){
  1139. if (!$appid || !$appsecret) {
  1140. $appid = $this->appid;
  1141. $appsecret = $this->appsecret;
  1142. }
  1143. if ($token) { //手动指定token,优先使用
  1144. $this->access_token=$token;
  1145. return $this->access_token;
  1146. }
  1147. $authname = 'wechat_access_token'.$appid;
  1148. if ($rs = $this->getCache($authname)) {
  1149. $this->access_token = $rs;
  1150. return $rs;
  1151. }
  1152. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  1153. if ($result)
  1154. {
  1155. $json = json_decode($result,true);
  1156. if (!$json || isset($json['errcode'])) {
  1157. $this->errCode = $json['errcode'];
  1158. $this->errMsg = $json['errmsg'];
  1159. return false;
  1160. }
  1161. $this->access_token = $json['access_token'];
  1162. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1163. $this->setCache($authname,$this->access_token,$expire);
  1164. return $this->access_token;
  1165. }
  1166. return false;
  1167. }
  1168. /**
  1169. * 删除验证数据
  1170. * @param string $appid
  1171. */
  1172. public function resetAuth($appid=''){
  1173. if (!$appid) $appid = $this->appid;
  1174. $this->access_token = '';
  1175. $authname = 'wechat_access_token'.$appid;
  1176. $this->removeCache($authname);
  1177. return true;
  1178. }
  1179. /**
  1180. * 删除JSAPI授权TICKET
  1181. * @param string $appid 用于多个appid时使用
  1182. */
  1183. public function resetJsTicket($appid=''){
  1184. if (!$appid) $appid = $this->appid;
  1185. $this->jsapi_ticket = '';
  1186. $authname = 'wechat_jsapi_ticket'.$appid;
  1187. $this->removeCache($authname);
  1188. return true;
  1189. }
  1190. /**
  1191. * 获取JSAPI授权TICKET
  1192. * @param string $appid 用于多个appid时使用,可空
  1193. * @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
  1194. */
  1195. public function getJsTicket($appid='',$jsapi_ticket=''){
  1196. if (!$this->access_token && !$this->checkAuth()) return false;
  1197. if (!$appid) $appid = $this->appid;
  1198. if ($jsapi_ticket) { //手动指定token,优先使用
  1199. $this->jsapi_ticket = $jsapi_ticket;
  1200. return $this->jsapi_ticket;
  1201. }
  1202. $authname = 'wechat_jsapi_ticket'.$appid;
  1203. if ($rs = $this->getCache($authname)) {
  1204. $this->jsapi_ticket = $rs;
  1205. return $rs;
  1206. }
  1207. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=jsapi');
  1208. if ($result)
  1209. {
  1210. $json = json_decode($result,true);
  1211. if (!$json || !empty($json['errcode'])) {
  1212. $this->errCode = $json['errcode'];
  1213. $this->errMsg = $json['errmsg'];
  1214. return false;
  1215. }
  1216. $this->jsapi_ticket = $json['ticket'];
  1217. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1218. $this->setCache($authname,$this->jsapi_ticket,$expire);
  1219. return $this->jsapi_ticket;
  1220. }
  1221. return false;
  1222. }
  1223. /**
  1224. * 获取JsApi使用签名
  1225. * @param string $url 网页的URL,自动处理#及其后面部分
  1226. * @param string $timestamp 当前时间戳 (为空则自动生成)
  1227. * @param string $noncestr 随机串 (为空则自动生成)
  1228. * @param string $appid 用于多个appid时使用,可空
  1229. * @return array|bool 返回签名字串
  1230. */
  1231. public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
  1232. if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
  1233. if (!$timestamp)
  1234. $timestamp = time();
  1235. if (!$noncestr)
  1236. $noncestr = $this->generateNonceStr();
  1237. $ret = strpos($url,'#');
  1238. if ($ret)
  1239. $url = substr($url,0,$ret);
  1240. $url = trim($url);
  1241. if (empty($url))
  1242. return false;
  1243. $arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
  1244. $sign = $this->getSignature($arrdata);
  1245. if (!$sign)
  1246. return false;
  1247. $signPackage = array(
  1248. "appId" => $this->appid,
  1249. "nonceStr" => $noncestr,
  1250. "timestamp" => $timestamp,
  1251. "url" => $url,
  1252. "signature" => $sign
  1253. );
  1254. return $signPackage;
  1255. }
  1256. /**
  1257. * 微信api不支持中文转义的json结构
  1258. * @param array $arr
  1259. */
  1260. static function json_encode($arr) {
  1261. if (count($arr) == 0) return "[]";
  1262. $parts = array ();
  1263. $is_list = false;
  1264. //Find out if the given array is a numerical array
  1265. $keys = array_keys ( $arr );
  1266. $max_length = count ( $arr ) - 1;
  1267. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  1268. $is_list = true;
  1269. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  1270. if ($i != $keys [$i]) { //A key fails at position check.
  1271. $is_list = false; //It is an associative array.
  1272. break;
  1273. }
  1274. }
  1275. }
  1276. foreach ( $arr as $key => $value ) {
  1277. if (is_array ( $value )) { //Custom handling for arrays
  1278. if ($is_list)
  1279. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  1280. else
  1281. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  1282. } else {
  1283. $str = '';
  1284. if (! $is_list)
  1285. $str = '"' . $key . '":';
  1286. //Custom handling for multiple data types
  1287. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  1288. $str .= $value; //Numbers
  1289. elseif ($value === false)
  1290. $str .= 'false'; //The booleans
  1291. elseif ($value === true)
  1292. $str .= 'true';
  1293. else
  1294. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  1295. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  1296. $parts [] = $str;
  1297. }
  1298. }
  1299. $json = implode ( ',', $parts );
  1300. if ($is_list)
  1301. return '[' . $json . ']'; //Return numerical JSON
  1302. return '{' . $json . '}'; //Return associative JSON
  1303. }
  1304. /**
  1305. * 获取签名
  1306. * @param array $arrdata 签名数组
  1307. * @param string $method 签名方法
  1308. * @return boolean|string 签名值
  1309. */
  1310. public function getSignature($arrdata,$method="sha1") {
  1311. if (!function_exists($method)) return false;
  1312. ksort($arrdata);
  1313. $paramstring = "";
  1314. foreach($arrdata as $key => $value)
  1315. {
  1316. if(strlen($paramstring) == 0)
  1317. $paramstring .= $key . "=" . $value;
  1318. else
  1319. $paramstring .= "&" . $key . "=" . $value;
  1320. }
  1321. $Sign = $method($paramstring);
  1322. return $Sign;
  1323. }
  1324. /**
  1325. * 获取微信卡券api_ticket
  1326. * @param string $appid 用于多个appid时使用,可空
  1327. * @param string $api_ticket 手动指定api_ticket,非必要情况不建议用
  1328. */
  1329. public function getJsCardTicket($appid='',$api_ticket=''){
  1330. if (!$this->access_token && !$this->checkAuth()) return false;
  1331. if (!$appid) $appid = $this->appid;
  1332. if ($api_ticket) { //手动指定token,优先使用
  1333. $this->api_ticket = $api_ticket;
  1334. return $this->api_ticket;
  1335. }
  1336. $authname = 'wechat_api_ticket_wxcard'.$appid;
  1337. if ($rs = $this->getCache($authname)) {
  1338. $this->api_ticket = $rs;
  1339. return $rs;
  1340. }
  1341. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=wx_card');
  1342. if ($result)
  1343. {
  1344. $json = json_decode($result,true);
  1345. if (!$json || !empty($json['errcode'])) {
  1346. $this->errCode = $json['errcode'];
  1347. $this->errMsg = $json['errmsg'];
  1348. return false;
  1349. }
  1350. $this->api_ticket = $json['ticket'];
  1351. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1352. $this->setCache($authname,$this->api_ticket,$expire);
  1353. return $this->api_ticket;
  1354. }
  1355. return false;
  1356. }
  1357. /**
  1358. * 获取微信卡券签名
  1359. * @param array $arrdata 签名数组
  1360. * @param string $method 签名方法
  1361. * @return boolean|string 签名值
  1362. */
  1363. public function getTicketSignature($arrdata,$method="sha1") {
  1364. if (!function_exists($method)) return false;
  1365. $newArray = array();
  1366. foreach($arrdata as $key => $value)
  1367. {
  1368. array_push($newArray,(string)$value);
  1369. }
  1370. sort($newArray,SORT_STRING);
  1371. return $method(implode($newArray));
  1372. }
  1373. /**
  1374. * 生成随机字串
  1375. * @param number $length 长度,默认为16,最长为32字节
  1376. * @return string
  1377. */
  1378. public function generateNonceStr($length=16){
  1379. // 密码字符集,可任意添加你需要的字符
  1380. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1381. $str = "";
  1382. for($i = 0; $i < $length; $i++)
  1383. {
  1384. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1385. }
  1386. return $str;
  1387. }
  1388. /**
  1389. * 获取微信服务器IP地址列表
  1390. * @return array('127.0.0.1','127.0.0.1')
  1391. */
  1392. public function getServerIp(){
  1393. if (!$this->access_token && !$this->checkAuth()) return false;
  1394. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1395. if ($result)
  1396. {
  1397. $json = json_decode($result,true);
  1398. if (!$json || isset($json['errcode'])) {
  1399. $this->errCode = $json['errcode'];
  1400. $this->errMsg = $json['errmsg'];
  1401. return false;
  1402. }
  1403. return $json['ip_list'];
  1404. }
  1405. return false;
  1406. }
  1407. /**
  1408. * 创建菜单(认证后的订阅号可用)
  1409. * @param array $data 菜单数组数据
  1410. * example:
  1411. * array (
  1412. * 'button' => array (
  1413. * 0 => array (
  1414. * 'name' => '扫码',
  1415. * 'sub_button' => array (
  1416. * 0 => array (
  1417. * 'type' => 'scancode_waitmsg',
  1418. * 'name' => '扫码带提示',
  1419. * 'key' => 'rselfmenu_0_0',
  1420. * ),
  1421. * 1 => array (
  1422. * 'type' => 'scancode_push',
  1423. * 'name' => '扫码推事件',
  1424. * 'key' => 'rselfmenu_0_1',
  1425. * ),
  1426. * ),
  1427. * ),
  1428. * 1 => array (
  1429. * 'name' => '发图',
  1430. * 'sub_button' => array (
  1431. * 0 => array (
  1432. * 'type' => 'pic_sysphoto',
  1433. * 'name' => '系统拍照发图',
  1434. * 'key' => 'rselfmenu_1_0',
  1435. * ),
  1436. * 1 => array (
  1437. * 'type' => 'pic_photo_or_album',
  1438. * 'name' => '拍照或者相册发图',
  1439. * 'key' => 'rselfmenu_1_1',
  1440. * )
  1441. * ),
  1442. * ),
  1443. * 2 => array (
  1444. * 'type' => 'location_select',
  1445. * 'name' => '发送位置',
  1446. * 'key' => 'rselfmenu_2_0'
  1447. * ),
  1448. * ),
  1449. * )
  1450. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  1451. * 1、click:点击推事件
  1452. * 2、view:跳转URL
  1453. * 3、scancode_push:扫码推事件
  1454. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1455. * 5、pic_sysphoto:弹出系统拍照发图
  1456. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1457. * 7、pic_weixin:弹出微信相册发图器
  1458. * 8、location_select:弹出地理位置选择器
  1459. */
  1460. public function createMenu($data){
  1461. if (!$this->access_token && !$this->checkAuth()) return false;
  1462. //die(self::json_encode($data));
  1463. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1464. dump($result);
  1465. if ($result)
  1466. {
  1467. $json = json_decode($result,true);
  1468. if (!$json || !empty($json['errcode'])) {
  1469. $this->errCode = $json['errcode'];
  1470. $this->errMsg = $json['errmsg'];
  1471. return false;
  1472. }
  1473. return true;
  1474. }
  1475. return false;
  1476. }
  1477. /**
  1478. * 获取菜单(认证后的订阅号可用)
  1479. * @return array('menu'=>array(....s))
  1480. */
  1481. public function getMenu(){
  1482. if (!$this->access_token && !$this->checkAuth()) return false;
  1483. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  1484. if ($result)
  1485. {
  1486. $json = json_decode($result,true);
  1487. if (!$json || isset($json['errcode'])) {
  1488. $this->errCode = $json['errcode'];
  1489. $this->errMsg = $json['errmsg'];
  1490. return false;
  1491. }
  1492. return $json;
  1493. }
  1494. return false;
  1495. }
  1496. /**
  1497. * 删除菜单(认证后的订阅号可用)
  1498. * @return boolean
  1499. */
  1500. public function deleteMenu(){
  1501. if (!$this->access_token && !$this->checkAuth()) return false;
  1502. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  1503. if ($result)
  1504. {
  1505. $json = json_decode($result,true);
  1506. if (!$json || !empty($json['errcode'])) {
  1507. $this->errCode = $json['errcode'];
  1508. $this->errMsg = $json['errmsg'];
  1509. return false;
  1510. }
  1511. return true;
  1512. }
  1513. return false;
  1514. }
  1515. /**
  1516. * 上传临时素材,有效期为3天(认证后的订阅号可用)
  1517. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1518. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1519. * 注意:临时素材的media_id是可复用的!
  1520. * @param array $data {"media":'@Path\filename.jpg'}
  1521. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1522. * @return boolean|array
  1523. */
  1524. public function uploadMedia($data, $type){
  1525. if (!$this->access_token && !$this->checkAuth()) return false;
  1526. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1527. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1528. if ($result)
  1529. {
  1530. $json = json_decode($result,true);
  1531. if (!$json || !empty($json['errcode'])) {
  1532. $this->errCode = $json['errcode'];
  1533. $this->errMsg = $json['errmsg'];
  1534. return false;
  1535. }
  1536. return $json;
  1537. }
  1538. return false;
  1539. }
  1540. /**
  1541. * 获取临时素材(认证后的订阅号可用)
  1542. * @param string $media_id 媒体文件id
  1543. * @param boolean $is_video 是否为视频文件,默认为否
  1544. * @return raw data
  1545. */
  1546. public function getMedia($media_id,$is_video=false){
  1547. if (!$this->access_token && !$this->checkAuth()) return false;
  1548. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1549. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1550. $url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1551. $result = $this->http_get($url_prefix.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1552. if ($result)
  1553. {
  1554. if (is_string($result)) {
  1555. $json = json_decode($result,true);
  1556. if (isset($json['errcode'])) {
  1557. $this->errCode = $json['errcode'];
  1558. $this->errMsg = $json['errmsg'];
  1559. return false;
  1560. }
  1561. }
  1562. return $result;
  1563. }
  1564. return false;
  1565. }
  1566. /**
  1567. * 上传图片,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 (认证后的订阅号可用)
  1568. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1569. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1570. * @param array $data {"media":'@Path\filename.jpg'}
  1571. *
  1572. * @return boolean|array
  1573. */
  1574. public function uploadImg($data){
  1575. if (!$this->access_token && !$this->checkAuth()) return false;
  1576. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1577. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADIMG_URL.'access_token='.$this->access_token,$data,true);
  1578. if ($result)
  1579. {
  1580. $json = json_decode($result,true);
  1581. if (!$json || !empty($json['errcode'])) {
  1582. $this->errCode = $json['errcode'];
  1583. $this->errMsg = $json['errmsg'];
  1584. return false;
  1585. }
  1586. return $json;
  1587. }
  1588. return false;
  1589. }
  1590. /**
  1591. * 上传永久素材(认证后的订阅号可用)
  1592. * 新增的永久素材也可以在公众平台官网素材管理模块中看到
  1593. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1594. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1595. * @param array $data {"media":'@Path\filename.jpg'}
  1596. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1597. * @param boolean $is_video 是否为视频文件,默认为否
  1598. * @param array $video_info 视频信息数组,非视频素材不需要提供 array('title'=>'视频标题','introduction'=>'描述')
  1599. * @return boolean|array
  1600. */
  1601. public function uploadForeverMedia($data, $type,$is_video=false,$video_info=array()){
  1602. if (!$this->access_token && !$this->checkAuth()) return false;
  1603. //#TODO 暂不确定此接口是否需要让视频文件走http协议
  1604. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1605. //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1606. //当上传视频文件时,附加视频文件信息
  1607. if ($is_video) $data['description'] = self::json_encode($video_info);
  1608. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1609. if ($result)
  1610. {
  1611. $json = json_decode($result,true);
  1612. if (!$json || !empty($json['errcode'])) {
  1613. $this->errCode = $json['errcode'];
  1614. $this->errMsg = $json['errmsg'];
  1615. return false;
  1616. }
  1617. return $json;
  1618. }
  1619. return false;
  1620. }
  1621. /**
  1622. * 上传永久图文素材(认证后的订阅号可用)
  1623. * 新增的永久素材也可以在公众平台官网素材管理模块中看到
  1624. * @param array $data 消息结构{"articles":[{...}]}
  1625. * @return boolean|array
  1626. */
  1627. public function uploadForeverArticles($data){
  1628. if (!$this->access_token && !$this->checkAuth()) return false;
  1629. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPLOAD_URL.'access_token='.$this->access_token,self::json_encode($data));
  1630. if ($result)
  1631. {
  1632. $json = json_decode($result,true);
  1633. if (!$json || !empty($json['errcode'])) {
  1634. $this->errCode = $json['errcode'];
  1635. $this->errMsg = $json['errmsg'];
  1636. return false;
  1637. }
  1638. return $json;
  1639. }
  1640. return false;
  1641. }
  1642. /**
  1643. * 修改永久图文素材(认证后的订阅号可用)
  1644. * 永久素材也可以在公众平台官网素材管理模块中看到
  1645. * @param string $media_id 图文素材id
  1646. * @param array $data 消息结构{"articles":[{...}]}
  1647. * @param int $index 更新的文章在图文素材的位置,第一篇为0,仅多图文使用
  1648. * @return boolean|array
  1649. */
  1650. public function updateForeverArticles($media_id,$data,$index=0){
  1651. if (!$this->access_token && !$this->checkAuth()) return false;
  1652. if (!isset($data['media_id'])) $data['media_id'] = $media_id;
  1653. if (!isset($data['index'])) $data['index'] = $index;
  1654. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1655. if ($result)
  1656. {
  1657. $json = json_decode($result,true);
  1658. if (!$json || !empty($json['errcode'])) {
  1659. $this->errCode = $json['errcode'];
  1660. $this->errMsg = $json['errmsg'];
  1661. return false;
  1662. }
  1663. return $json;
  1664. }
  1665. return false;
  1666. }
  1667. /**
  1668. * 获取永久素材(认证后的订阅号可用)
  1669. * 返回图文消息数组或二进制数据,失败返回false
  1670. * @param string $media_id 媒体文件id
  1671. * @param boolean $is_video 是否为视频文件,默认为否
  1672. * @return boolean|array|raw data
  1673. */
  1674. public function getForeverMedia($media_id,$is_video=false){
  1675. if (!$this->access_token && !$this->checkAuth()) return false;
  1676. $data = array('media_id' => $media_id);
  1677. //#TODO 暂不确定此接口是否需要让视频文件走http协议
  1678. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1679. //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1680. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_GET_URL.'access_token='.$this->access_token,self::json_encode($data));
  1681. if ($result)
  1682. {
  1683. if (is_string($result)) {
  1684. $json = json_decode($result,true);
  1685. if ($json) {
  1686. if (isset($json['errcode'])) {
  1687. $this->errCode = $json['errcode'];
  1688. $this->errMsg = $json['errmsg'];
  1689. return false;
  1690. }
  1691. return $json;
  1692. } else {
  1693. return $result;
  1694. }
  1695. }
  1696. return $result;
  1697. }
  1698. return false;
  1699. }
  1700. /**
  1701. * 删除永久素材(认证后的订阅号可用)
  1702. * @param string $media_id 媒体文件id
  1703. * @return boolean
  1704. */
  1705. public function delForeverMedia($media_id){
  1706. if (!$this->access_token && !$this->checkAuth()) return false;
  1707. $data = array('media_id' => $media_id);
  1708. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_DEL_URL.'access_token='.$this->access_token,self::json_encode($data));
  1709. if ($result)
  1710. {
  1711. $json = json_decode($result,true);
  1712. if (!$json || !empty($json['errcode'])) {
  1713. $this->errCode = $json['errcode'];
  1714. $this->errMsg = $json['errmsg'];
  1715. return false;
  1716. }
  1717. return true;
  1718. }
  1719. return false;
  1720. }
  1721. /**
  1722. * 获取永久素材列表(认证后的订阅号可用)
  1723. * @param string $type 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
  1724. * @param int $offset 全部素材的偏移位置,0表示从第一个素材
  1725. * @param int $count 返回素材的数量,取值在1到20之间
  1726. * @return boolean|array
  1727. * 返回数组格式:
  1728. * array(
  1729. * 'total_count'=>0, //该类型的素材的总数
  1730. * 'item_count'=>0, //本次调用获取的素材的数量
  1731. * 'item'=>array() //素材列表数组,内容定义请参考官方文档
  1732. * )
  1733. */
  1734. public function getForeverList($type,$offset,$count){
  1735. if (!$this->access_token && !$this->checkAuth()) return false;
  1736. $data = array(
  1737. 'type' => $type,
  1738. 'offset' => $offset,
  1739. 'count' => $count,
  1740. );
  1741. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_BATCHGET_URL.'access_token='.$this->access_token,self::json_encode($data));
  1742. if ($result)
  1743. {
  1744. $json = json_decode($result,true);
  1745. if (isset($json['errcode'])) {
  1746. $this->errCode = $json['errcode'];
  1747. $this->errMsg = $json['errmsg'];
  1748. return false;
  1749. }
  1750. return $json;
  1751. }
  1752. return false;
  1753. }
  1754. /**
  1755. * 获取永久素材总数(认证后的订阅号可用)
  1756. * @return boolean|array
  1757. * 返回数组格式:
  1758. * array(
  1759. * 'voice_count'=>0, //语音总数量
  1760. * 'video_count'=>0, //视频总数量
  1761. * 'image_count'=>0, //图片总数量
  1762. * 'news_count'=>0 //图文总数量
  1763. * )
  1764. */
  1765. public function getForeverCount(){
  1766. if (!$this->access_token && !$this->checkAuth()) return false;
  1767. $result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_FOREVER_COUNT_URL.'access_token='.$this->access_token);
  1768. if ($result)
  1769. {
  1770. $json = json_decode($result,true);
  1771. if (isset($json['errcode'])) {
  1772. $this->errCode = $json['errcode'];
  1773. $this->errMsg = $json['errmsg'];
  1774. return false;
  1775. }
  1776. return $json;
  1777. }
  1778. return false;
  1779. }
  1780. /**
  1781. * 上传图文消息素材,用于群发(认证后的订阅号可用)
  1782. * @param array $data 消息结构{"articles":[{...}]}
  1783. * @return boolean|array
  1784. */
  1785. public function uploadArticles($data){
  1786. if (!$this->access_token && !$this->checkAuth()) return false;
  1787. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1788. if ($result)
  1789. {
  1790. $json = json_decode($result,true);
  1791. if (!$json || !empty($json['errcode'])) {
  1792. $this->errCode = $json['errcode'];
  1793. $this->errMsg = $json['errmsg'];
  1794. return false;
  1795. }
  1796. return $json;
  1797. }
  1798. return false;
  1799. }
  1800. /**
  1801. * 上传视频素材(认证后的订阅号可用)
  1802. * @param array $data 消息结构
  1803. * {
  1804. * "media_id"=>"", //通过上传媒体接口得到的MediaId
  1805. * "title"=>"TITLE", //视频标题
  1806. * "description"=>"Description" //视频描述
  1807. * }
  1808. * @return boolean|array
  1809. * {
  1810. * "type":"video",
  1811. * "media_id":"mediaid",
  1812. * "created_at":1398848981
  1813. * }
  1814. */
  1815. public function uploadMpVideo($data){
  1816. if (!$this->access_token && !$this->checkAuth()) return false;
  1817. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_VIDEO_UPLOAD.'access_token='.$this->access_token,self::json_encode($data));
  1818. if ($result)
  1819. {
  1820. $json = json_decode($result,true);
  1821. if (!$json || !empty($json['errcode'])) {
  1822. $this->errCode = $json['errcode'];
  1823. $this->errMsg = $json['errmsg'];
  1824. return false;
  1825. }
  1826. return $json;
  1827. }
  1828. return false;
  1829. }
  1830. /**
  1831. * 高级群发消息, 根据OpenID列表群发图文消息(订阅号不可用)
  1832. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1833. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1834. * @param array $data 消息结构
  1835. * {
  1836. * "touser"=>array(
  1837. * "OPENID1",
  1838. * "OPENID2"
  1839. * ),
  1840. * "msgtype"=>"mpvideo",
  1841. * // 在下面5种类型中选择对应的参数内容
  1842. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1843. * // text => array ( "content" => "hello")
  1844. * }
  1845. * @return boolean|array
  1846. */
  1847. public function sendMassMessage($data){
  1848. if (!$this->access_token && !$this->checkAuth()) return false;
  1849. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1850. if ($result)
  1851. {
  1852. $json = json_decode($result,true);
  1853. if (!$json || !empty($json['errcode'])) {
  1854. $this->errCode = $json['errcode'];
  1855. $this->errMsg = $json['errmsg'];
  1856. return false;
  1857. }
  1858. return $json;
  1859. }
  1860. return false;
  1861. }
  1862. /**
  1863. * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用)
  1864. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1865. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1866. * @param array $data 消息结构
  1867. * {
  1868. * "filter"=>array(
  1869. * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id
  1870. * "group_id"=>"2" //群发的分组id
  1871. * ),
  1872. * "msgtype"=>"mpvideo",
  1873. * // 在下面5种类型中选择对应的参数内容
  1874. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1875. * // text => array ( "content" => "hello")
  1876. * }
  1877. * @return boolean|array
  1878. */
  1879. public function sendGroupMassMessage($data){
  1880. if (!$this->access_token && !$this->checkAuth()) return false;
  1881. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1882. if ($result)
  1883. {
  1884. $json = json_decode($result,true);
  1885. if (!$json || !empty($json['errcode'])) {
  1886. $this->errCode = $json['errcode'];
  1887. $this->errMsg = $json['errmsg'];
  1888. return false;
  1889. }
  1890. return $json;
  1891. }
  1892. return false;
  1893. }
  1894. /**
  1895. * 高级群发消息, 删除群发图文消息(认证后的订阅号可用)
  1896. * @param int $msg_id 消息id
  1897. * @return boolean|array
  1898. */
  1899. public function deleteMassMessage($msg_id){
  1900. if (!$this->access_token && !$this->checkAuth()) return false;
  1901. $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)));
  1902. if ($result)
  1903. {
  1904. $json = json_decode($result,true);
  1905. if (!$json || !empty($json['errcode'])) {
  1906. $this->errCode = $json['errcode'];
  1907. $this->errMsg = $json['errmsg'];
  1908. return false;
  1909. }
  1910. return true;
  1911. }
  1912. return false;
  1913. }
  1914. /**
  1915. * 高级群发消息, 预览群发消息(认证后的订阅号可用)
  1916. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1917. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1918. * @param array $data 消息结构
  1919. * {
  1920. * "touser"=>"OPENID",
  1921. * "msgtype"=>"mpvideo",
  1922. * // 在下面5种类型中选择对应的参数内容
  1923. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1924. * // text => array ( "content" => "hello")
  1925. * }
  1926. * @return boolean|array
  1927. */
  1928. public function previewMassMessage($data){
  1929. if (!$this->access_token && !$this->checkAuth()) return false;
  1930. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_PREVIEW_URL.'access_token='.$this->access_token,self::json_encode($data));
  1931. if ($result)
  1932. {
  1933. $json = json_decode($result,true);
  1934. if (!$json || !empty($json['errcode'])) {
  1935. $this->errCode = $json['errcode'];
  1936. $this->errMsg = $json['errmsg'];
  1937. return false;
  1938. }
  1939. return $json;
  1940. }
  1941. return false;
  1942. }
  1943. /**
  1944. * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用)
  1945. * @param int $msg_id 消息id
  1946. * @return boolean|array
  1947. * {
  1948. * "msg_id":201053012, //群发消息后返回的消息id
  1949. * "msg_status":"SEND_SUCCESS" //消息发送后的状态,SENDING表示正在发送 SEND_SUCCESS表示发送成功
  1950. * }
  1951. */
  1952. public function queryMassMessage($msg_id){
  1953. if (!$this->access_token && !$this->checkAuth()) return false;
  1954. $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)));
  1955. if ($result)
  1956. {
  1957. $json = json_decode($result,true);
  1958. if (!$json || !empty($json['errcode'])) {
  1959. $this->errCode = $json['errcode'];
  1960. $this->errMsg = $json['errmsg'];
  1961. return false;
  1962. }
  1963. return $json;
  1964. }
  1965. return false;
  1966. }
  1967. /**
  1968. * 创建二维码ticket
  1969. * @param int|string $scene_id 自定义追踪id,临时二维码只能用数值型
  1970. * @param int $type 0:临时二维码;1:数值型永久二维码(此时expire参数无效);2:字符串型永久二维码(此时expire参数无效)
  1971. * @param int $expire 临时二维码有效期,最大为604800秒
  1972. * @return array('ticket'=>'qrcode字串','expire_seconds'=>604800,'url'=>'二维码图片解析后的地址')
  1973. */
  1974. public function getQRCode($scene_id,$type=0,$expire=604800){
  1975. if (!$this->access_token && !$this->checkAuth()) return false;
  1976. if (!isset($scene_id)) return false;
  1977. switch ($type) {
  1978. case '0':
  1979. if (!is_numeric($scene_id))
  1980. return false;
  1981. $action_name = 'QR_SCENE';
  1982. $action_info = array('scene'=>(array('scene_id'=>$scene_id)));
  1983. break;
  1984. case '1':
  1985. if (!is_numeric($scene_id))
  1986. return false;
  1987. $action_name = 'QR_LIMIT_SCENE';
  1988. $action_info = array('scene'=>(array('scene_id'=>$scene_id)));
  1989. break;
  1990. case '2':
  1991. if (!is_string($scene_id))
  1992. return false;
  1993. $action_name = 'QR_LIMIT_STR_SCENE';
  1994. $action_info = array('scene'=>(array('scene_str'=>$scene_id)));
  1995. break;
  1996. default:
  1997. return false;
  1998. }
  1999. $data = array(
  2000. 'action_name' => $action_name,
  2001. 'expire_seconds' => $expire,
  2002. 'action_info' => $action_info
  2003. );
  2004. if ($type) {
  2005. unset($data['expire_seconds']);
  2006. }
  2007. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2008. if ($result) {
  2009. $json = json_decode($result,true);
  2010. if (!$json || !empty($json['errcode'])) {
  2011. $this->errCode = $json['errcode'];
  2012. $this->errMsg = $json['errmsg'];
  2013. return false;
  2014. }
  2015. return $json;
  2016. }
  2017. return false;
  2018. }
  2019. /**
  2020. * 获取二维码图片
  2021. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  2022. * @return string url 返回http地址
  2023. */
  2024. public function getQRUrl($ticket) {
  2025. return self::QRCODE_IMG_URL.urlencode($ticket);
  2026. }
  2027. /**
  2028. * 长链接转短链接接口
  2029. * @param string $long_url 传入要转换的长url
  2030. * @return boolean|string url 成功则返回转换后的短url
  2031. */
  2032. public function getShortUrl($long_url){
  2033. if (!$this->access_token && !$this->checkAuth()) return false;
  2034. $data = array(
  2035. 'action'=>'long2short',
  2036. 'long_url'=>$long_url
  2037. );
  2038. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  2039. if ($result)
  2040. {
  2041. $json = json_decode($result,true);
  2042. if (!$json || !empty($json['errcode'])) {
  2043. $this->errCode = $json['errcode'];
  2044. $this->errMsg = $json['errmsg'];
  2045. return false;
  2046. }
  2047. return $json['short_url'];
  2048. }
  2049. return false;
  2050. }
  2051. /**
  2052. * 获取统计数据
  2053. * @param string $type 数据分类(user|article|upstreammsg|interface)分别为(用户分析|图文分析|消息分析|接口分析)
  2054. * @param string $subtype 数据子分类,参考 DATACUBE_URL_ARR 常量定义部分 或者README.md说明文档
  2055. * @param string $begin_date 开始时间
  2056. * @param string $end_date 结束时间
  2057. * @return boolean|array 成功返回查询结果数组,其定义请看官方文档
  2058. */
  2059. public function getDatacube($type,$subtype,$begin_date,$end_date=''){
  2060. if (!$this->access_token && !$this->checkAuth()) return false;
  2061. if (!isset(self::$DATACUBE_URL_ARR[$type]) || !isset(self::$DATACUBE_URL_ARR[$type][$subtype]))
  2062. return false;
  2063. $data = array(
  2064. 'begin_date'=>$begin_date,
  2065. 'end_date'=>$end_date?$end_date:$begin_date
  2066. );
  2067. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::$DATACUBE_URL_ARR[$type][$subtype].'access_token='.$this->access_token,self::json_encode($data));
  2068. if ($result)
  2069. {
  2070. $json = json_decode($result,true);
  2071. if (!$json || !empty($json['errcode'])) {
  2072. $this->errCode = $json['errcode'];
  2073. $this->errMsg = $json['errmsg'];
  2074. return false;
  2075. }
  2076. return isset($json['list'])?$json['list']:$json;
  2077. }
  2078. return false;
  2079. }
  2080. /**
  2081. * 批量获取关注用户列表
  2082. * @param unknown $next_openid
  2083. */
  2084. public function getUserList($next_openid=''){
  2085. if (!$this->access_token && !$this->checkAuth()) return false;
  2086. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  2087. if ($result)
  2088. {
  2089. $json = json_decode($result,true);
  2090. if (isset($json['errcode'])) {
  2091. $this->errCode = $json['errcode'];
  2092. $this->errMsg = $json['errmsg'];
  2093. return false;
  2094. }
  2095. return $json;
  2096. }
  2097. return false;
  2098. }
  2099. /**
  2100. * 获取关注者详细信息
  2101. * @param string $openid
  2102. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  2103. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  2104. */
  2105. public function getUserInfo($openid){
  2106. if (!$this->access_token && !$this->checkAuth()) return false;
  2107. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  2108. if ($result)
  2109. {
  2110. $json = json_decode($result,true);
  2111. if (isset($json['errcode'])) {
  2112. $this->errCode = $json['errcode'];
  2113. $this->errMsg = $json['errmsg'];
  2114. return false;
  2115. }
  2116. return $json;
  2117. }
  2118. return false;
  2119. }
  2120. /**
  2121. * 设置用户备注名
  2122. * @param string $openid
  2123. * @param string $remark 备注名
  2124. * @return boolean|array
  2125. */
  2126. public function updateUserRemark($openid,$remark){
  2127. if (!$this->access_token && !$this->checkAuth()) return false;
  2128. $data = array(
  2129. 'openid'=>$openid,
  2130. 'remark'=>$remark
  2131. );
  2132. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
  2133. if ($result)
  2134. {
  2135. $json = json_decode($result,true);
  2136. if (!$json || !empty($json['errcode'])) {
  2137. $this->errCode = $json['errcode'];
  2138. $this->errMsg = $json['errmsg'];
  2139. return false;
  2140. }
  2141. return $json;
  2142. }
  2143. return false;
  2144. }
  2145. /**
  2146. * 获取用户分组列表
  2147. * @return boolean|array
  2148. */
  2149. public function getGroup(){
  2150. if (!$this->access_token && !$this->checkAuth()) return false;
  2151. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  2152. if ($result)
  2153. {
  2154. $json = json_decode($result,true);
  2155. if (isset($json['errcode'])) {
  2156. $this->errCode = $json['errcode'];
  2157. $this->errMsg = $json['errmsg'];
  2158. return false;
  2159. }
  2160. return $json;
  2161. }
  2162. return false;
  2163. }
  2164. /**
  2165. * 获取用户所在分组
  2166. * @param string $openid
  2167. * @return boolean|int 成功则返回用户分组id
  2168. */
  2169. public function getUserGroup($openid){
  2170. if (!$this->access_token && !$this->checkAuth()) return false;
  2171. $data = array(
  2172. 'openid'=>$openid
  2173. );
  2174. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  2175. if ($result)
  2176. {
  2177. $json = json_decode($result,true);
  2178. if (!$json || !empty($json['errcode'])) {
  2179. $this->errCode = $json['errcode'];
  2180. $this->errMsg = $json['errmsg'];
  2181. return false;
  2182. } else
  2183. if (isset($json['groupid'])) return $json['groupid'];
  2184. }
  2185. return false;
  2186. }
  2187. /**
  2188. * 新增自定分组
  2189. * @param string $name 分组名称
  2190. * @return boolean|array
  2191. */
  2192. public function createGroup($name){
  2193. if (!$this->access_token && !$this->checkAuth()) return false;
  2194. $data = array(
  2195. 'group'=>array('name'=>$name)
  2196. );
  2197. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2198. if ($result)
  2199. {
  2200. $json = json_decode($result,true);
  2201. if (!$json || !empty($json['errcode'])) {
  2202. $this->errCode = $json['errcode'];
  2203. $this->errMsg = $json['errmsg'];
  2204. return false;
  2205. }
  2206. return $json;
  2207. }
  2208. return false;
  2209. }
  2210. /**
  2211. * 更改分组名称
  2212. * @param int $groupid 分组id
  2213. * @param string $name 分组名称
  2214. * @return boolean|array
  2215. */
  2216. public function updateGroup($groupid,$name){
  2217. if (!$this->access_token && !$this->checkAuth()) return false;
  2218. $data = array(
  2219. 'group'=>array('id'=>$groupid,'name'=>$name)
  2220. );
  2221. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2222. if ($result)
  2223. {
  2224. $json = json_decode($result,true);
  2225. if (!$json || !empty($json['errcode'])) {
  2226. $this->errCode = $json['errcode'];
  2227. $this->errMsg = $json['errmsg'];
  2228. return false;
  2229. }
  2230. return $json;
  2231. }
  2232. return false;
  2233. }
  2234. /**
  2235. * 移动用户分组
  2236. * @param int $groupid 分组id
  2237. * @param string $openid 用户openid
  2238. * @return boolean|array
  2239. */
  2240. public function updateGroupMembers($groupid,$openid){
  2241. if (!$this->access_token && !$this->checkAuth()) return false;
  2242. $data = array(
  2243. 'openid'=>$openid,
  2244. 'to_groupid'=>$groupid
  2245. );
  2246. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2247. if ($result)
  2248. {
  2249. $json = json_decode($result,true);
  2250. if (!$json || !empty($json['errcode'])) {
  2251. $this->errCode = $json['errcode'];
  2252. $this->errMsg = $json['errmsg'];
  2253. return false;
  2254. }
  2255. return $json;
  2256. }
  2257. return false;
  2258. }
  2259. /**
  2260. * 批量移动用户分组
  2261. * @param int $groupid 分组id
  2262. * @param string $openid_list 用户openid数组,一次不能超过50个
  2263. * @return boolean|array
  2264. */
  2265. public function batchUpdateGroupMembers($groupid,$openid_list){
  2266. if (!$this->access_token && !$this->checkAuth()) return false;
  2267. $data = array(
  2268. 'openid_list'=>$openid_list,
  2269. 'to_groupid'=>$groupid
  2270. );
  2271. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_BATCHUPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2272. if ($result)
  2273. {
  2274. $json = json_decode($result,true);
  2275. if (!$json || !empty($json['errcode'])) {
  2276. $this->errCode = $json['errcode'];
  2277. $this->errMsg = $json['errmsg'];
  2278. return false;
  2279. }
  2280. return $json;
  2281. }
  2282. return false;
  2283. }
  2284. /**
  2285. * 发送客服消息
  2286. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  2287. * @return boolean|array
  2288. */
  2289. public function sendCustomMessage($data){
  2290. if (!$this->access_token && !$this->checkAuth()) return false;
  2291. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  2292. if ($result)
  2293. {
  2294. $json = json_decode($result,true);
  2295. if (!$json || !empty($json['errcode'])) {
  2296. $this->errCode = $json['errcode'];
  2297. $this->errMsg = $json['errmsg'];
  2298. return false;
  2299. }
  2300. return $json;
  2301. }
  2302. return false;
  2303. }
  2304. /**
  2305. * oauth 授权跳转接口
  2306. * @param string $callback 回调URI
  2307. * @return string
  2308. */
  2309. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  2310. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  2311. }
  2312. /**
  2313. * 通过code获取Access Token
  2314. * @return array {access_token,expires_in,refresh_token,openid,scope}
  2315. */
  2316. public function getOauthAccessToken(){
  2317. $code = isset($_GET['code'])?$_GET['code']:'';
  2318. if (!$code) return false;
  2319. $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');
  2320. if ($result)
  2321. {
  2322. $json = json_decode($result,true);
  2323. if (!$json || !empty($json['errcode'])) {
  2324. $this->errCode = $json['errcode'];
  2325. $this->errMsg = $json['errmsg'];
  2326. return false;
  2327. }
  2328. $this->user_token = $json['access_token'];
  2329. return $json;
  2330. }
  2331. return false;
  2332. }
  2333. /**
  2334. * 刷新access token并续期
  2335. * @param string $refresh_token
  2336. * @return boolean|mixed
  2337. */
  2338. public function getOauthRefreshToken($refresh_token){
  2339. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  2340. if ($result)
  2341. {
  2342. $json = json_decode($result,true);
  2343. if (!$json || !empty($json['errcode'])) {
  2344. $this->errCode = $json['errcode'];
  2345. $this->errMsg = $json['errmsg'];
  2346. return false;
  2347. }
  2348. $this->user_token = $json['access_token'];
  2349. return $json;
  2350. }
  2351. return false;
  2352. }
  2353. /**
  2354. * 获取授权后的用户资料
  2355. * @param string $access_token
  2356. * @param string $openid
  2357. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  2358. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  2359. */
  2360. public function getOauthUserinfo($access_token,$openid){
  2361. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  2362. if ($result)
  2363. {
  2364. $json = json_decode($result,true);
  2365. if (!$json || !empty($json['errcode'])) {
  2366. $this->errCode = $json['errcode'];
  2367. $this->errMsg = $json['errmsg'];
  2368. return false;
  2369. }
  2370. return $json;
  2371. }
  2372. return false;
  2373. }
  2374. /**
  2375. * 检验授权凭证是否有效
  2376. * @param string $access_token
  2377. * @param string $openid
  2378. * @return boolean 是否有效
  2379. */
  2380. public function getOauthAuth($access_token,$openid){
  2381. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  2382. if ($result)
  2383. {
  2384. $json = json_decode($result,true);
  2385. if (!$json || !empty($json['errcode'])) {
  2386. $this->errCode = $json['errcode'];
  2387. $this->errMsg = $json['errmsg'];
  2388. return false;
  2389. } else
  2390. if ($json['errcode']==0) return true;
  2391. }
  2392. return false;
  2393. }
  2394. /**
  2395. * 模板消息 设置所属行业
  2396. * @param int $id1 公众号模板消息所属行业编号,参看官方开发文档 行业代码
  2397. * @param int $id2 同$id1。但如果只有一个行业,此参数可省略
  2398. * @return boolean|array
  2399. */
  2400. public function setTMIndustry($id1,$id2=''){
  2401. if ($id1) $data['industry_id1'] = $id1;
  2402. if ($id2) $data['industry_id2'] = $id2;
  2403. if (!$this->access_token && !$this->checkAuth()) return false;
  2404. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SET_INDUSTRY_URL.'access_token='.$this->access_token,self::json_encode($data));
  2405. if($result){
  2406. $json = json_decode($result,true);
  2407. if (!$json || !empty($json['errcode'])) {
  2408. $this->errCode = $json['errcode'];
  2409. $this->errMsg = $json['errmsg'];
  2410. return false;
  2411. }
  2412. return $json;
  2413. }
  2414. return false;
  2415. }
  2416. /**
  2417. * 模板消息 添加消息模板
  2418. * 成功返回消息模板的调用id
  2419. * @param string $tpl_id 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
  2420. * @return boolean|string
  2421. */
  2422. public function addTemplateMessage($tpl_id){
  2423. $data = array ('template_id_short' =>$tpl_id);
  2424. if (!$this->access_token && !$this->checkAuth()) return false;
  2425. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_ADD_TPL_URL.'access_token='.$this->access_token,self::json_encode($data));
  2426. if($result){
  2427. $json = json_decode($result,true);
  2428. if (!$json || !empty($json['errcode'])) {
  2429. $this->errCode = $json['errcode'];
  2430. $this->errMsg = $json['errmsg'];
  2431. return false;
  2432. }
  2433. return $json['template_id'];
  2434. }
  2435. return false;
  2436. }
  2437. /**
  2438. * 发送模板消息
  2439. * @param array $data 消息结构
  2440. * {
  2441. "touser":"OPENID",
  2442. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  2443. "url":"http://weixin.qq.com/download",
  2444. "topcolor":"#FF0000",
  2445. "data":{
  2446. "参数名1": {
  2447. "value":"参数",
  2448. "color":"#173177" //参数颜色
  2449. },
  2450. "Date":{
  2451. "value":"06月07日 19时24分",
  2452. "color":"#173177"
  2453. },
  2454. "CardNumber":{
  2455. "value":"0426",
  2456. "color":"#173177"
  2457. },
  2458. "Type":{
  2459. "value":"消费",
  2460. "color":"#173177"
  2461. }
  2462. }
  2463. }
  2464. * @return boolean|array
  2465. */
  2466. public function sendTemplateMessage($data){
  2467. if (!$this->access_token && !$this->checkAuth()) return false;
  2468. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  2469. if($result){
  2470. $json = json_decode($result,true);
  2471. if (!$json || !empty($json['errcode'])) {
  2472. $this->errCode = $json['errcode'];
  2473. $this->errMsg = $json['errmsg'];
  2474. return false;
  2475. }
  2476. return $json;
  2477. }
  2478. return false;
  2479. }
  2480. /**
  2481. * 获取多客服会话记录
  2482. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  2483. * @return boolean|array
  2484. */
  2485. public function getCustomServiceMessage($data){
  2486. if (!$this->access_token && !$this->checkAuth()) return false;
  2487. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  2488. if ($result)
  2489. {
  2490. $json = json_decode($result,true);
  2491. if (!$json || !empty($json['errcode'])) {
  2492. $this->errCode = $json['errcode'];
  2493. $this->errMsg = $json['errmsg'];
  2494. return false;
  2495. }
  2496. return $json;
  2497. }
  2498. return false;
  2499. }
  2500. /**
  2501. * 转发多客服消息
  2502. * Example: $obj->transfer_customer_service($customer_account)->reply();
  2503. * @param string $customer_account 转发到指定客服帐号:test1@test
  2504. */
  2505. public function transfer_customer_service($customer_account = '')
  2506. {
  2507. $msg = array(
  2508. 'ToUserName' => $this->getRevFrom(),
  2509. 'FromUserName'=>$this->getRevTo(),
  2510. 'CreateTime'=>time(),
  2511. 'MsgType'=>'transfer_customer_service',
  2512. );
  2513. if ($customer_account) {
  2514. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  2515. }
  2516. $this->Message($msg);
  2517. return $this;
  2518. }
  2519. /**
  2520. * 获取多客服客服基本信息
  2521. *
  2522. * @return boolean|array
  2523. */
  2524. public function getCustomServiceKFlist(){
  2525. if (!$this->access_token && !$this->checkAuth()) return false;
  2526. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  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. *
  2542. * @return boolean|array {
  2543. "kf_online_list": [
  2544. {
  2545. "kf_account": "test1@test", //客服账号@微信别名
  2546. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  2547. "kf_id": "1001", //客服工号
  2548. "auto_accept": 0, //客服设置的最大自动接入数
  2549. "accepted_case": 1 //客服当前正在接待的会话数
  2550. }
  2551. ]
  2552. }
  2553. */
  2554. public function getCustomServiceOnlineKFlist(){
  2555. if (!$this->access_token && !$this->checkAuth()) return false;
  2556. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  2557. if ($result)
  2558. {
  2559. $json = json_decode($result,true);
  2560. if (!$json || !empty($json['errcode'])) {
  2561. $this->errCode = $json['errcode'];
  2562. $this->errMsg = $json['errmsg'];
  2563. return false;
  2564. }
  2565. return $json;
  2566. }
  2567. return false;
  2568. }
  2569. /**
  2570. * 创建指定多客服会话
  2571. * @tutorial 当用户已被其他客服接待或指定客服不在线则会失败
  2572. * @param string $openid //用户openid
  2573. * @param string $kf_account //客服账号
  2574. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2575. * @return boolean | array //成功返回json数组
  2576. * {
  2577. * "errcode": 0,
  2578. * "errmsg": "ok",
  2579. * }
  2580. */
  2581. public function createKFSession($openid,$kf_account,$text=''){
  2582. $data=array(
  2583. "openid" =>$openid,
  2584. "kf_account" => $kf_account
  2585. );
  2586. if ($text) $data["text"] = $text;
  2587. if (!$this->access_token && !$this->checkAuth()) return false;
  2588. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CREATE.'access_token='.$this->access_token,self::json_encode($data));
  2589. if ($result)
  2590. {
  2591. $json = json_decode($result,true);
  2592. if (!$json || !empty($json['errcode'])) {
  2593. $this->errCode = $json['errcode'];
  2594. $this->errMsg = $json['errmsg'];
  2595. return false;
  2596. }
  2597. return $json;
  2598. }
  2599. return false;
  2600. }
  2601. /**
  2602. * 关闭指定多客服会话
  2603. * @tutorial 当用户被其他客服接待时则会失败
  2604. * @param string $openid //用户openid
  2605. * @param string $kf_account //客服账号
  2606. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2607. * @return boolean | array //成功返回json数组
  2608. * {
  2609. * "errcode": 0,
  2610. * "errmsg": "ok",
  2611. * }
  2612. */
  2613. public function closeKFSession($openid,$kf_account,$text=''){
  2614. $data=array(
  2615. "openid" =>$openid,
  2616. "kf_account" => $kf_account
  2617. );
  2618. if ($text) $data["text"] = $text;
  2619. if (!$this->access_token && !$this->checkAuth()) return false;
  2620. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CLOSE .'access_token='.$this->access_token,self::json_encode($data));
  2621. if ($result)
  2622. {
  2623. $json = json_decode($result,true);
  2624. if (!$json || !empty($json['errcode'])) {
  2625. $this->errCode = $json['errcode'];
  2626. $this->errMsg = $json['errmsg'];
  2627. return false;
  2628. }
  2629. return $json;
  2630. }
  2631. return false;
  2632. }
  2633. /**
  2634. * 获取用户会话状态
  2635. * @param string $openid //用户openid
  2636. * @return boolean | array //成功返回json数组
  2637. * {
  2638. * "errcode" : 0,
  2639. * "errmsg" : "ok",
  2640. * "kf_account" : "test1@test", //正在接待的客服
  2641. * "createtime": 123456789, //会话接入时间
  2642. * }
  2643. */
  2644. public function getKFSession($openid){
  2645. if (!$this->access_token && !$this->checkAuth()) return false;
  2646. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET .'access_token='.$this->access_token.'&openid='.$openid);
  2647. if ($result)
  2648. {
  2649. $json = json_decode($result,true);
  2650. if (!$json || !empty($json['errcode'])) {
  2651. $this->errCode = $json['errcode'];
  2652. $this->errMsg = $json['errmsg'];
  2653. return false;
  2654. }
  2655. return $json;
  2656. }
  2657. return false;
  2658. }
  2659. /**
  2660. * 获取指定客服的会话列表
  2661. * @param string $openid //用户openid
  2662. * @return boolean | array //成功返回json数组
  2663. * array(
  2664. * 'sessionlist' => array (
  2665. * array (
  2666. * 'openid'=>'OPENID', //客户 openid
  2667. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2668. * ),
  2669. * array (
  2670. * 'openid'=>'OPENID', //客户 openid
  2671. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2672. * ),
  2673. * )
  2674. * )
  2675. */
  2676. public function getKFSessionlist($kf_account){
  2677. if (!$this->access_token && !$this->checkAuth()) return false;
  2678. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_LIST .'access_token='.$this->access_token.'&kf_account='.$kf_account);
  2679. if ($result)
  2680. {
  2681. $json = json_decode($result,true);
  2682. if (!$json || !empty($json['errcode'])) {
  2683. $this->errCode = $json['errcode'];
  2684. $this->errMsg = $json['errmsg'];
  2685. return false;
  2686. }
  2687. return $json;
  2688. }
  2689. return false;
  2690. }
  2691. /**
  2692. * 获取未接入会话列表
  2693. * @param string $openid //用户openid
  2694. * @return boolean | array //成功返回json数组
  2695. * array (
  2696. * 'count' => 150 , //未接入会话数量
  2697. * 'waitcaselist' => array (
  2698. * array (
  2699. * 'openid'=>'OPENID', //客户 openid
  2700. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2701. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2702. * ),
  2703. * array (
  2704. * 'openid'=>'OPENID', //客户 openid
  2705. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2706. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2707. * )
  2708. * )
  2709. * )
  2710. */
  2711. public function getKFSessionWait(){
  2712. if (!$this->access_token && !$this->checkAuth()) return false;
  2713. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_WAIT .'access_token='.$this->access_token);
  2714. if ($result)
  2715. {
  2716. $json = json_decode($result,true);
  2717. if (!$json || !empty($json['errcode'])) {
  2718. $this->errCode = $json['errcode'];
  2719. $this->errMsg = $json['errmsg'];
  2720. return false;
  2721. }
  2722. return $json;
  2723. }
  2724. return false;
  2725. }
  2726. /**
  2727. * 添加客服账号
  2728. *
  2729. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2730. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2731. * @param string $password //客服账号明文登录密码,会自动加密
  2732. * @return boolean|array
  2733. * 成功返回结果
  2734. * {
  2735. * "errcode": 0,
  2736. * "errmsg": "ok",
  2737. * }
  2738. */
  2739. public function addKFAccount($account,$nickname,$password){
  2740. $data=array(
  2741. "kf_account" =>$account,
  2742. "nickname" => $nickname,
  2743. "password" => md5($password)
  2744. );
  2745. if (!$this->access_token && !$this->checkAuth()) return false;
  2746. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_ADD_URL.'access_token='.$this->access_token,self::json_encode($data));
  2747. if ($result)
  2748. {
  2749. $json = json_decode($result,true);
  2750. if (!$json || !empty($json['errcode'])) {
  2751. $this->errCode = $json['errcode'];
  2752. $this->errMsg = $json['errmsg'];
  2753. return false;
  2754. }
  2755. return $json;
  2756. }
  2757. return false;
  2758. }
  2759. /**
  2760. * 修改客服账号信息
  2761. *
  2762. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2763. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2764. * @param string $password //客服账号明文登录密码,会自动加密
  2765. * @return boolean|array
  2766. * 成功返回结果
  2767. * {
  2768. * "errcode": 0,
  2769. * "errmsg": "ok",
  2770. * }
  2771. */
  2772. public function updateKFAccount($account,$nickname,$password){
  2773. $data=array(
  2774. "kf_account" =>$account,
  2775. "nickname" => $nickname,
  2776. "password" => md5($password)
  2777. );
  2778. if (!$this->access_token && !$this->checkAuth()) return false;
  2779. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2780. if ($result)
  2781. {
  2782. $json = json_decode($result,true);
  2783. if (!$json || !empty($json['errcode'])) {
  2784. $this->errCode = $json['errcode'];
  2785. $this->errMsg = $json['errmsg'];
  2786. return false;
  2787. }
  2788. return $json;
  2789. }
  2790. return false;
  2791. }
  2792. /**
  2793. * 删除客服账号
  2794. *
  2795. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2796. * @return boolean|array
  2797. * 成功返回结果
  2798. * {
  2799. * "errcode": 0,
  2800. * "errmsg": "ok",
  2801. * }
  2802. */
  2803. public function deleteKFAccount($account){
  2804. if (!$this->access_token && !$this->checkAuth()) return false;
  2805. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_DEL_URL.'access_token='.$this->access_token.'&kf_account='.$account);
  2806. if ($result)
  2807. {
  2808. $json = json_decode($result,true);
  2809. if (!$json || !empty($json['errcode'])) {
  2810. $this->errCode = $json['errcode'];
  2811. $this->errMsg = $json['errmsg'];
  2812. return false;
  2813. }
  2814. return $json;
  2815. }
  2816. return false;
  2817. }
  2818. /**
  2819. * 上传客服头像
  2820. *
  2821. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2822. * @param string $imgfile //头像文件完整路径,如:'D:\user.jpg'。头像文件必须JPG格式,像素建议640*640
  2823. * @return boolean|array
  2824. * 成功返回结果
  2825. * {
  2826. * "errcode": 0,
  2827. * "errmsg": "ok",
  2828. * }
  2829. */
  2830. public function setKFHeadImg($account,$imgfile){
  2831. if (!$this->access_token && !$this->checkAuth()) return false;
  2832. $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);
  2833. if ($result)
  2834. {
  2835. $json = json_decode($result,true);
  2836. if (!$json || !empty($json['errcode'])) {
  2837. $this->errCode = $json['errcode'];
  2838. $this->errMsg = $json['errmsg'];
  2839. return false;
  2840. }
  2841. return $json;
  2842. }
  2843. return false;
  2844. }
  2845. /**
  2846. * 语义理解接口
  2847. * @param String $uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
  2848. * @param String $query 输入文本串
  2849. * @param String $category 需要使用的服务类型,多个用“,”隔开,不能为空
  2850. * @param Float $latitude 纬度坐标,与经度同时传入;与城市二选一传入
  2851. * @param Float $longitude 经度坐标,与纬度同时传入;与城市二选一传入
  2852. * @param String $city 城市名称,与经纬度二选一传入
  2853. * @param String $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入
  2854. * @return boolean|array
  2855. */
  2856. public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
  2857. if (!$this->access_token && !$this->checkAuth()) return false;
  2858. $data=array(
  2859. 'query' => $query,
  2860. 'category' => $category,
  2861. 'appid' => $this->appid,
  2862. 'uid' => ''
  2863. );
  2864. //地理坐标或城市名称二选一
  2865. if ($latitude) {
  2866. $data['latitude'] = $latitude;
  2867. $data['longitude'] = $longitude;
  2868. } elseif ($city) {
  2869. $data['city'] = $city;
  2870. } elseif ($region) {
  2871. $data['region'] = $region;
  2872. }
  2873. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
  2874. if ($result)
  2875. {
  2876. $json = json_decode($result,true);
  2877. if (!$json || !empty($json['errcode'])) {
  2878. $this->errCode = $json['errcode'];
  2879. $this->errMsg = $json['errmsg'];
  2880. return false;
  2881. }
  2882. return $json;
  2883. }
  2884. return false;
  2885. }
  2886. /**
  2887. * 创建卡券
  2888. * @param Array $data 卡券数据
  2889. * @return array|boolean 返回数组中card_id为卡券ID
  2890. */
  2891. public function createCard($data) {
  2892. if (!$this->access_token && !$this->checkAuth()) return false;
  2893. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2894. if ($result) {
  2895. $json = json_decode($result, true);
  2896. if (!$json || !empty($json['errcode'])) {
  2897. $this->errCode = $json['errcode'];
  2898. $this->errMsg = $json['errmsg'];
  2899. return false;
  2900. }
  2901. return $json;
  2902. }
  2903. return false;
  2904. }
  2905. /**
  2906. * 更改卡券信息
  2907. * 调用该接口更新信息后会重新送审,卡券状态变更为待审核。已被用户领取的卡券会实时更新票面信息。
  2908. * @param string $data
  2909. * @return boolean
  2910. */
  2911. public function updateCard($data) {
  2912. if (!$this->access_token && !$this->checkAuth()) return false;
  2913. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2914. if ($result) {
  2915. $json = json_decode($result, true);
  2916. if (!$json || !empty($json['errcode'])) {
  2917. $this->errCode = $json['errcode'];
  2918. $this->errMsg = $json['errmsg'];
  2919. return false;
  2920. }
  2921. return true;
  2922. }
  2923. return false;
  2924. }
  2925. /**
  2926. * 删除卡券
  2927. * 允许商户删除任意一类卡券。删除卡券后,该卡券对应已生成的领取用二维码、添加到卡包 JS API 均会失效。
  2928. * 注意:删除卡券不能删除已被用户领取,保存在微信客户端中的卡券,已领取的卡券依旧有效。
  2929. * @param string $card_id 卡券ID
  2930. * @return boolean
  2931. */
  2932. public function delCard($card_id) {
  2933. $data = array(
  2934. 'card_id' => $card_id,
  2935. );
  2936. if (!$this->access_token && !$this->checkAuth()) return false;
  2937. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  2938. if ($result) {
  2939. $json = json_decode($result, true);
  2940. if (!$json || !empty($json['errcode'])) {
  2941. $this->errCode = $json['errcode'];
  2942. $this->errMsg = $json['errmsg'];
  2943. return false;
  2944. }
  2945. return true;
  2946. }
  2947. return false;
  2948. }
  2949. /**
  2950. * 查询卡券详情
  2951. * @param string $card_id
  2952. * @return boolean|array 返回数组信息比较复杂,请参看卡券接口文档
  2953. */
  2954. public function getCardInfo($card_id) {
  2955. $data = array(
  2956. 'card_id' => $card_id,
  2957. );
  2958. if (!$this->access_token && !$this->checkAuth()) return false;
  2959. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  2960. if ($result) {
  2961. $json = json_decode($result, true);
  2962. if (!$json || !empty($json['errcode'])) {
  2963. $this->errCode = $json['errcode'];
  2964. $this->errMsg = $json['errmsg'];
  2965. return false;
  2966. }
  2967. return $json;
  2968. }
  2969. return false;
  2970. }
  2971. /**
  2972. * 获取颜色列表
  2973. * 获得卡券的最新颜色列表,用于创建卡券
  2974. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  2975. */
  2976. public function getCardColors() {
  2977. if (!$this->access_token && !$this->checkAuth()) return false;
  2978. $result = $this->http_get(self::API_BASE_URL_PREFIX . self::CARD_GETCOLORS . 'access_token=' . $this->access_token);
  2979. if ($result) {
  2980. $json = json_decode($result, true);
  2981. if (!$json || !empty($json['errcode'])) {
  2982. $this->errCode = $json['errcode'];
  2983. $this->errMsg = $json['errmsg'];
  2984. return false;
  2985. }
  2986. return $json;
  2987. }
  2988. return false;
  2989. }
  2990. /**
  2991. * 拉取门店列表
  2992. * 获取在公众平台上申请创建的门店列表
  2993. * @param int $offset 开始拉取的偏移,默认为0从头开始
  2994. * @param int $count 拉取的数量,默认为0拉取全部
  2995. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  2996. */
  2997. public function getCardLocations($offset=0,$count=0) {
  2998. $data=array(
  2999. 'offset'=>$offset,
  3000. 'count'=>$count
  3001. );
  3002. if (!$this->access_token && !$this->checkAuth()) return false;
  3003. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  3004. if ($result) {
  3005. $json = json_decode($result, true);
  3006. if (!$json || !empty($json['errcode'])) {
  3007. $this->errCode = $json['errcode'];
  3008. $this->errMsg = $json['errmsg'];
  3009. return false;
  3010. }
  3011. return $json;
  3012. }
  3013. return false;
  3014. }
  3015. /**
  3016. * 批量导入门店信息
  3017. * @tutorial 返回插入的门店id列表,以逗号分隔。如果有插入失败的,则为-1,请自行核查是哪个插入失败
  3018. * @param array $data 数组形式的json数据,由于内容较多,具体内容格式请查看 微信卡券接口文档
  3019. * @return boolean|string 成功返回插入的门店id列表
  3020. */
  3021. public function addCardLocations($data) {
  3022. if (!$this->access_token && !$this->checkAuth()) return false;
  3023. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHADD . 'access_token=' . $this->access_token, self::json_encode($data));
  3024. if ($result) {
  3025. $json = json_decode($result, true);
  3026. if (!$json || !empty($json['errcode'])) {
  3027. $this->errCode = $json['errcode'];
  3028. $this->errMsg = $json['errmsg'];
  3029. return false;
  3030. }
  3031. return $json;
  3032. }
  3033. return false;
  3034. }
  3035. /**
  3036. * 生成卡券二维码
  3037. * 成功则直接返回ticket值,可以用 getQRUrl($ticket) 换取二维码url
  3038. *
  3039. * @param string $cardid 卡券ID 必须
  3040. * @param string $code 指定卡券 code 码,只能被领一次。use_custom_code 字段为 true 的卡券必须填写,非自定义 code 不必填写。
  3041. * @param string $openid 指定领取者的 openid,只有该用户能领取。bind_openid 字段为 true 的卡券必须填写,非自定义 openid 不必填写。
  3042. * @param int $expire_seconds 指定二维码的有效时间,范围是 60 ~ 1800 秒。不填默认为永久有效。
  3043. * @param boolean $is_unique_code 指定下发二维码,生成的二维码随机分配一个 code,领取后不可再次扫描。填写 true 或 false。默认 false。
  3044. * @param string $balance 红包余额,以分为单位。红包类型必填(LUCKY_MONEY),其他卡券类型不填。
  3045. * @return boolean|string
  3046. */
  3047. public function createCardQrcode($card_id,$code='',$openid='',$expire_seconds=0,$is_unique_code=false,$balance='') {
  3048. $card = array(
  3049. 'card_id' => $card_id
  3050. );
  3051. $data = array(
  3052. 'action_name' => "QR_CARD"
  3053. );
  3054. if ($code)
  3055. $card['code'] = $code;
  3056. if ($openid)
  3057. $card['openid'] = $openid;
  3058. if ($is_unique_code)
  3059. $card['is_unique_code'] = $is_unique_code;
  3060. if ($balance)
  3061. $card['balance'] = $balance;
  3062. if ($expire_seconds)
  3063. $data['expire_seconds'] = $expire_seconds;
  3064. $data['action_info'] = array('card' => $card);
  3065. if (!$this->access_token && !$this->checkAuth()) return false;
  3066. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_QRCODE_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3067. if ($result) {
  3068. $json = json_decode($result, true);
  3069. if (!$json || !empty($json['errcode'])) {
  3070. $this->errCode = $json['errcode'];
  3071. $this->errMsg = $json['errmsg'];
  3072. return false;
  3073. }
  3074. return $json;
  3075. }
  3076. return false;
  3077. }
  3078. /**
  3079. * 消耗 code
  3080. * 自定义 code(use_custom_code 为 true)的优惠券,在 code 被核销时,必须调用此接口。
  3081. *
  3082. * @param string $code 要消耗的序列号
  3083. * @param string $card_id 要消耗序列号所述的 card_id,创建卡券时use_custom_code 填写 true 时必填。
  3084. * @return boolean|array
  3085. * {
  3086. * "errcode":0,
  3087. * "errmsg":"ok",
  3088. * "card":{"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"},
  3089. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA"
  3090. * }
  3091. */
  3092. public function consumeCardCode($code,$card_id='') {
  3093. $data = array('code' => $code);
  3094. if ($card_id)
  3095. $data['card_id'] = $card_id;
  3096. if (!$this->access_token && !$this->checkAuth()) return false;
  3097. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_CONSUME . 'access_token=' . $this->access_token, self::json_encode($data));
  3098. if ($result) {
  3099. $json = json_decode($result, true);
  3100. if (!$json || !empty($json['errcode'])) {
  3101. $this->errCode = $json['errcode'];
  3102. $this->errMsg = $json['errmsg'];
  3103. return false;
  3104. }
  3105. return $json;
  3106. }
  3107. return false;
  3108. }
  3109. /**
  3110. * code 解码
  3111. * @param string $encrypt_code 通过 choose_card_info 获取的加密字符串
  3112. * @return boolean|array
  3113. * {
  3114. * "errcode":0,
  3115. * "errmsg":"ok",
  3116. * "code":"751234212312"
  3117. * }
  3118. */
  3119. public function decryptCardCode($encrypt_code) {
  3120. $data = array(
  3121. 'encrypt_code' => $encrypt_code,
  3122. );
  3123. if (!$this->access_token && !$this->checkAuth()) return false;
  3124. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_DECRYPT . 'access_token=' . $this->access_token, self::json_encode($data));
  3125. if ($result) {
  3126. $json = json_decode($result, true);
  3127. if (!$json || !empty($json['errcode'])) {
  3128. $this->errCode = $json['errcode'];
  3129. $this->errMsg = $json['errmsg'];
  3130. return false;
  3131. }
  3132. return $json;
  3133. }
  3134. return false;
  3135. }
  3136. /**
  3137. * 查询 code 的有效性(非自定义 code)
  3138. * @param string $code
  3139. * @return boolean|array
  3140. * {
  3141. * "errcode":0,
  3142. * "errmsg":"ok",
  3143. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA", //用户 openid
  3144. * "card":{
  3145. * "card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc",
  3146. * "begin_time": 1404205036, //起始使用时间
  3147. * "end_time": 1404205036, //结束时间
  3148. * }
  3149. * }
  3150. */
  3151. public function checkCardCode($code) {
  3152. $data = array(
  3153. 'code' => $code,
  3154. );
  3155. if (!$this->access_token && !$this->checkAuth()) return false;
  3156. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  3157. if ($result) {
  3158. $json = json_decode($result, true);
  3159. if (!$json || !empty($json['errcode'])) {
  3160. $this->errCode = $json['errcode'];
  3161. $this->errMsg = $json['errmsg'];
  3162. return false;
  3163. }
  3164. return $json;
  3165. }
  3166. return false;
  3167. }
  3168. /**
  3169. * 批量查询卡列表
  3170. * @param $offset 开始拉取的偏移,默认为0从头开始
  3171. * @param $count 需要查询的卡片的数量(数量最大50,默认50)
  3172. * @return boolean|array
  3173. * {
  3174. * "errcode":0,
  3175. * "errmsg":"ok",
  3176. * "card_id_list":["ph_gmt7cUVrlRk8swPwx7aDyF-pg"], //卡 id 列表
  3177. * "total_num":1 //该商户名下 card_id 总数
  3178. * }
  3179. */
  3180. public function getCardIdList($offset=0,$count=50) {
  3181. if ($count>50)
  3182. $count = 50;
  3183. $data = array(
  3184. 'offset' => $offset,
  3185. 'count' => $count,
  3186. );
  3187. if (!$this->access_token && !$this->checkAuth()) return false;
  3188. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  3189. if ($result) {
  3190. $json = json_decode($result, true);
  3191. if (!$json || !empty($json['errcode'])) {
  3192. $this->errCode = $json['errcode'];
  3193. $this->errMsg = $json['errmsg'];
  3194. return false;
  3195. }
  3196. return $json;
  3197. }
  3198. return false;
  3199. }
  3200. /**
  3201. * 更改 code
  3202. * 为确保转赠后的安全性,微信允许自定义code的商户对已下发的code进行更改。
  3203. * 注:为避免用户疑惑,建议仅在发生转赠行为后(发生转赠后,微信会通过事件推送的方式告知商户被转赠的卡券code)对用户的code进行更改。
  3204. * @param string $code 卡券的 code 编码
  3205. * @param string $card_id 卡券 ID
  3206. * @param string $new_code 新的卡券 code 编码
  3207. * @return boolean
  3208. */
  3209. public function updateCardCode($code,$card_id,$new_code) {
  3210. $data = array(
  3211. 'code' => $code,
  3212. 'card_id' => $card_id,
  3213. 'new_code' => $new_code,
  3214. );
  3215. if (!$this->access_token && !$this->checkAuth()) return false;
  3216. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3217. if ($result) {
  3218. $json = json_decode($result, true);
  3219. if (!$json || !empty($json['errcode'])) {
  3220. $this->errCode = $json['errcode'];
  3221. $this->errMsg = $json['errmsg'];
  3222. return false;
  3223. }
  3224. return true;
  3225. }
  3226. return false;
  3227. }
  3228. /**
  3229. * 设置卡券失效
  3230. * 设置卡券失效的操作不可逆
  3231. * @param string $code 需要设置为失效的 code
  3232. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 的卡券不填。
  3233. * @return boolean
  3234. */
  3235. public function unavailableCardCode($code,$card_id='') {
  3236. $data = array(
  3237. 'code' => $code,
  3238. );
  3239. if ($card_id)
  3240. $data['card_id'] = $card_id;
  3241. if (!$this->access_token && !$this->checkAuth()) return false;
  3242. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UNAVAILABLE . 'access_token=' . $this->access_token, self::json_encode($data));
  3243. if ($result) {
  3244. $json = json_decode($result, true);
  3245. if (!$json || !empty($json['errcode'])) {
  3246. $this->errCode = $json['errcode'];
  3247. $this->errMsg = $json['errmsg'];
  3248. return false;
  3249. }
  3250. return true;
  3251. }
  3252. return false;
  3253. }
  3254. /**
  3255. * 库存修改
  3256. * @param string $data
  3257. * @return boolean
  3258. */
  3259. public function modifyCardStock($data) {
  3260. if (!$this->access_token && !$this->checkAuth()) return false;
  3261. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MODIFY_STOCK . 'access_token=' . $this->access_token, self::json_encode($data));
  3262. if ($result) {
  3263. $json = json_decode($result, true);
  3264. if (!$json || !empty($json['errcode'])) {
  3265. $this->errCode = $json['errcode'];
  3266. $this->errMsg = $json['errmsg'];
  3267. return false;
  3268. }
  3269. return true;
  3270. }
  3271. return false;
  3272. }
  3273. /**
  3274. * 更新门票
  3275. * @param string $data
  3276. * @return boolean
  3277. */
  3278. public function updateMeetingCard($data) {
  3279. if (!$this->access_token && !$this->checkAuth()) return false;
  3280. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEETINGCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  3281. if ($result) {
  3282. $json = json_decode($result, true);
  3283. if (!$json || !empty($json['errcode'])) {
  3284. $this->errCode = $json['errcode'];
  3285. $this->errMsg = $json['errmsg'];
  3286. return false;
  3287. }
  3288. return true;
  3289. }
  3290. return false;
  3291. }
  3292. /**
  3293. * 激活/绑定会员卡
  3294. * @param string $data 具体结构请参看卡券开发文档(6.1.1 激活/绑定会员卡)章节
  3295. * @return boolean
  3296. */
  3297. public function activateMemberCard($data) {
  3298. if (!$this->access_token && !$this->checkAuth()) return false;
  3299. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_ACTIVATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3300. if ($result) {
  3301. $json = json_decode($result, true);
  3302. if (!$json || !empty($json['errcode'])) {
  3303. $this->errCode = $json['errcode'];
  3304. $this->errMsg = $json['errmsg'];
  3305. return false;
  3306. }
  3307. return true;
  3308. }
  3309. return false;
  3310. }
  3311. /**
  3312. * 会员卡交易
  3313. * 会员卡交易后每次积分及余额变更需通过接口通知微信,便于后续消息通知及其他扩展功能。
  3314. * @param string $data 具体结构请参看卡券开发文档(6.1.2 会员卡交易)章节
  3315. * @return boolean|array
  3316. */
  3317. public function updateMemberCard($data) {
  3318. if (!$this->access_token && !$this->checkAuth()) return false;
  3319. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  3320. if ($result) {
  3321. $json = json_decode($result, true);
  3322. if (!$json || !empty($json['errcode'])) {
  3323. $this->errCode = $json['errcode'];
  3324. $this->errMsg = $json['errmsg'];
  3325. return false;
  3326. }
  3327. return $json;
  3328. }
  3329. return false;
  3330. }
  3331. /**
  3332. * 更新红包金额
  3333. * @param string $code 红包的序列号
  3334. * @param $balance 红包余额
  3335. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 可不填。
  3336. * @return boolean|array
  3337. */
  3338. public function updateLuckyMoney($code,$balance,$card_id='') {
  3339. $data = array(
  3340. 'code' => $code,
  3341. 'balance' => $balance
  3342. );
  3343. if ($card_id)
  3344. $data['card_id'] = $card_id;
  3345. if (!$this->access_token && !$this->checkAuth()) return false;
  3346. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LUCKYMONEY_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3347. if ($result) {
  3348. $json = json_decode($result, true);
  3349. if (!$json || !empty($json['errcode'])) {
  3350. $this->errCode = $json['errcode'];
  3351. $this->errMsg = $json['errmsg'];
  3352. return false;
  3353. }
  3354. return true;
  3355. }
  3356. return false;
  3357. }
  3358. /**
  3359. * 设置卡券测试白名单
  3360. * @param string $openid 测试的 openid 列表
  3361. * @param string $user 测试的微信号列表
  3362. * @return boolean
  3363. */
  3364. public function setCardTestWhiteList($openid=array(),$user=array()) {
  3365. $data = array();
  3366. if (count($openid) > 0)
  3367. $data['openid'] = $openid;
  3368. if (count($user) > 0)
  3369. $data['username'] = $user;
  3370. if (!$this->access_token && !$this->checkAuth()) return false;
  3371. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_TESTWHILELIST_SET . 'access_token=' . $this->access_token, self::json_encode($data));
  3372. if ($result) {
  3373. $json = json_decode($result, true);
  3374. if (!$json || !empty($json['errcode'])) {
  3375. $this->errCode = $json['errcode'];
  3376. $this->errMsg = $json['errmsg'];
  3377. return false;
  3378. }
  3379. return true;
  3380. }
  3381. return false;
  3382. }
  3383. /**
  3384. * 申请设备ID
  3385. * [applyShakeAroundDevice 申请配置设备所需的UUID、Major、Minor。
  3386. * 若激活率小于50%,不能新增设备。单次新增设备超过500 个,需走人工审核流程。
  3387. * 审核通过后,可用迒回的批次ID 用“查询设备列表”接口拉取本次申请的设备ID]
  3388. * @param array $data
  3389. * array(
  3390. * "quantity" => 3, //申请的设备ID 的数量,单次新增设备超过500 个,需走人工审核流程(必填)
  3391. * "apply_reason" => "测试",//申请理由(必填)
  3392. * "comment" => "测试专用", //备注(非必填)
  3393. * "poi_id" => 1234 //设备关联的门店ID(非必填)
  3394. * )
  3395. * @return boolean|mixed
  3396. * {
  3397. "data": {
  3398. "apply_id": 123,
  3399. "device_identifiers":[
  3400. {
  3401. "device_id":10100,
  3402. "uuid":"FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3403. "major":10001,
  3404. "minor":10002
  3405. }
  3406. ]
  3407. },
  3408. "errcode": 0,
  3409. "errmsg": "success."
  3410. }
  3411. apply_id:申请的批次ID,可用在“查询设备列表”接口按批次查询本次申请成功的设备ID
  3412. device_identifiers:指定的设备ID 列表
  3413. device_id:设备编号
  3414. uuid、major、minor
  3415. audit_status:审核状态。0:审核未通过、1:审核中、2:审核已通过;审核会在三个工作日内完成
  3416. audit_comment:审核备注,包括审核不通过的原因
  3417. * @access public
  3418. * @author polo<gao.bo168@gmail.com>
  3419. * @version 2015-3-25 下午1:24:06
  3420. * @copyright Show More
  3421. */
  3422. public function applyShakeAroundDevice($data){
  3423. if (!$this->access_token && !$this->checkAuth()) return false;
  3424. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_APPLYID . 'access_token=' . $this->access_token, self::json_encode($data));
  3425. $this->log($result);
  3426. if ($result) {
  3427. $json = json_decode($result, true);
  3428. if (!$json || !empty($json['errcode'])) {
  3429. $this->errCode = $json['errcode'];
  3430. $this->errMsg = $json['errmsg'];
  3431. return false;
  3432. }
  3433. return $json;
  3434. }
  3435. return false;
  3436. }
  3437. /**
  3438. * 编辑设备信息
  3439. * [updateShakeAroundDevice 编辑设备的备注信息。可用设备ID或完整的UUID、Major、Minor指定设备,二者选其一。]
  3440. * @param array $data
  3441. * array(
  3442. * "device_identifier" => array(
  3443. * "device_id" => 10011, //当提供了device_id则不需要使用uuid、major、minor,反之亦然
  3444. * "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3445. * "major" => 1002,
  3446. * "minor" => 1223
  3447. * ),
  3448. * "comment" => "测试专用", //备注(非必填)
  3449. * )
  3450. * {
  3451. "data": {
  3452. },
  3453. "errcode": 0,
  3454. "errmsg": "success."
  3455. }
  3456. * @return boolean
  3457. * @author binsee<binsee@163.com>
  3458. * @version 2015-4-20 23:45:00
  3459. */
  3460. public function updateShakeAroundDevice($data){
  3461. if (!$this->access_token && !$this->checkAuth()) return false;
  3462. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3463. $this->log($result);
  3464. if ($result) {
  3465. $json = json_decode($result, true);
  3466. if (!$json || !empty($json['errcode'])) {
  3467. $this->errCode = $json['errcode'];
  3468. $this->errMsg = $json['errmsg'];
  3469. return false;
  3470. }
  3471. return true;
  3472. }
  3473. return false;
  3474. }
  3475. /**
  3476. * 查询设备列表
  3477. * [searchShakeAroundDevice 查询已有的设备ID、UUID、Major、Minor、激活状态、备注信息、关联门店、关联页面等信息。
  3478. * 可指定设备ID 或完整的UUID、Major、Minor 查询,也可批量拉取设备信息列表。]
  3479. * @param array $data
  3480. * $data 三种格式:
  3481. * ①查询指定设备时:$data = array(
  3482. * "device_identifiers" => array(
  3483. * array(
  3484. * "device_id" => 10100,
  3485. * "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3486. * "major" => 10001,
  3487. * "minor" => 10002
  3488. * )
  3489. * )
  3490. * );
  3491. * device_identifiers:指定的设备
  3492. * device_id:设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3493. * uuid、major、minor:三个信息需填写完整,若填了设备编号,则可不填此信息
  3494. * +-------------------------------------------------------------------------------------------------------------
  3495. * ②需要分页查询或者指定范围内的设备时: $data = array(
  3496. * "begin" => 0,
  3497. * "count" => 3
  3498. * );
  3499. * begin:设备列表的起始索引值
  3500. * count:待查询的设备个数
  3501. * +-------------------------------------------------------------------------------------------------------------
  3502. * ③当需要根据批次ID 查询时: $data = array(
  3503. * "apply_id" => 1231,
  3504. * "begin" => 0,
  3505. * "count" => 3
  3506. * );
  3507. * apply_id:批次ID
  3508. * +-------------------------------------------------------------------------------------------------------------
  3509. * @return boolean|mixed
  3510. *正确迒回JSON 数据示例:
  3511. *字段说明
  3512. {
  3513. "data": {
  3514. "devices": [ //指定的设备信息列表
  3515. {
  3516. "comment": "", //设备的备注信息
  3517. "device_id": 10097, //设备编号
  3518. "major": 10001,
  3519. "minor": 12102,
  3520. "page_ids": "15369", //与此设备关联的页面ID 列表,用逗号隔开
  3521. "status": 1, //激活状态,0:未激活,1:已激活(但不活跃),2:活跃
  3522. "poi_id": 0, //门店ID
  3523. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3524. },
  3525. {
  3526. "comment": "", //设备的备注信息
  3527. "device_id": 10098, //设备编号
  3528. "major": 10001,
  3529. "minor": 12103,
  3530. "page_ids": "15368", //与此设备关联的页面ID 列表,用逗号隔开
  3531. "status": 1, //激活状态,0:未激活,1:已激活(但不活跃),2:活跃
  3532. "poi_id": 0, //门店ID
  3533. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3534. }
  3535. ],
  3536. "total_count": 151 //商户名下的设备总量
  3537. },
  3538. "errcode": 0,
  3539. "errmsg": "success."
  3540. }
  3541. * @access public
  3542. * @author polo<gao.bo168@gmail.com>
  3543. * @version 2015-3-25 下午1:45:42
  3544. * @copyright Show More
  3545. */
  3546. public function searchShakeAroundDevice($data){
  3547. if (!$this->access_token && !$this->checkAuth()) return false;
  3548. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
  3549. $this->log($result);
  3550. if ($result) {
  3551. $json = json_decode($result, true);
  3552. if (!$json || !empty($json['errcode'])) {
  3553. $this->errCode = $json['errcode'];
  3554. $this->errMsg = $json['errmsg'];
  3555. return false;
  3556. }
  3557. return $json;
  3558. }
  3559. return false;
  3560. }
  3561. /**
  3562. * [bindLocationShakeAroundDevice 配置设备与门店的关联关系]
  3563. * @param string $device_id 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3564. * @param int $poi_id 待关联的门店ID
  3565. * @param string $uuid UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息
  3566. * @param int $major
  3567. * @param int $minor
  3568. * @return boolean|mixed
  3569. * 正确返回JSON 数据示例:
  3570. * {
  3571. "data": {
  3572. },
  3573. "errcode": 0,
  3574. "errmsg": "success."
  3575. }
  3576. * @access public
  3577. * @author polo<gao.bo168@gmail.com>
  3578. * @version 2015-4-21 00:14:00
  3579. * @copyright Show More
  3580. */
  3581. public function bindLocationShakeAroundDevice($device_id,$poi_id,$uuid='',$major=0,$minor=0){
  3582. if (!$this->access_token && !$this->checkAuth()) return false;
  3583. if(!$device_id){
  3584. if(!$uuid || !$major || !$minor){
  3585. return false;
  3586. }
  3587. $device_identifier = array(
  3588. 'uuid' => $uuid,
  3589. 'major' => $major,
  3590. 'minor' => $minor
  3591. );
  3592. }else{
  3593. $device_identifier = array(
  3594. 'device_id' => $device_id
  3595. );
  3596. }
  3597. $data = array(
  3598. 'device_identifier' => $device_identifier,
  3599. 'poi_id' => $poi_id
  3600. );
  3601. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDLOCATION . 'access_token=' . $this->access_token, self::json_encode($data));
  3602. $this->log($result);
  3603. if ($result) {
  3604. $json = json_decode($result, true);
  3605. if (!$json || !empty($json['errcode'])) {
  3606. $this->errCode = $json['errcode'];
  3607. $this->errMsg = $json['errmsg'];
  3608. return false;
  3609. }
  3610. return $json; //这个可以更改为返回true
  3611. }
  3612. return false;
  3613. }
  3614. /**
  3615. * [bindPageShakeAroundDevice 配置设备与页面的关联关系。
  3616. * 支持建立或解除关联关系,也支持新增页面或覆盖页面等操作。
  3617. * 配置完成后,在此设备的信号范围内,即可摇出关联的页面信息。
  3618. * 若设备配置多个页面,则随机出现页面信息]
  3619. * @param string $device_id 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3620. * @param array $page_ids 待关联的页面列表
  3621. * @param number $bind 关联操作标志位, 0 为解除关联关系,1 为建立关联关系
  3622. * @param number $append 新增操作标志位, 0 为覆盖,1 为新增
  3623. * @param string $uuid UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息
  3624. * @param int $major
  3625. * @param int $minor
  3626. * @return boolean|mixed
  3627. * 正确返回JSON 数据示例:
  3628. * {
  3629. "data": {
  3630. },
  3631. "errcode": 0,
  3632. "errmsg": "success."
  3633. }
  3634. * @access public
  3635. * @author polo<gao.bo168@gmail.com>
  3636. * @version 2015-4-21 00:31:00
  3637. * @copyright Show More
  3638. */
  3639. public function bindPageShakeAroundDevice($device_id,$page_ids=array(),$bind=1,$append=1,$uuid='',$major=0,$minor=0){
  3640. if (!$this->access_token && !$this->checkAuth()) return false;
  3641. if(!$device_id){
  3642. if(!$uuid || !$major || !$minor){
  3643. return false;
  3644. }
  3645. $device_identifier = array(
  3646. 'uuid' => $uuid,
  3647. 'major' => $major,
  3648. 'minor' => $minor
  3649. );
  3650. }else{
  3651. $device_identifier = array(
  3652. 'device_id' => $device_id
  3653. );
  3654. }
  3655. $data = array(
  3656. 'device_identifier' => $device_identifier,
  3657. 'page_ids' => $page_ids,
  3658. 'bind' => $bind,
  3659. 'append' => $append
  3660. );
  3661. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDPAGE . 'access_token=' . $this->access_token, self::json_encode($data));
  3662. $this->log($result);
  3663. if ($result) {
  3664. $json = json_decode($result, true);
  3665. if (!$json || !empty($json['errcode'])) {
  3666. $this->errCode = $json['errcode'];
  3667. $this->errMsg = $json['errmsg'];
  3668. return false;
  3669. }
  3670. return $json;
  3671. }
  3672. return false;
  3673. }
  3674. /**
  3675. * 上传在摇一摇页面展示的图片素材
  3676. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  3677. * @param array $data {"media":'@Path\filename.jpg'} 格式限定为:jpg,jpeg,png,gif,图片大小建议120px*120 px,限制不超过200 px *200 px,图片需为正方形。
  3678. * @return boolean|array
  3679. * {
  3680. "data": {
  3681. "pic_url":"http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
  3682. },
  3683. "errcode": 0,
  3684. "errmsg": "success."
  3685. }
  3686. }
  3687. * @author binsee<binsee@163.com>
  3688. * @version 2015-4-21 00:51:00
  3689. */
  3690. public function uploadShakeAroundMedia($data){
  3691. if (!$this->access_token && !$this->checkAuth()) return false;
  3692. $result = $this->http_post(self::API_URL_PREFIX.self::SHAKEAROUND_MATERIAL_ADD.'access_token='.$this->access_token,$data,true);
  3693. if ($result)
  3694. {
  3695. $json = json_decode($result,true);
  3696. if (!$json || !empty($json['errcode'])) {
  3697. $this->errCode = $json['errcode'];
  3698. $this->errMsg = $json['errmsg'];
  3699. return false;
  3700. }
  3701. return $json;
  3702. }
  3703. return false;
  3704. }
  3705. /**
  3706. * [addShakeAroundPage 增加摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。]
  3707. * @param string $title 在摇一摇页面展示的主标题,不超过6 个字
  3708. * @param string $description 在摇一摇页面展示的副标题,不超过7 个字
  3709. * @param sting $icon_url 在摇一摇页面展示的图片, 格式限定为:jpg,jpeg,png,gif; 建议120*120 , 限制不超过200*200
  3710. * @param string $page_url 跳转链接
  3711. * @param string $comment 页面的备注信息,不超过15 个字,可不填
  3712. * @return boolean|mixed
  3713. * 正确返回JSON 数据示例:
  3714. * {
  3715. "data": {
  3716. "page_id": 28840 //新增页面的页面id
  3717. }
  3718. "errcode": 0,
  3719. "errmsg": "success."
  3720. }
  3721. * @access public
  3722. * @author polo<gao.bo168@gmail.com>
  3723. * @version 2015-3-25 下午2:57:09
  3724. * @copyright Show More
  3725. */
  3726. public function addShakeAroundPage($title,$description,$icon_url,$page_url,$comment=''){
  3727. if (!$this->access_token && !$this->checkAuth()) return false;
  3728. $data = array(
  3729. "title" => $title,
  3730. "description" => $description,
  3731. "icon_url" => $icon_url,
  3732. "page_url" => $page_url,
  3733. "comment" => $comment
  3734. );
  3735. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_ADD . 'access_token=' . $this->access_token, self::json_encode($data));
  3736. $this->log($result);
  3737. if ($result) {
  3738. $json = json_decode($result, true);
  3739. if (!$json || !empty($json['errcode'])) {
  3740. $this->errCode = $json['errcode'];
  3741. $this->errMsg = $json['errmsg'];
  3742. return false;
  3743. }
  3744. return $json;
  3745. }
  3746. return false;
  3747. }
  3748. /**
  3749. * [updateShakeAroundPage 编辑摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。]
  3750. * @param int $page_id
  3751. * @param string $title 在摇一摇页面展示的主标题,不超过6 个字
  3752. * @param string $description 在摇一摇页面展示的副标题,不超过7 个字
  3753. * @param sting $icon_url 在摇一摇页面展示的图片, 格式限定为:jpg,jpeg,png,gif; 建议120*120 , 限制不超过200*200
  3754. * @param string $page_url 跳转链接
  3755. * @param string $comment 页面的备注信息,不超过15 个字,可不填
  3756. * @return boolean|mixed
  3757. * 正确返回JSON 数据示例:
  3758. * {
  3759. "data": {
  3760. "page_id": 28840 //编辑页面的页面ID
  3761. }
  3762. "errcode": 0,
  3763. "errmsg": "success."
  3764. }
  3765. * @access public
  3766. * @author polo<gao.bo168@gmail.com>
  3767. * @version 2015-3-25 下午3:02:51
  3768. * @copyright Show More
  3769. */
  3770. public function updateShakeAroundPage($page_id,$title,$description,$icon_url,$page_url,$comment=''){
  3771. if (!$this->access_token && !$this->checkAuth()) return false;
  3772. $data = array(
  3773. "page_id" => $page_id,
  3774. "title" => $title,
  3775. "description" => $description,
  3776. "icon_url" => $icon_url,
  3777. "page_url" => $page_url,
  3778. "comment" => $comment
  3779. );
  3780. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3781. $this->log($result);
  3782. if ($result) {
  3783. $json = json_decode($result, true);
  3784. if (!$json || !empty($json['errcode'])) {
  3785. $this->errCode = $json['errcode'];
  3786. $this->errMsg = $json['errmsg'];
  3787. return false;
  3788. }
  3789. return $json;
  3790. }
  3791. return false;
  3792. }
  3793. /**
  3794. * [searchShakeAroundPage 查询已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
  3795. * 提供两种查询方式,①可指定页面ID 查询,②也可批量拉取页面列表。]
  3796. * @param array $page_ids
  3797. * @param int $begin
  3798. * @param int $count
  3799. * ①需要查询指定页面时:
  3800. * {
  3801. "page_ids":[12345, 23456, 34567]
  3802. }
  3803. * +-------------------------------------------------------------------------------------------------------------
  3804. * ②需要分页查询或者指定范围内的页面时:
  3805. * {
  3806. "begin": 0,
  3807. "count": 3
  3808. }
  3809. * +-------------------------------------------------------------------------------------------------------------
  3810. * @return boolean|mixed
  3811. * 正确返回JSON 数据示例:
  3812. {
  3813. "data": {
  3814. "pages": [
  3815. {
  3816. "comment": "just for test",
  3817. "description": "test",
  3818. "icon_url": "https://www.baidu.com/img/bd_logo1.png",
  3819. "page_id": 28840,
  3820. "page_url": "http://xw.qq.com/testapi1",
  3821. "title": "测试1"
  3822. },
  3823. {
  3824. "comment": "just for test",
  3825. "description": "test",
  3826. "icon_url": "https://www.baidu.com/img/bd_logo1.png",
  3827. "page_id": 28842,
  3828. "page_url": "http://xw.qq.com/testapi2",
  3829. "title": "测试2"
  3830. }
  3831. ],
  3832. "total_count": 2
  3833. },
  3834. "errcode": 0,
  3835. "errmsg": "success."
  3836. }
  3837. *字段说明:
  3838. *total_count 商户名下的页面总数
  3839. *page_id 摇周边页面唯一ID
  3840. *title 在摇一摇页面展示的主标题
  3841. *description 在摇一摇页面展示的副标题
  3842. *icon_url 在摇一摇页面展示的图片
  3843. *page_url 跳转链接
  3844. *comment 页面的备注信息
  3845. * @access public
  3846. * @author polo<gao.bo168@gmail.com>
  3847. * @version 2015-3-25 下午3:12:17
  3848. * @copyright Show More
  3849. */
  3850. public function searchShakeAroundPage($page_ids=array(),$begin=0,$count=1){
  3851. if (!$this->access_token && !$this->checkAuth()) return false;
  3852. if(!empty($page_ids)){
  3853. $data = array(
  3854. 'page_ids' => $page_ids
  3855. );
  3856. }else{
  3857. $data = array(
  3858. 'begin' => $begin,
  3859. 'count' => $count
  3860. );
  3861. }
  3862. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
  3863. $this->log($result);
  3864. if ($result) {
  3865. $json = json_decode($result, true);
  3866. if (!$json || !empty($json['errcode'])) {
  3867. $this->errCode = $json['errcode'];
  3868. $this->errMsg = $json['errmsg'];
  3869. return false;
  3870. }
  3871. return $json;
  3872. }
  3873. return false;
  3874. }
  3875. /**
  3876. * [deleteShakeAroundPage 删除已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
  3877. * 只有页面与设备没有关联关系时,才可被删除。]
  3878. * @param array $page_ids
  3879. * {
  3880. "page_ids":[12345,23456,34567]
  3881. }
  3882. * @return boolean|mixed
  3883. * 正确返回JSON 数据示例:
  3884. * {
  3885. "data": {
  3886. },
  3887. "errcode": 0,
  3888. "errmsg": "success."
  3889. }
  3890. * @access public
  3891. * @author polo<gao.bo168@gmail.com>
  3892. * @version 2015-3-25 下午3:23:00
  3893. * @copyright Show More
  3894. */
  3895. public function deleteShakeAroundPage($page_ids=array()){
  3896. if (!$this->access_token && !$this->checkAuth()) return false;
  3897. $data = array(
  3898. 'page_ids' => $page_ids
  3899. );
  3900. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  3901. $this->log($result);
  3902. if ($result) {
  3903. $json = json_decode($result, true);
  3904. if (!$json || !empty($json['errcode'])) {
  3905. $this->errCode = $json['errcode'];
  3906. $this->errMsg = $json['errmsg'];
  3907. return false;
  3908. }
  3909. return $json;
  3910. }
  3911. return false;
  3912. }
  3913. /**
  3914. * [getShakeInfoShakeAroundUser 获取设备信息,包括UUID、major、minor,以及距离、openID 等信息。]
  3915. * @param string $ticket 摇周边业务的ticket,可在摇到的URL 中得到,ticket生效时间为30 分钟
  3916. * @return boolean|mixed
  3917. * 正确返回JSON 数据示例:
  3918. * {
  3919. "data": {
  3920. "page_id ": 14211,
  3921. "beacon_info": {
  3922. "distance": 55.00620700469034,
  3923. "major": 10001,
  3924. "minor": 19007,
  3925. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3926. },
  3927. "openid": "oVDmXjp7y8aG2AlBuRpMZTb1-cmA"
  3928. },
  3929. "errcode": 0,
  3930. "errmsg": "success."
  3931. }
  3932. * 字段说明:
  3933. * beacon_info 设备信息,包括UUID、major、minor,以及距离
  3934. * UUID、major、minor UUID、major、minor
  3935. * distance Beacon 信号与手机的距离
  3936. * page_id 摇周边页面唯一ID
  3937. * openid 商户AppID 下用户的唯一标识
  3938. * poi_id 门店ID,有的话则返回,没有的话不会在JSON 格式内
  3939. * @access public
  3940. * @author polo<gao.bo168@gmail.com>
  3941. * @version 2015-3-25 下午3:28:20
  3942. * @copyright Show More
  3943. */
  3944. public function getShakeInfoShakeAroundUser($ticket){
  3945. if (!$this->access_token && !$this->checkAuth()) return false;
  3946. $data = array('ticket' => $ticket);
  3947. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_USER_GETSHAKEINFO . 'access_token=' . $this->access_token, self::json_encode($data));
  3948. $this->log($result);
  3949. if ($result) {
  3950. $json = json_decode($result, true);
  3951. if (!$json || !empty($json['errcode'])) {
  3952. $this->errCode = $json['errcode'];
  3953. $this->errMsg = $json['errmsg'];
  3954. return false;
  3955. }
  3956. return $json;
  3957. }
  3958. return false;
  3959. }
  3960. /**
  3961. * [deviceShakeAroundStatistics 以设备为维度的数据统计接口。
  3962. * 查询单个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数;查询的最长时间跨度为30天。]
  3963. * @param int $device_id 设备编号,若填了UUID、major、minor,即可不填设备编号,二者选其一
  3964. * @param int $begin_date 起始日期时间戳,最长时间跨度为30 天
  3965. * @param int $end_date 结束日期时间戳,最长时间跨度为30 天
  3966. * @param string $uuid UUID、major、minor,三个信息需填写完成,若填了设备编辑,即可不填此信息,二者选其一
  3967. * @param int $major
  3968. * @param int $minor
  3969. * @return boolean|mixed
  3970. * 正确返回JSON 数据示例:
  3971. * {
  3972. "data": [
  3973. {
  3974. "click_pv": 0,
  3975. "click_uv": 0,
  3976. "ftime": 1425052800,
  3977. "shake_pv": 0,
  3978. "shake_uv": 0
  3979. },
  3980. {
  3981. "click_pv": 0,
  3982. "click_uv": 0,
  3983. "ftime": 1425139200,
  3984. "shake_pv": 0,
  3985. "shake_uv": 0
  3986. }
  3987. ],
  3988. "errcode": 0,
  3989. "errmsg": "success."
  3990. }
  3991. * 字段说明:
  3992. * ftime 当天0 点对应的时间戳
  3993. * click_pv 点击摇周边消息的次数
  3994. * click_uv 点击摇周边消息的人数
  3995. * shake_pv 摇周边的次数
  3996. * shake_uv 摇周边的人数
  3997. * @access public
  3998. * @author polo<gao.bo168@gmail.com>
  3999. * @version 2015-4-21 00:39:00
  4000. * @copyright Show More
  4001. */
  4002. public function deviceShakeAroundStatistics($device_id,$begin_date,$end_date,$uuid='',$major=0,$minor=0){
  4003. if (!$this->access_token && !$this->checkAuth()) return false;
  4004. if(!$device_id){
  4005. if(!$uuid || !$major || !$minor){
  4006. return false;
  4007. }
  4008. $device_identifier = array(
  4009. 'uuid' => $uuid,
  4010. 'major' => $major,
  4011. 'minor' => $minor
  4012. );
  4013. }else{
  4014. $device_identifier = array(
  4015. 'device_id' => $device_id
  4016. );
  4017. }
  4018. $data = array(
  4019. 'device_identifier' => $device_identifier,
  4020. 'begin_date' => $begin_date,
  4021. 'end_date' => $end_date
  4022. );
  4023. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
  4024. $this->log($result);
  4025. if ($result) {
  4026. $json = json_decode($result, true);
  4027. if (!$json || !empty($json['errcode'])) {
  4028. $this->errCode = $json['errcode'];
  4029. $this->errMsg = $json['errmsg'];
  4030. return false;
  4031. }
  4032. return $json;
  4033. }
  4034. return false;
  4035. }
  4036. /**
  4037. * [pageShakeAroundStatistics 以页面为维度的数据统计接口。
  4038. * 查询单个页面通过摇周边摇出来的人数、次数,点击摇周边页面的人数、次数;查询的最长时间跨度为30天。]
  4039. * @param int $page_id 指定页面的ID
  4040. * @param int $begin_date 起始日期时间戳,最长时间跨度为30 天
  4041. * @param int $end_date 结束日期时间戳,最长时间跨度为30 天
  4042. * @return boolean|mixed
  4043. * 正确返回JSON 数据示例:
  4044. * {
  4045. "data": [
  4046. {
  4047. "click_pv": 0,
  4048. "click_uv": 0,
  4049. "ftime": 1425052800,
  4050. "shake_pv": 0,
  4051. "shake_uv": 0
  4052. },
  4053. {
  4054. "click_pv": 0,
  4055. "click_uv": 0,
  4056. "ftime": 1425139200,
  4057. "shake_pv": 0,
  4058. "shake_uv": 0
  4059. }
  4060. ],
  4061. "errcode": 0,
  4062. "errmsg": "success."
  4063. }
  4064. * 字段说明:
  4065. * ftime 当天0 点对应的时间戳
  4066. * click_pv 点击摇周边消息的次数
  4067. * click_uv 点击摇周边消息的人数
  4068. * shake_pv 摇周边的次数
  4069. * shake_uv 摇周边的人数
  4070. * @author binsee<binsee@163.com>
  4071. * @version 2015-4-21 00:43:00
  4072. */
  4073. public function pageShakeAroundStatistics($page_id,$begin_date,$end_date){
  4074. if (!$this->access_token && !$this->checkAuth()) return false;
  4075. $data = array(
  4076. 'page_id' => $page_id,
  4077. 'begin_date' => $begin_date,
  4078. 'end_date' => $end_date
  4079. );
  4080. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
  4081. $this->log($result);
  4082. if ($result) {
  4083. $json = json_decode($result, true);
  4084. if (!$json || !empty($json['errcode'])) {
  4085. $this->errCode = $json['errcode'];
  4086. $this->errMsg = $json['errmsg'];
  4087. return false;
  4088. }
  4089. return $json;
  4090. }
  4091. return false;
  4092. }
  4093. /**
  4094. * 根据订单ID获取订单详情
  4095. * @param string $order_id 订单ID
  4096. * @return order array|bool
  4097. */
  4098. public function getOrderByID($order_id){
  4099. if (!$this->access_token && !$this->checkAuth()) return false;
  4100. if (!$order_id) return false;
  4101. $data = array(
  4102. 'order_id'=>$order_id
  4103. );
  4104. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_GETBYID.'access_token='.$this->access_token, self::json_encode($data));
  4105. if ($result)
  4106. {
  4107. $json = json_decode($result,true);
  4108. if (isset($json['errcode']) && $json['errcode']) {
  4109. $this->errCode = $json['errcode'];
  4110. $this->errMsg = $json['errmsg'];
  4111. return false;
  4112. }
  4113. return $json['order'];
  4114. }
  4115. return false;
  4116. }
  4117. /**
  4118. * 根据订单状态/创建时间获取订单详情
  4119. * @param int $status 订单状态(不带该字段-全部状态, 2-待发货, 3-已发货, 5-已完成, 8-维权中, )
  4120. * @param int $begintime 订单创建时间起始时间(不带该字段则不按照时间做筛选)
  4121. * @param int $endtime 订单创建时间终止时间(不带该字段则不按照时间做筛选)
  4122. * @return order list array|bool
  4123. */
  4124. public function getOrderByFilter($status = null, $begintime = null, $endtime = null){
  4125. if (!$this->access_token && !$this->checkAuth()) return false;
  4126. $data = array();
  4127. $valid_status = array(2, 3, 5, 8);
  4128. if (is_numeric($status) && in_array($status, $valid_status)) {
  4129. $data['status'] = $status;
  4130. }
  4131. if (is_numeric($begintime) && is_numeric($endtime)) {
  4132. $data['begintime'] = $begintime;
  4133. $data['endtime'] = $endtime;
  4134. }
  4135. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_GETBYFILTER.'access_token='.$this->access_token, self::json_encode($data));
  4136. if ($result)
  4137. {
  4138. $json = json_decode($result,true);
  4139. if (isset($json['errcode']) && $json['errcode']) {
  4140. $this->errCode = $json['errcode'];
  4141. $this->errMsg = $json['errmsg'];
  4142. return false;
  4143. }
  4144. return $json['order_list'];
  4145. }
  4146. return false;
  4147. }
  4148. /**
  4149. * 设置订单发货信息
  4150. * @param string $order_id 订单 ID
  4151. * @param int $need_delivery 商品是否需要物流(0-不需要,1-需要)
  4152. * @param string $delivery_company 物流公司 ID
  4153. * @param string $delivery_track_no 运单 ID
  4154. * @param int $is_others 是否为 6.4.5 表之外的其它物流公司(0-否,1-是)
  4155. * @return bool
  4156. */
  4157. public function setOrderDelivery($order_id, $need_delivery = 0, $delivery_company = null, $delivery_track_no = null, $is_others = 0){
  4158. if (!$this->access_token && !$this->checkAuth()) return false;
  4159. if (!$order_id) return false;
  4160. $data = array();
  4161. $data['order_id'] = $order_id;
  4162. if ($need_delivery) {
  4163. $data['delivery_company'] = $delivery_company;
  4164. $data['delivery_track_no'] = $delivery_track_no;
  4165. $data['is_others'] = $is_others;
  4166. }
  4167. else {
  4168. $data['need_delivery'] = $need_delivery;
  4169. }
  4170. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_SETDELIVERY.'access_token='.$this->access_token, self::json_encode($data));
  4171. if ($result)
  4172. {
  4173. $json = json_decode($result,true);
  4174. if (isset($json['errcode']) && $json['errcode']) {
  4175. $this->errCode = $json['errcode'];
  4176. $this->errMsg = $json['errmsg'];
  4177. return false;
  4178. }
  4179. return true;
  4180. }
  4181. return false;
  4182. }
  4183. /**
  4184. * 关闭订单
  4185. * @param string $order_id 订单 ID
  4186. * @return bool
  4187. */
  4188. public function closeOrder($order_id){
  4189. if (!$this->access_token && !$this->checkAuth()) return false;
  4190. if (!$order_id) return false;
  4191. $data = array(
  4192. 'order_id'=>$order_id
  4193. );
  4194. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_CLOSE.'access_token='.$this->access_token, self::json_encode($data));
  4195. if ($result)
  4196. {
  4197. $json = json_decode($result,true);
  4198. if (isset($json['errcode']) && $json['errcode']) {
  4199. $this->errCode = $json['errcode'];
  4200. $this->errMsg = $json['errmsg'];
  4201. return false;
  4202. }
  4203. return true;
  4204. }
  4205. return false;
  4206. }
  4207. private function parseSkuInfo($skuInfo) {
  4208. $skuInfo = str_replace("\$", "", $skuInfo);
  4209. $matches = explode(";", $skuInfo);
  4210. $result = array();
  4211. foreach ($matches as $matche) {
  4212. $arrs = explode(":", $matche);
  4213. $result[$arrs[0]] = $arrs[1];
  4214. }
  4215. return $result;
  4216. }
  4217. /**
  4218. * 获取订单SkuInfo - 订单付款通知
  4219. * 当Event为 merchant_order(订单付款通知)
  4220. * @return array|boolean
  4221. */
  4222. public function getRevOrderSkuInfo(){
  4223. if (isset($this->_receive['SkuInfo'])) //订单 SkuInfo
  4224. return $this->parseSkuInfo($this->_receive['SkuInfo']);
  4225. else
  4226. return false;
  4227. }
  4228. }
  4229. /**
  4230. * PKCS7Encoder class
  4231. *
  4232. * 提供基于PKCS7算法的加解密接口.
  4233. */
  4234. class PKCS7Encoder
  4235. {
  4236. public static $block_size = 32;
  4237. /**
  4238. * 对需要加密的明文进行填充补位
  4239. * @param $text 需要进行填充补位操作的明文
  4240. * @return 补齐明文字符串
  4241. */
  4242. function encode($text)
  4243. {
  4244. $block_size = PKCS7Encoder::$block_size;
  4245. $text_length = strlen($text);
  4246. //计算需要填充的位数
  4247. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  4248. if ($amount_to_pad == 0) {
  4249. $amount_to_pad = PKCS7Encoder::block_size;
  4250. }
  4251. //获得补位所用的字符
  4252. $pad_chr = chr($amount_to_pad);
  4253. $tmp = "";
  4254. for ($index = 0; $index < $amount_to_pad; $index++) {
  4255. $tmp .= $pad_chr;
  4256. }
  4257. return $text . $tmp;
  4258. }
  4259. /**
  4260. * 对解密后的明文进行补位删除
  4261. * @param decrypted 解密后的明文
  4262. * @return 删除填充补位后的明文
  4263. */
  4264. function decode($text)
  4265. {
  4266. $pad = ord(substr($text, -1));
  4267. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  4268. $pad = 0;
  4269. }
  4270. return substr($text, 0, (strlen($text) - $pad));
  4271. }
  4272. }
  4273. /**
  4274. * Prpcrypt class
  4275. *
  4276. * 提供接收和推送给公众平台消息的加解密接口.
  4277. */
  4278. class Prpcrypt
  4279. {
  4280. public $key;
  4281. function __construct($k) {
  4282. $this->key = base64_decode($k . "=");
  4283. }
  4284. /**
  4285. * 兼容老版本php构造函数,不能在 __construct() 方法前边,否则报错
  4286. */
  4287. function Prpcrypt($k)
  4288. {
  4289. $this->key = base64_decode($k . "=");
  4290. }
  4291. /**
  4292. * 对明文进行加密
  4293. * @param string $text 需要加密的明文
  4294. * @return string 加密后的密文
  4295. */
  4296. public function encrypt($text, $appid)
  4297. {
  4298. try {
  4299. //获得16位随机字符串,填充到明文之前
  4300. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  4301. $text = $random . pack("N", strlen($text)) . $text . $appid;
  4302. // 网络字节序
  4303. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  4304. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  4305. $iv = substr($this->key, 0, 16);
  4306. //使用自定义的填充方式对明文进行补位填充
  4307. $pkc_encoder = new PKCS7Encoder;
  4308. $text = $pkc_encoder->encode($text);
  4309. mcrypt_generic_init($module, $this->key, $iv);
  4310. //加密
  4311. $encrypted = mcrypt_generic($module, $text);
  4312. mcrypt_generic_deinit($module);
  4313. mcrypt_module_close($module);
  4314. // print(base64_encode($encrypted));
  4315. //使用BASE64对加密后的字符串进行编码
  4316. return array(ErrorCode::$OK, base64_encode($encrypted));
  4317. } catch (Exception $e) {
  4318. //print $e;
  4319. return array(ErrorCode::$EncryptAESError, null);
  4320. }
  4321. }
  4322. /**
  4323. * 对密文进行解密
  4324. * @param string $encrypted 需要解密的密文
  4325. * @return string 解密得到的明文
  4326. */
  4327. public function decrypt($encrypted, $appid)
  4328. {
  4329. try {
  4330. //使用BASE64对需要解密的字符串进行解码
  4331. $ciphertext_dec = base64_decode($encrypted);
  4332. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  4333. $iv = substr($this->key, 0, 16);
  4334. mcrypt_generic_init($module, $this->key, $iv);
  4335. //解密
  4336. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  4337. mcrypt_generic_deinit($module);
  4338. mcrypt_module_close($module);
  4339. } catch (Exception $e) {
  4340. return array(ErrorCode::$DecryptAESError, null);
  4341. }
  4342. try {
  4343. //去除补位字符
  4344. $pkc_encoder = new PKCS7Encoder;
  4345. $result = $pkc_encoder->decode($decrypted);
  4346. //去除16位随机字符串,网络字节序和AppId
  4347. if (strlen($result) < 16)
  4348. return "";
  4349. $content = substr($result, 16, strlen($result));
  4350. $len_list = unpack("N", substr($content, 0, 4));
  4351. $xml_len = $len_list[1];
  4352. $xml_content = substr($content, 4, $xml_len);
  4353. $from_appid = substr($content, $xml_len + 4);
  4354. if (!$appid)
  4355. $appid = $from_appid;
  4356. //如果传入的appid是空的,则认为是订阅号,使用数据中提取出来的appid
  4357. } catch (Exception $e) {
  4358. //print $e;
  4359. return array(ErrorCode::$IllegalBuffer, null);
  4360. }
  4361. if ($from_appid != $appid)
  4362. return array(ErrorCode::$ValidateAppidError, null);
  4363. //不注释上边两行,避免传入appid是错误的情况
  4364. return array(0, $xml_content, $from_appid); //增加appid,为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
  4365. }
  4366. /**
  4367. * 随机生成16位字符串
  4368. * @return string 生成的字符串
  4369. */
  4370. function getRandomStr()
  4371. {
  4372. $str = "";
  4373. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  4374. $max = strlen($str_pol) - 1;
  4375. for ($i = 0; $i < 16; $i++) {
  4376. $str .= $str_pol[mt_rand(0, $max)];
  4377. }
  4378. return $str;
  4379. }
  4380. }
  4381. /**
  4382. * error code
  4383. * 仅用作类内部使用,不用于官方API接口的errCode码
  4384. */
  4385. class ErrorCode
  4386. {
  4387. public static $OK = 0;
  4388. public static $ValidateSignatureError = 40001;
  4389. public static $ParseXmlError = 40002;
  4390. public static $ComputeSignatureError = 40003;
  4391. public static $IllegalAesKey = 40004;
  4392. public static $ValidateAppidError = 40005;
  4393. public static $EncryptAESError = 40006;
  4394. public static $DecryptAESError = 40007;
  4395. public static $IllegalBuffer = 40008;
  4396. public static $EncodeBase64Error = 40009;
  4397. public static $DecodeBase64Error = 40010;
  4398. public static $GenReturnXmlError = 40011;
  4399. public static $errCode=array(
  4400. '0' => '处理成功',
  4401. '40001' => '校验签名失败',
  4402. '40002' => '解析xml失败',
  4403. '40003' => '计算签名失败',
  4404. '40004' => '不合法的AESKey',
  4405. '40005' => '校验AppID失败',
  4406. '40006' => 'AES加密失败',
  4407. '40007' => 'AES解密失败',
  4408. '40008' => '公众平台发送的xml不合法',
  4409. '40009' => 'Base64编码失败',
  4410. '40010' => 'Base64解码失败',
  4411. '40011' => '公众帐号生成回包xml失败'
  4412. );
  4413. public static function getErrText($err) {
  4414. if (isset(self::$errCode[$err])) {
  4415. return self::$errCode[$err];
  4416. }else {
  4417. return false;
  4418. };
  4419. }
  4420. }