wechat.class.php 159 KB

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