wechat.class.php 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617
  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. if(PHP_VERSION_ID >= 50500){
  1085. curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, FALSE);
  1086. }
  1087. $sContent = curl_exec($oCurl);
  1088. $aStatus = curl_getinfo($oCurl);
  1089. curl_close($oCurl);
  1090. if(intval($aStatus["http_code"])==200){
  1091. return $sContent;
  1092. }else{
  1093. return false;
  1094. }
  1095. }
  1096. /**
  1097. * 设置缓存,按需重载
  1098. * @param string $cachename
  1099. * @param mixed $value
  1100. * @param int $expired
  1101. * @return boolean
  1102. */
  1103. protected function setCache($cachename,$value,$expired){
  1104. //TODO: set cache implementation
  1105. return false;
  1106. }
  1107. /**
  1108. * 获取缓存,按需重载
  1109. * @param string $cachename
  1110. * @return mixed
  1111. */
  1112. protected function getCache($cachename){
  1113. //TODO: get cache implementation
  1114. return false;
  1115. }
  1116. /**
  1117. * 清除缓存,按需重载
  1118. * @param string $cachename
  1119. * @return boolean
  1120. */
  1121. protected function removeCache($cachename){
  1122. //TODO: remove cache implementation
  1123. return false;
  1124. }
  1125. /**
  1126. * 获取access_token
  1127. * @param string $appid 如在类初始化时已提供,则可为空
  1128. * @param string $appsecret 如在类初始化时已提供,则可为空
  1129. * @param string $token 手动指定access_token,非必要情况不建议用
  1130. */
  1131. public function checkAuth($appid='',$appsecret='',$token=''){
  1132. if (!$appid || !$appsecret) {
  1133. $appid = $this->appid;
  1134. $appsecret = $this->appsecret;
  1135. }
  1136. if ($token) { //手动指定token,优先使用
  1137. $this->access_token=$token;
  1138. return $this->access_token;
  1139. }
  1140. $authname = 'wechat_access_token'.$appid;
  1141. if ($rs = $this->getCache($authname)) {
  1142. $this->access_token = $rs;
  1143. return $rs;
  1144. }
  1145. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  1146. if ($result)
  1147. {
  1148. $json = json_decode($result,true);
  1149. if (!$json || isset($json['errcode'])) {
  1150. $this->errCode = $json['errcode'];
  1151. $this->errMsg = $json['errmsg'];
  1152. return false;
  1153. }
  1154. $this->access_token = $json['access_token'];
  1155. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1156. $this->setCache($authname,$this->access_token,$expire);
  1157. return $this->access_token;
  1158. }
  1159. return false;
  1160. }
  1161. /**
  1162. * 删除验证数据
  1163. * @param string $appid
  1164. */
  1165. public function resetAuth($appid=''){
  1166. if (!$appid) $appid = $this->appid;
  1167. $this->access_token = '';
  1168. $authname = 'wechat_access_token'.$appid;
  1169. $this->removeCache($authname);
  1170. return true;
  1171. }
  1172. /**
  1173. * 删除JSAPI授权TICKET
  1174. * @param string $appid 用于多个appid时使用
  1175. */
  1176. public function resetJsTicket($appid=''){
  1177. if (!$appid) $appid = $this->appid;
  1178. $this->jsapi_ticket = '';
  1179. $authname = 'wechat_jsapi_ticket'.$appid;
  1180. $this->removeCache($authname);
  1181. return true;
  1182. }
  1183. /**
  1184. * 获取JSAPI授权TICKET
  1185. * @param string $appid 用于多个appid时使用,可空
  1186. * @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
  1187. */
  1188. public function getJsTicket($appid='',$jsapi_ticket=''){
  1189. if (!$this->access_token && !$this->checkAuth()) return false;
  1190. if (!$appid) $appid = $this->appid;
  1191. if ($jsapi_ticket) { //手动指定token,优先使用
  1192. $this->jsapi_ticket = $jsapi_ticket;
  1193. return $this->jsapi_ticket;
  1194. }
  1195. $authname = 'wechat_jsapi_ticket'.$appid;
  1196. if ($rs = $this->getCache($authname)) {
  1197. $this->jsapi_ticket = $rs;
  1198. return $rs;
  1199. }
  1200. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=jsapi');
  1201. if ($result)
  1202. {
  1203. $json = json_decode($result,true);
  1204. if (!$json || !empty($json['errcode'])) {
  1205. $this->errCode = $json['errcode'];
  1206. $this->errMsg = $json['errmsg'];
  1207. return false;
  1208. }
  1209. $this->jsapi_ticket = $json['ticket'];
  1210. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1211. $this->setCache($authname,$this->jsapi_ticket,$expire);
  1212. return $this->jsapi_ticket;
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * 获取JsApi使用签名
  1218. * @param string $url 网页的URL,自动处理#及其后面部分
  1219. * @param string $timestamp 当前时间戳 (为空则自动生成)
  1220. * @param string $noncestr 随机串 (为空则自动生成)
  1221. * @param string $appid 用于多个appid时使用,可空
  1222. * @return array|bool 返回签名字串
  1223. */
  1224. public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
  1225. if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
  1226. if (!$timestamp)
  1227. $timestamp = time();
  1228. if (!$noncestr)
  1229. $noncestr = $this->generateNonceStr();
  1230. $ret = strpos($url,'#');
  1231. if ($ret)
  1232. $url = substr($url,0,$ret);
  1233. $url = trim($url);
  1234. if (empty($url))
  1235. return false;
  1236. $arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
  1237. $sign = $this->getSignature($arrdata);
  1238. if (!$sign)
  1239. return false;
  1240. $signPackage = array(
  1241. "appId" => $this->appid,
  1242. "nonceStr" => $noncestr,
  1243. "timestamp" => $timestamp,
  1244. "url" => $url,
  1245. "signature" => $sign
  1246. );
  1247. return $signPackage;
  1248. }
  1249. /**
  1250. * 微信api不支持中文转义的json结构
  1251. * @param array $arr
  1252. */
  1253. static function json_encode($arr) {
  1254. if (count($arr) == 0) return "[]";
  1255. $parts = array ();
  1256. $is_list = false;
  1257. //Find out if the given array is a numerical array
  1258. $keys = array_keys ( $arr );
  1259. $max_length = count ( $arr ) - 1;
  1260. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  1261. $is_list = true;
  1262. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  1263. if ($i != $keys [$i]) { //A key fails at position check.
  1264. $is_list = false; //It is an associative array.
  1265. break;
  1266. }
  1267. }
  1268. }
  1269. foreach ( $arr as $key => $value ) {
  1270. if (is_array ( $value )) { //Custom handling for arrays
  1271. if ($is_list)
  1272. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  1273. else
  1274. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  1275. } else {
  1276. $str = '';
  1277. if (! $is_list)
  1278. $str = '"' . $key . '":';
  1279. //Custom handling for multiple data types
  1280. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  1281. $str .= $value; //Numbers
  1282. elseif ($value === false)
  1283. $str .= 'false'; //The booleans
  1284. elseif ($value === true)
  1285. $str .= 'true';
  1286. else
  1287. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  1288. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  1289. $parts [] = $str;
  1290. }
  1291. }
  1292. $json = implode ( ',', $parts );
  1293. if ($is_list)
  1294. return '[' . $json . ']'; //Return numerical JSON
  1295. return '{' . $json . '}'; //Return associative JSON
  1296. }
  1297. /**
  1298. * 获取签名
  1299. * @param array $arrdata 签名数组
  1300. * @param string $method 签名方法
  1301. * @return boolean|string 签名值
  1302. */
  1303. public function getSignature($arrdata,$method="sha1") {
  1304. if (!function_exists($method)) return false;
  1305. ksort($arrdata);
  1306. $paramstring = "";
  1307. foreach($arrdata as $key => $value)
  1308. {
  1309. if(strlen($paramstring) == 0)
  1310. $paramstring .= $key . "=" . $value;
  1311. else
  1312. $paramstring .= "&" . $key . "=" . $value;
  1313. }
  1314. $Sign = $method($paramstring);
  1315. return $Sign;
  1316. }
  1317. /**
  1318. * 获取微信卡券api_ticket
  1319. * @param string $appid 用于多个appid时使用,可空
  1320. * @param string $api_ticket 手动指定api_ticket,非必要情况不建议用
  1321. */
  1322. public function getJsCardTicket($appid='',$api_ticket=''){
  1323. if (!$this->access_token && !$this->checkAuth()) return false;
  1324. if (!$appid) $appid = $this->appid;
  1325. if ($api_ticket) { //手动指定token,优先使用
  1326. $this->api_ticket = $api_ticket;
  1327. return $this->api_ticket;
  1328. }
  1329. $authname = 'wechat_api_ticket_wxcard'.$appid;
  1330. if ($rs = $this->getCache($authname)) {
  1331. $this->api_ticket = $rs;
  1332. return $rs;
  1333. }
  1334. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=wx_card');
  1335. if ($result)
  1336. {
  1337. $json = json_decode($result,true);
  1338. if (!$json || !empty($json['errcode'])) {
  1339. $this->errCode = $json['errcode'];
  1340. $this->errMsg = $json['errmsg'];
  1341. return false;
  1342. }
  1343. $this->api_ticket = $json['ticket'];
  1344. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1345. $this->setCache($authname,$this->api_ticket,$expire);
  1346. return $this->api_ticket;
  1347. }
  1348. return false;
  1349. }
  1350. /**
  1351. * 获取微信卡券签名
  1352. * @param array $arrdata 签名数组
  1353. * @param string $method 签名方法
  1354. * @return boolean|string 签名值
  1355. */
  1356. public function getTicketSignature($arrdata,$method="sha1") {
  1357. if (!function_exists($method)) return false;
  1358. $newArray = array();
  1359. foreach($arrdata as $key => $value)
  1360. {
  1361. array_push($newArray,(string)$value);
  1362. }
  1363. sort($newArray,SORT_STRING);
  1364. return $method(implode($newArray));
  1365. }
  1366. /**
  1367. * 生成随机字串
  1368. * @param number $length 长度,默认为16,最长为32字节
  1369. * @return string
  1370. */
  1371. public function generateNonceStr($length=16){
  1372. // 密码字符集,可任意添加你需要的字符
  1373. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1374. $str = "";
  1375. for($i = 0; $i < $length; $i++)
  1376. {
  1377. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1378. }
  1379. return $str;
  1380. }
  1381. /**
  1382. * 获取微信服务器IP地址列表
  1383. * @return array('127.0.0.1','127.0.0.1')
  1384. */
  1385. public function getServerIp(){
  1386. if (!$this->access_token && !$this->checkAuth()) return false;
  1387. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1388. if ($result)
  1389. {
  1390. $json = json_decode($result,true);
  1391. if (!$json || isset($json['errcode'])) {
  1392. $this->errCode = $json['errcode'];
  1393. $this->errMsg = $json['errmsg'];
  1394. return false;
  1395. }
  1396. return $json['ip_list'];
  1397. }
  1398. return false;
  1399. }
  1400. /**
  1401. * 创建菜单(认证后的订阅号可用)
  1402. * @param array $data 菜单数组数据
  1403. * example:
  1404. * array (
  1405. * 'button' => array (
  1406. * 0 => array (
  1407. * 'name' => '扫码',
  1408. * 'sub_button' => array (
  1409. * 0 => array (
  1410. * 'type' => 'scancode_waitmsg',
  1411. * 'name' => '扫码带提示',
  1412. * 'key' => 'rselfmenu_0_0',
  1413. * ),
  1414. * 1 => array (
  1415. * 'type' => 'scancode_push',
  1416. * 'name' => '扫码推事件',
  1417. * 'key' => 'rselfmenu_0_1',
  1418. * ),
  1419. * ),
  1420. * ),
  1421. * 1 => array (
  1422. * 'name' => '发图',
  1423. * 'sub_button' => array (
  1424. * 0 => array (
  1425. * 'type' => 'pic_sysphoto',
  1426. * 'name' => '系统拍照发图',
  1427. * 'key' => 'rselfmenu_1_0',
  1428. * ),
  1429. * 1 => array (
  1430. * 'type' => 'pic_photo_or_album',
  1431. * 'name' => '拍照或者相册发图',
  1432. * 'key' => 'rselfmenu_1_1',
  1433. * )
  1434. * ),
  1435. * ),
  1436. * 2 => array (
  1437. * 'type' => 'location_select',
  1438. * 'name' => '发送位置',
  1439. * 'key' => 'rselfmenu_2_0'
  1440. * ),
  1441. * ),
  1442. * )
  1443. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  1444. * 1、click:点击推事件
  1445. * 2、view:跳转URL
  1446. * 3、scancode_push:扫码推事件
  1447. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1448. * 5、pic_sysphoto:弹出系统拍照发图
  1449. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1450. * 7、pic_weixin:弹出微信相册发图器
  1451. * 8、location_select:弹出地理位置选择器
  1452. */
  1453. public function createMenu($data){
  1454. if (!$this->access_token && !$this->checkAuth()) return false;
  1455. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1456. if ($result)
  1457. {
  1458. $json = json_decode($result,true);
  1459. if (!$json || !empty($json['errcode'])) {
  1460. $this->errCode = $json['errcode'];
  1461. $this->errMsg = $json['errmsg'];
  1462. return false;
  1463. }
  1464. return true;
  1465. }
  1466. return false;
  1467. }
  1468. /**
  1469. * 获取菜单(认证后的订阅号可用)
  1470. * @return array('menu'=>array(....s))
  1471. */
  1472. public function getMenu(){
  1473. if (!$this->access_token && !$this->checkAuth()) return false;
  1474. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  1475. if ($result)
  1476. {
  1477. $json = json_decode($result,true);
  1478. if (!$json || isset($json['errcode'])) {
  1479. $this->errCode = $json['errcode'];
  1480. $this->errMsg = $json['errmsg'];
  1481. return false;
  1482. }
  1483. return $json;
  1484. }
  1485. return false;
  1486. }
  1487. /**
  1488. * 删除菜单(认证后的订阅号可用)
  1489. * @return boolean
  1490. */
  1491. public function deleteMenu(){
  1492. if (!$this->access_token && !$this->checkAuth()) return false;
  1493. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  1494. if ($result)
  1495. {
  1496. $json = json_decode($result,true);
  1497. if (!$json || !empty($json['errcode'])) {
  1498. $this->errCode = $json['errcode'];
  1499. $this->errMsg = $json['errmsg'];
  1500. return false;
  1501. }
  1502. return true;
  1503. }
  1504. return false;
  1505. }
  1506. /**
  1507. * 上传临时素材,有效期为3天(认证后的订阅号可用)
  1508. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1509. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1510. * 注意:临时素材的media_id是可复用的!
  1511. * @param array $data {"media":'@Path\filename.jpg'}
  1512. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1513. * @return boolean|array
  1514. */
  1515. public function uploadMedia($data, $type){
  1516. if (!$this->access_token && !$this->checkAuth()) return false;
  1517. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1518. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1519. if ($result)
  1520. {
  1521. $json = json_decode($result,true);
  1522. if (!$json || !empty($json['errcode'])) {
  1523. $this->errCode = $json['errcode'];
  1524. $this->errMsg = $json['errmsg'];
  1525. return false;
  1526. }
  1527. return $json;
  1528. }
  1529. return false;
  1530. }
  1531. /**
  1532. * 获取临时素材(认证后的订阅号可用)
  1533. * @param string $media_id 媒体文件id
  1534. * @param boolean $is_video 是否为视频文件,默认为否
  1535. * @return raw data
  1536. */
  1537. public function getMedia($media_id,$is_video=false){
  1538. if (!$this->access_token && !$this->checkAuth()) return false;
  1539. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1540. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1541. $url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1542. $result = $this->http_get($url_prefix.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1543. if ($result)
  1544. {
  1545. if (is_string($result)) {
  1546. $json = json_decode($result,true);
  1547. if (isset($json['errcode'])) {
  1548. $this->errCode = $json['errcode'];
  1549. $this->errMsg = $json['errmsg'];
  1550. return false;
  1551. }
  1552. }
  1553. return $result;
  1554. }
  1555. return false;
  1556. }
  1557. /**
  1558. * 上传图片,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 (认证后的订阅号可用)
  1559. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1560. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1561. * @param array $data {"media":'@Path\filename.jpg'}
  1562. *
  1563. * @return boolean|array
  1564. */
  1565. public function uploadImg($data){
  1566. if (!$this->access_token && !$this->checkAuth()) return false;
  1567. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1568. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADIMG_URL.'access_token='.$this->access_token,$data,true);
  1569. if ($result)
  1570. {
  1571. $json = json_decode($result,true);
  1572. if (!$json || !empty($json['errcode'])) {
  1573. $this->errCode = $json['errcode'];
  1574. $this->errMsg = $json['errmsg'];
  1575. return false;
  1576. }
  1577. return $json;
  1578. }
  1579. return false;
  1580. }
  1581. /**
  1582. * 上传永久素材(认证后的订阅号可用)
  1583. * 新增的永久素材也可以在公众平台官网素材管理模块中看到
  1584. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1585. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1586. * @param array $data {"media":'@Path\filename.jpg'}
  1587. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1588. * @param boolean $is_video 是否为视频文件,默认为否
  1589. * @param array $video_info 视频信息数组,非视频素材不需要提供 array('title'=>'视频标题','introduction'=>'描述')
  1590. * @return boolean|array
  1591. */
  1592. public function uploadForeverMedia($data, $type,$is_video=false,$video_info=array()){
  1593. if (!$this->access_token && !$this->checkAuth()) return false;
  1594. //#TODO 暂不确定此接口是否需要让视频文件走http协议
  1595. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1596. //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1597. //当上传视频文件时,附加视频文件信息
  1598. if ($is_video) $data['description'] = self::json_encode($video_info);
  1599. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1600. if ($result)
  1601. {
  1602. $json = json_decode($result,true);
  1603. if (!$json || !empty($json['errcode'])) {
  1604. $this->errCode = $json['errcode'];
  1605. $this->errMsg = $json['errmsg'];
  1606. return false;
  1607. }
  1608. return $json;
  1609. }
  1610. return false;
  1611. }
  1612. /**
  1613. * 上传永久图文素材(认证后的订阅号可用)
  1614. * 新增的永久素材也可以在公众平台官网素材管理模块中看到
  1615. * @param array $data 消息结构{"articles":[{...}]}
  1616. * @return boolean|array
  1617. */
  1618. public function uploadForeverArticles($data){
  1619. if (!$this->access_token && !$this->checkAuth()) return false;
  1620. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPLOAD_URL.'access_token='.$this->access_token,self::json_encode($data));
  1621. if ($result)
  1622. {
  1623. $json = json_decode($result,true);
  1624. if (!$json || !empty($json['errcode'])) {
  1625. $this->errCode = $json['errcode'];
  1626. $this->errMsg = $json['errmsg'];
  1627. return false;
  1628. }
  1629. return $json;
  1630. }
  1631. return false;
  1632. }
  1633. /**
  1634. * 修改永久图文素材(认证后的订阅号可用)
  1635. * 永久素材也可以在公众平台官网素材管理模块中看到
  1636. * @param string $media_id 图文素材id
  1637. * @param array $data 消息结构{"articles":[{...}]}
  1638. * @param int $index 更新的文章在图文素材的位置,第一篇为0,仅多图文使用
  1639. * @return boolean|array
  1640. */
  1641. public function updateForeverArticles($media_id,$data,$index=0){
  1642. if (!$this->access_token && !$this->checkAuth()) return false;
  1643. if (!isset($data['media_id'])) $data['media_id'] = $media_id;
  1644. if (!isset($data['index'])) $data['index'] = $index;
  1645. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1646. if ($result)
  1647. {
  1648. $json = json_decode($result,true);
  1649. if (!$json || !empty($json['errcode'])) {
  1650. $this->errCode = $json['errcode'];
  1651. $this->errMsg = $json['errmsg'];
  1652. return false;
  1653. }
  1654. return $json;
  1655. }
  1656. return false;
  1657. }
  1658. /**
  1659. * 获取永久素材(认证后的订阅号可用)
  1660. * 返回图文消息数组或二进制数据,失败返回false
  1661. * @param string $media_id 媒体文件id
  1662. * @param boolean $is_video 是否为视频文件,默认为否
  1663. * @return boolean|array|raw data
  1664. */
  1665. public function getForeverMedia($media_id,$is_video=false){
  1666. if (!$this->access_token && !$this->checkAuth()) return false;
  1667. $data = array('media_id' => $media_id);
  1668. //#TODO 暂不确定此接口是否需要让视频文件走http协议
  1669. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1670. //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1671. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_GET_URL.'access_token='.$this->access_token,self::json_encode($data));
  1672. if ($result)
  1673. {
  1674. if (is_string($result)) {
  1675. $json = json_decode($result,true);
  1676. if ($json) {
  1677. if (isset($json['errcode'])) {
  1678. $this->errCode = $json['errcode'];
  1679. $this->errMsg = $json['errmsg'];
  1680. return false;
  1681. }
  1682. return $json;
  1683. } else {
  1684. return $result;
  1685. }
  1686. }
  1687. return $result;
  1688. }
  1689. return false;
  1690. }
  1691. /**
  1692. * 删除永久素材(认证后的订阅号可用)
  1693. * @param string $media_id 媒体文件id
  1694. * @return boolean
  1695. */
  1696. public function delForeverMedia($media_id){
  1697. if (!$this->access_token && !$this->checkAuth()) return false;
  1698. $data = array('media_id' => $media_id);
  1699. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_DEL_URL.'access_token='.$this->access_token,self::json_encode($data));
  1700. if ($result)
  1701. {
  1702. $json = json_decode($result,true);
  1703. if (!$json || !empty($json['errcode'])) {
  1704. $this->errCode = $json['errcode'];
  1705. $this->errMsg = $json['errmsg'];
  1706. return false;
  1707. }
  1708. return true;
  1709. }
  1710. return false;
  1711. }
  1712. /**
  1713. * 获取永久素材列表(认证后的订阅号可用)
  1714. * @param string $type 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
  1715. * @param int $offset 全部素材的偏移位置,0表示从第一个素材
  1716. * @param int $count 返回素材的数量,取值在1到20之间
  1717. * @return boolean|array
  1718. * 返回数组格式:
  1719. * array(
  1720. * 'total_count'=>0, //该类型的素材的总数
  1721. * 'item_count'=>0, //本次调用获取的素材的数量
  1722. * 'item'=>array() //素材列表数组,内容定义请参考官方文档
  1723. * )
  1724. */
  1725. public function getForeverList($type,$offset,$count){
  1726. if (!$this->access_token && !$this->checkAuth()) return false;
  1727. $data = array(
  1728. 'type' => $type,
  1729. 'offset' => $offset,
  1730. 'count' => $count,
  1731. );
  1732. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_BATCHGET_URL.'access_token='.$this->access_token,self::json_encode($data));
  1733. if ($result)
  1734. {
  1735. $json = json_decode($result,true);
  1736. if (isset($json['errcode'])) {
  1737. $this->errCode = $json['errcode'];
  1738. $this->errMsg = $json['errmsg'];
  1739. return false;
  1740. }
  1741. return $json;
  1742. }
  1743. return false;
  1744. }
  1745. /**
  1746. * 获取永久素材总数(认证后的订阅号可用)
  1747. * @return boolean|array
  1748. * 返回数组格式:
  1749. * array(
  1750. * 'voice_count'=>0, //语音总数量
  1751. * 'video_count'=>0, //视频总数量
  1752. * 'image_count'=>0, //图片总数量
  1753. * 'news_count'=>0 //图文总数量
  1754. * )
  1755. */
  1756. public function getForeverCount(){
  1757. if (!$this->access_token && !$this->checkAuth()) return false;
  1758. $result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_FOREVER_COUNT_URL.'access_token='.$this->access_token);
  1759. if ($result)
  1760. {
  1761. $json = json_decode($result,true);
  1762. if (isset($json['errcode'])) {
  1763. $this->errCode = $json['errcode'];
  1764. $this->errMsg = $json['errmsg'];
  1765. return false;
  1766. }
  1767. return $json;
  1768. }
  1769. return false;
  1770. }
  1771. /**
  1772. * 上传图文消息素材,用于群发(认证后的订阅号可用)
  1773. * @param array $data 消息结构{"articles":[{...}]}
  1774. * @return boolean|array
  1775. */
  1776. public function uploadArticles($data){
  1777. if (!$this->access_token && !$this->checkAuth()) return false;
  1778. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1779. if ($result)
  1780. {
  1781. $json = json_decode($result,true);
  1782. if (!$json || !empty($json['errcode'])) {
  1783. $this->errCode = $json['errcode'];
  1784. $this->errMsg = $json['errmsg'];
  1785. return false;
  1786. }
  1787. return $json;
  1788. }
  1789. return false;
  1790. }
  1791. /**
  1792. * 上传视频素材(认证后的订阅号可用)
  1793. * @param array $data 消息结构
  1794. * {
  1795. * "media_id"=>"", //通过上传媒体接口得到的MediaId
  1796. * "title"=>"TITLE", //视频标题
  1797. * "description"=>"Description" //视频描述
  1798. * }
  1799. * @return boolean|array
  1800. * {
  1801. * "type":"video",
  1802. * "media_id":"mediaid",
  1803. * "created_at":1398848981
  1804. * }
  1805. */
  1806. public function uploadMpVideo($data){
  1807. if (!$this->access_token && !$this->checkAuth()) return false;
  1808. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_VIDEO_UPLOAD.'access_token='.$this->access_token,self::json_encode($data));
  1809. if ($result)
  1810. {
  1811. $json = json_decode($result,true);
  1812. if (!$json || !empty($json['errcode'])) {
  1813. $this->errCode = $json['errcode'];
  1814. $this->errMsg = $json['errmsg'];
  1815. return false;
  1816. }
  1817. return $json;
  1818. }
  1819. return false;
  1820. }
  1821. /**
  1822. * 高级群发消息, 根据OpenID列表群发图文消息(订阅号不可用)
  1823. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1824. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1825. * @param array $data 消息结构
  1826. * {
  1827. * "touser"=>array(
  1828. * "OPENID1",
  1829. * "OPENID2"
  1830. * ),
  1831. * "msgtype"=>"mpvideo",
  1832. * // 在下面5种类型中选择对应的参数内容
  1833. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1834. * // text => array ( "content" => "hello")
  1835. * }
  1836. * @return boolean|array
  1837. */
  1838. public function sendMassMessage($data){
  1839. if (!$this->access_token && !$this->checkAuth()) return false;
  1840. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1841. if ($result)
  1842. {
  1843. $json = json_decode($result,true);
  1844. if (!$json || !empty($json['errcode'])) {
  1845. $this->errCode = $json['errcode'];
  1846. $this->errMsg = $json['errmsg'];
  1847. return false;
  1848. }
  1849. return $json;
  1850. }
  1851. return false;
  1852. }
  1853. /**
  1854. * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用)
  1855. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1856. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1857. * @param array $data 消息结构
  1858. * {
  1859. * "filter"=>array(
  1860. * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id
  1861. * "group_id"=>"2" //群发的分组id
  1862. * ),
  1863. * "msgtype"=>"mpvideo",
  1864. * // 在下面5种类型中选择对应的参数内容
  1865. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1866. * // text => array ( "content" => "hello")
  1867. * }
  1868. * @return boolean|array
  1869. */
  1870. public function sendGroupMassMessage($data){
  1871. if (!$this->access_token && !$this->checkAuth()) return false;
  1872. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1873. if ($result)
  1874. {
  1875. $json = json_decode($result,true);
  1876. if (!$json || !empty($json['errcode'])) {
  1877. $this->errCode = $json['errcode'];
  1878. $this->errMsg = $json['errmsg'];
  1879. return false;
  1880. }
  1881. return $json;
  1882. }
  1883. return false;
  1884. }
  1885. /**
  1886. * 高级群发消息, 删除群发图文消息(认证后的订阅号可用)
  1887. * @param int $msg_id 消息id
  1888. * @return boolean|array
  1889. */
  1890. public function deleteMassMessage($msg_id){
  1891. if (!$this->access_token && !$this->checkAuth()) return false;
  1892. $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)));
  1893. if ($result)
  1894. {
  1895. $json = json_decode($result,true);
  1896. if (!$json || !empty($json['errcode'])) {
  1897. $this->errCode = $json['errcode'];
  1898. $this->errMsg = $json['errmsg'];
  1899. return false;
  1900. }
  1901. return true;
  1902. }
  1903. return false;
  1904. }
  1905. /**
  1906. * 高级群发消息, 预览群发消息(认证后的订阅号可用)
  1907. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1908. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1909. * @param array $data 消息结构
  1910. * {
  1911. * "touser"=>"OPENID",
  1912. * "msgtype"=>"mpvideo",
  1913. * // 在下面5种类型中选择对应的参数内容
  1914. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1915. * // text => array ( "content" => "hello")
  1916. * }
  1917. * @return boolean|array
  1918. */
  1919. public function previewMassMessage($data){
  1920. if (!$this->access_token && !$this->checkAuth()) return false;
  1921. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_PREVIEW_URL.'access_token='.$this->access_token,self::json_encode($data));
  1922. if ($result)
  1923. {
  1924. $json = json_decode($result,true);
  1925. if (!$json || !empty($json['errcode'])) {
  1926. $this->errCode = $json['errcode'];
  1927. $this->errMsg = $json['errmsg'];
  1928. return false;
  1929. }
  1930. return $json;
  1931. }
  1932. return false;
  1933. }
  1934. /**
  1935. * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用)
  1936. * @param int $msg_id 消息id
  1937. * @return boolean|array
  1938. * {
  1939. * "msg_id":201053012, //群发消息后返回的消息id
  1940. * "msg_status":"SEND_SUCCESS" //消息发送后的状态,SENDING表示正在发送 SEND_SUCCESS表示发送成功
  1941. * }
  1942. */
  1943. public function queryMassMessage($msg_id){
  1944. if (!$this->access_token && !$this->checkAuth()) return false;
  1945. $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)));
  1946. if ($result)
  1947. {
  1948. $json = json_decode($result,true);
  1949. if (!$json || !empty($json['errcode'])) {
  1950. $this->errCode = $json['errcode'];
  1951. $this->errMsg = $json['errmsg'];
  1952. return false;
  1953. }
  1954. return $json;
  1955. }
  1956. return false;
  1957. }
  1958. /**
  1959. * 创建二维码ticket
  1960. * @param int|string $scene_id 自定义追踪id,临时二维码只能用数值型
  1961. * @param int $type 0:临时二维码;1:数值型永久二维码(此时expire参数无效);2:字符串型永久二维码(此时expire参数无效)
  1962. * @param int $expire 临时二维码有效期,最大为604800秒
  1963. * @return array('ticket'=>'qrcode字串','expire_seconds'=>604800,'url'=>'二维码图片解析后的地址')
  1964. */
  1965. public function getQRCode($scene_id,$type=0,$expire=604800){
  1966. if (!$this->access_token && !$this->checkAuth()) return false;
  1967. if (!isset($scene_id)) return false;
  1968. switch ($type) {
  1969. case '0':
  1970. if (!is_numeric($scene_id))
  1971. return false;
  1972. $action_name = 'QR_SCENE';
  1973. $action_info = array('scene'=>(array('scene_id'=>$scene_id)));
  1974. break;
  1975. case '1':
  1976. if (!is_numeric($scene_id))
  1977. return false;
  1978. $action_name = 'QR_LIMIT_SCENE';
  1979. $action_info = array('scene'=>(array('scene_id'=>$scene_id)));
  1980. break;
  1981. case '2':
  1982. if (!is_string($scene_id))
  1983. return false;
  1984. $action_name = 'QR_LIMIT_STR_SCENE';
  1985. $action_info = array('scene'=>(array('scene_str'=>$scene_id)));
  1986. break;
  1987. default:
  1988. return false;
  1989. }
  1990. $data = array(
  1991. 'action_name' => $action_name,
  1992. 'expire_seconds' => $expire,
  1993. 'action_info' => $action_info
  1994. );
  1995. if ($type) {
  1996. unset($data['expire_seconds']);
  1997. }
  1998. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1999. if ($result) {
  2000. $json = json_decode($result,true);
  2001. if (!$json || !empty($json['errcode'])) {
  2002. $this->errCode = $json['errcode'];
  2003. $this->errMsg = $json['errmsg'];
  2004. return false;
  2005. }
  2006. return $json;
  2007. }
  2008. return false;
  2009. }
  2010. /**
  2011. * 获取二维码图片
  2012. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  2013. * @return string url 返回http地址
  2014. */
  2015. public function getQRUrl($ticket) {
  2016. return self::QRCODE_IMG_URL.urlencode($ticket);
  2017. }
  2018. /**
  2019. * 长链接转短链接接口
  2020. * @param string $long_url 传入要转换的长url
  2021. * @return boolean|string url 成功则返回转换后的短url
  2022. */
  2023. public function getShortUrl($long_url){
  2024. if (!$this->access_token && !$this->checkAuth()) return false;
  2025. $data = array(
  2026. 'action'=>'long2short',
  2027. 'long_url'=>$long_url
  2028. );
  2029. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  2030. if ($result)
  2031. {
  2032. $json = json_decode($result,true);
  2033. if (!$json || !empty($json['errcode'])) {
  2034. $this->errCode = $json['errcode'];
  2035. $this->errMsg = $json['errmsg'];
  2036. return false;
  2037. }
  2038. return $json['short_url'];
  2039. }
  2040. return false;
  2041. }
  2042. /**
  2043. * 获取统计数据
  2044. * @param string $type 数据分类(user|article|upstreammsg|interface)分别为(用户分析|图文分析|消息分析|接口分析)
  2045. * @param string $subtype 数据子分类,参考 DATACUBE_URL_ARR 常量定义部分 或者README.md说明文档
  2046. * @param string $begin_date 开始时间
  2047. * @param string $end_date 结束时间
  2048. * @return boolean|array 成功返回查询结果数组,其定义请看官方文档
  2049. */
  2050. public function getDatacube($type,$subtype,$begin_date,$end_date=''){
  2051. if (!$this->access_token && !$this->checkAuth()) return false;
  2052. if (!isset(self::$DATACUBE_URL_ARR[$type]) || !isset(self::$DATACUBE_URL_ARR[$type][$subtype]))
  2053. return false;
  2054. $data = array(
  2055. 'begin_date'=>$begin_date,
  2056. 'end_date'=>$end_date?$end_date:$begin_date
  2057. );
  2058. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::$DATACUBE_URL_ARR[$type][$subtype].'access_token='.$this->access_token,self::json_encode($data));
  2059. if ($result)
  2060. {
  2061. $json = json_decode($result,true);
  2062. if (!$json || !empty($json['errcode'])) {
  2063. $this->errCode = $json['errcode'];
  2064. $this->errMsg = $json['errmsg'];
  2065. return false;
  2066. }
  2067. return isset($json['list'])?$json['list']:$json;
  2068. }
  2069. return false;
  2070. }
  2071. /**
  2072. * 批量获取关注用户列表
  2073. * @param unknown $next_openid
  2074. */
  2075. public function getUserList($next_openid=''){
  2076. if (!$this->access_token && !$this->checkAuth()) return false;
  2077. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  2078. if ($result)
  2079. {
  2080. $json = json_decode($result,true);
  2081. if (isset($json['errcode'])) {
  2082. $this->errCode = $json['errcode'];
  2083. $this->errMsg = $json['errmsg'];
  2084. return false;
  2085. }
  2086. return $json;
  2087. }
  2088. return false;
  2089. }
  2090. /**
  2091. * 获取关注者详细信息
  2092. * @param string $openid
  2093. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  2094. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  2095. */
  2096. public function getUserInfo($openid){
  2097. if (!$this->access_token && !$this->checkAuth()) return false;
  2098. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  2099. if ($result)
  2100. {
  2101. $json = json_decode($result,true);
  2102. if (isset($json['errcode'])) {
  2103. $this->errCode = $json['errcode'];
  2104. $this->errMsg = $json['errmsg'];
  2105. return false;
  2106. }
  2107. return $json;
  2108. }
  2109. return false;
  2110. }
  2111. /**
  2112. * 设置用户备注名
  2113. * @param string $openid
  2114. * @param string $remark 备注名
  2115. * @return boolean|array
  2116. */
  2117. public function updateUserRemark($openid,$remark){
  2118. if (!$this->access_token && !$this->checkAuth()) return false;
  2119. $data = array(
  2120. 'openid'=>$openid,
  2121. 'remark'=>$remark
  2122. );
  2123. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
  2124. if ($result)
  2125. {
  2126. $json = json_decode($result,true);
  2127. if (!$json || !empty($json['errcode'])) {
  2128. $this->errCode = $json['errcode'];
  2129. $this->errMsg = $json['errmsg'];
  2130. return false;
  2131. }
  2132. return $json;
  2133. }
  2134. return false;
  2135. }
  2136. /**
  2137. * 获取用户分组列表
  2138. * @return boolean|array
  2139. */
  2140. public function getGroup(){
  2141. if (!$this->access_token && !$this->checkAuth()) return false;
  2142. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  2143. if ($result)
  2144. {
  2145. $json = json_decode($result,true);
  2146. if (isset($json['errcode'])) {
  2147. $this->errCode = $json['errcode'];
  2148. $this->errMsg = $json['errmsg'];
  2149. return false;
  2150. }
  2151. return $json;
  2152. }
  2153. return false;
  2154. }
  2155. /**
  2156. * 获取用户所在分组
  2157. * @param string $openid
  2158. * @return boolean|int 成功则返回用户分组id
  2159. */
  2160. public function getUserGroup($openid){
  2161. if (!$this->access_token && !$this->checkAuth()) return false;
  2162. $data = array(
  2163. 'openid'=>$openid
  2164. );
  2165. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  2166. if ($result)
  2167. {
  2168. $json = json_decode($result,true);
  2169. if (!$json || !empty($json['errcode'])) {
  2170. $this->errCode = $json['errcode'];
  2171. $this->errMsg = $json['errmsg'];
  2172. return false;
  2173. } else
  2174. if (isset($json['groupid'])) return $json['groupid'];
  2175. }
  2176. return false;
  2177. }
  2178. /**
  2179. * 新增自定分组
  2180. * @param string $name 分组名称
  2181. * @return boolean|array
  2182. */
  2183. public function createGroup($name){
  2184. if (!$this->access_token && !$this->checkAuth()) return false;
  2185. $data = array(
  2186. 'group'=>array('name'=>$name)
  2187. );
  2188. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2189. if ($result)
  2190. {
  2191. $json = json_decode($result,true);
  2192. if (!$json || !empty($json['errcode'])) {
  2193. $this->errCode = $json['errcode'];
  2194. $this->errMsg = $json['errmsg'];
  2195. return false;
  2196. }
  2197. return $json;
  2198. }
  2199. return false;
  2200. }
  2201. /**
  2202. * 更改分组名称
  2203. * @param int $groupid 分组id
  2204. * @param string $name 分组名称
  2205. * @return boolean|array
  2206. */
  2207. public function updateGroup($groupid,$name){
  2208. if (!$this->access_token && !$this->checkAuth()) return false;
  2209. $data = array(
  2210. 'group'=>array('id'=>$groupid,'name'=>$name)
  2211. );
  2212. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2213. if ($result)
  2214. {
  2215. $json = json_decode($result,true);
  2216. if (!$json || !empty($json['errcode'])) {
  2217. $this->errCode = $json['errcode'];
  2218. $this->errMsg = $json['errmsg'];
  2219. return false;
  2220. }
  2221. return $json;
  2222. }
  2223. return false;
  2224. }
  2225. /**
  2226. * 移动用户分组
  2227. * @param int $groupid 分组id
  2228. * @param string $openid 用户openid
  2229. * @return boolean|array
  2230. */
  2231. public function updateGroupMembers($groupid,$openid){
  2232. if (!$this->access_token && !$this->checkAuth()) return false;
  2233. $data = array(
  2234. 'openid'=>$openid,
  2235. 'to_groupid'=>$groupid
  2236. );
  2237. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2238. if ($result)
  2239. {
  2240. $json = json_decode($result,true);
  2241. if (!$json || !empty($json['errcode'])) {
  2242. $this->errCode = $json['errcode'];
  2243. $this->errMsg = $json['errmsg'];
  2244. return false;
  2245. }
  2246. return $json;
  2247. }
  2248. return false;
  2249. }
  2250. /**
  2251. * 批量移动用户分组
  2252. * @param int $groupid 分组id
  2253. * @param string $openid_list 用户openid数组,一次不能超过50个
  2254. * @return boolean|array
  2255. */
  2256. public function batchUpdateGroupMembers($groupid,$openid_list){
  2257. if (!$this->access_token && !$this->checkAuth()) return false;
  2258. $data = array(
  2259. 'openid_list'=>$openid_list,
  2260. 'to_groupid'=>$groupid
  2261. );
  2262. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_BATCHUPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2263. if ($result)
  2264. {
  2265. $json = json_decode($result,true);
  2266. if (!$json || !empty($json['errcode'])) {
  2267. $this->errCode = $json['errcode'];
  2268. $this->errMsg = $json['errmsg'];
  2269. return false;
  2270. }
  2271. return $json;
  2272. }
  2273. return false;
  2274. }
  2275. /**
  2276. * 发送客服消息
  2277. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  2278. * @return boolean|array
  2279. */
  2280. public function sendCustomMessage($data){
  2281. if (!$this->access_token && !$this->checkAuth()) return false;
  2282. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  2283. if ($result)
  2284. {
  2285. $json = json_decode($result,true);
  2286. if (!$json || !empty($json['errcode'])) {
  2287. $this->errCode = $json['errcode'];
  2288. $this->errMsg = $json['errmsg'];
  2289. return false;
  2290. }
  2291. return $json;
  2292. }
  2293. return false;
  2294. }
  2295. /**
  2296. * oauth 授权跳转接口
  2297. * @param string $callback 回调URI
  2298. * @return string
  2299. */
  2300. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  2301. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  2302. }
  2303. /**
  2304. * 通过code获取Access Token
  2305. * @return array {access_token,expires_in,refresh_token,openid,scope}
  2306. */
  2307. public function getOauthAccessToken(){
  2308. $code = isset($_GET['code'])?$_GET['code']:'';
  2309. if (!$code) return false;
  2310. $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');
  2311. if ($result)
  2312. {
  2313. $json = json_decode($result,true);
  2314. if (!$json || !empty($json['errcode'])) {
  2315. $this->errCode = $json['errcode'];
  2316. $this->errMsg = $json['errmsg'];
  2317. return false;
  2318. }
  2319. $this->user_token = $json['access_token'];
  2320. return $json;
  2321. }
  2322. return false;
  2323. }
  2324. /**
  2325. * 刷新access token并续期
  2326. * @param string $refresh_token
  2327. * @return boolean|mixed
  2328. */
  2329. public function getOauthRefreshToken($refresh_token){
  2330. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  2331. if ($result)
  2332. {
  2333. $json = json_decode($result,true);
  2334. if (!$json || !empty($json['errcode'])) {
  2335. $this->errCode = $json['errcode'];
  2336. $this->errMsg = $json['errmsg'];
  2337. return false;
  2338. }
  2339. $this->user_token = $json['access_token'];
  2340. return $json;
  2341. }
  2342. return false;
  2343. }
  2344. /**
  2345. * 获取授权后的用户资料
  2346. * @param string $access_token
  2347. * @param string $openid
  2348. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  2349. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  2350. */
  2351. public function getOauthUserinfo($access_token,$openid){
  2352. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  2353. if ($result)
  2354. {
  2355. $json = json_decode($result,true);
  2356. if (!$json || !empty($json['errcode'])) {
  2357. $this->errCode = $json['errcode'];
  2358. $this->errMsg = $json['errmsg'];
  2359. return false;
  2360. }
  2361. return $json;
  2362. }
  2363. return false;
  2364. }
  2365. /**
  2366. * 检验授权凭证是否有效
  2367. * @param string $access_token
  2368. * @param string $openid
  2369. * @return boolean 是否有效
  2370. */
  2371. public function getOauthAuth($access_token,$openid){
  2372. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  2373. if ($result)
  2374. {
  2375. $json = json_decode($result,true);
  2376. if (!$json || !empty($json['errcode'])) {
  2377. $this->errCode = $json['errcode'];
  2378. $this->errMsg = $json['errmsg'];
  2379. return false;
  2380. } else
  2381. if ($json['errcode']==0) return true;
  2382. }
  2383. return false;
  2384. }
  2385. /**
  2386. * 模板消息 设置所属行业
  2387. * @param int $id1 公众号模板消息所属行业编号,参看官方开发文档 行业代码
  2388. * @param int $id2 同$id1。但如果只有一个行业,此参数可省略
  2389. * @return boolean|array
  2390. */
  2391. public function setTMIndustry($id1,$id2=''){
  2392. if ($id1) $data['industry_id1'] = $id1;
  2393. if ($id2) $data['industry_id2'] = $id2;
  2394. if (!$this->access_token && !$this->checkAuth()) return false;
  2395. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SET_INDUSTRY_URL.'access_token='.$this->access_token,self::json_encode($data));
  2396. if($result){
  2397. $json = json_decode($result,true);
  2398. if (!$json || !empty($json['errcode'])) {
  2399. $this->errCode = $json['errcode'];
  2400. $this->errMsg = $json['errmsg'];
  2401. return false;
  2402. }
  2403. return $json;
  2404. }
  2405. return false;
  2406. }
  2407. /**
  2408. * 模板消息 添加消息模板
  2409. * 成功返回消息模板的调用id
  2410. * @param string $tpl_id 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
  2411. * @return boolean|string
  2412. */
  2413. public function addTemplateMessage($tpl_id){
  2414. $data = array ('template_id_short' =>$tpl_id);
  2415. if (!$this->access_token && !$this->checkAuth()) return false;
  2416. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_ADD_TPL_URL.'access_token='.$this->access_token,self::json_encode($data));
  2417. if($result){
  2418. $json = json_decode($result,true);
  2419. if (!$json || !empty($json['errcode'])) {
  2420. $this->errCode = $json['errcode'];
  2421. $this->errMsg = $json['errmsg'];
  2422. return false;
  2423. }
  2424. return $json['template_id'];
  2425. }
  2426. return false;
  2427. }
  2428. /**
  2429. * 发送模板消息
  2430. * @param array $data 消息结构
  2431. * {
  2432. "touser":"OPENID",
  2433. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  2434. "url":"http://weixin.qq.com/download",
  2435. "topcolor":"#FF0000",
  2436. "data":{
  2437. "参数名1": {
  2438. "value":"参数",
  2439. "color":"#173177" //参数颜色
  2440. },
  2441. "Date":{
  2442. "value":"06月07日 19时24分",
  2443. "color":"#173177"
  2444. },
  2445. "CardNumber":{
  2446. "value":"0426",
  2447. "color":"#173177"
  2448. },
  2449. "Type":{
  2450. "value":"消费",
  2451. "color":"#173177"
  2452. }
  2453. }
  2454. }
  2455. * @return boolean|array
  2456. */
  2457. public function sendTemplateMessage($data){
  2458. if (!$this->access_token && !$this->checkAuth()) return false;
  2459. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  2460. if($result){
  2461. $json = json_decode($result,true);
  2462. if (!$json || !empty($json['errcode'])) {
  2463. $this->errCode = $json['errcode'];
  2464. $this->errMsg = $json['errmsg'];
  2465. return false;
  2466. }
  2467. return $json;
  2468. }
  2469. return false;
  2470. }
  2471. /**
  2472. * 获取多客服会话记录
  2473. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  2474. * @return boolean|array
  2475. */
  2476. public function getCustomServiceMessage($data){
  2477. if (!$this->access_token && !$this->checkAuth()) return false;
  2478. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  2479. if ($result)
  2480. {
  2481. $json = json_decode($result,true);
  2482. if (!$json || !empty($json['errcode'])) {
  2483. $this->errCode = $json['errcode'];
  2484. $this->errMsg = $json['errmsg'];
  2485. return false;
  2486. }
  2487. return $json;
  2488. }
  2489. return false;
  2490. }
  2491. /**
  2492. * 转发多客服消息
  2493. * Example: $obj->transfer_customer_service($customer_account)->reply();
  2494. * @param string $customer_account 转发到指定客服帐号:test1@test
  2495. */
  2496. public function transfer_customer_service($customer_account = '')
  2497. {
  2498. $msg = array(
  2499. 'ToUserName' => $this->getRevFrom(),
  2500. 'FromUserName'=>$this->getRevTo(),
  2501. 'CreateTime'=>time(),
  2502. 'MsgType'=>'transfer_customer_service',
  2503. );
  2504. if ($customer_account) {
  2505. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  2506. }
  2507. $this->Message($msg);
  2508. return $this;
  2509. }
  2510. /**
  2511. * 获取多客服客服基本信息
  2512. *
  2513. * @return boolean|array
  2514. */
  2515. public function getCustomServiceKFlist(){
  2516. if (!$this->access_token && !$this->checkAuth()) return false;
  2517. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  2518. if ($result)
  2519. {
  2520. $json = json_decode($result,true);
  2521. if (!$json || !empty($json['errcode'])) {
  2522. $this->errCode = $json['errcode'];
  2523. $this->errMsg = $json['errmsg'];
  2524. return false;
  2525. }
  2526. return $json;
  2527. }
  2528. return false;
  2529. }
  2530. /**
  2531. * 获取多客服在线客服接待信息
  2532. *
  2533. * @return boolean|array {
  2534. "kf_online_list": [
  2535. {
  2536. "kf_account": "test1@test", //客服账号@微信别名
  2537. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  2538. "kf_id": "1001", //客服工号
  2539. "auto_accept": 0, //客服设置的最大自动接入数
  2540. "accepted_case": 1 //客服当前正在接待的会话数
  2541. }
  2542. ]
  2543. }
  2544. */
  2545. public function getCustomServiceOnlineKFlist(){
  2546. if (!$this->access_token && !$this->checkAuth()) return false;
  2547. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  2548. if ($result)
  2549. {
  2550. $json = json_decode($result,true);
  2551. if (!$json || !empty($json['errcode'])) {
  2552. $this->errCode = $json['errcode'];
  2553. $this->errMsg = $json['errmsg'];
  2554. return false;
  2555. }
  2556. return $json;
  2557. }
  2558. return false;
  2559. }
  2560. /**
  2561. * 创建指定多客服会话
  2562. * @tutorial 当用户已被其他客服接待或指定客服不在线则会失败
  2563. * @param string $openid //用户openid
  2564. * @param string $kf_account //客服账号
  2565. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2566. * @return boolean | array //成功返回json数组
  2567. * {
  2568. * "errcode": 0,
  2569. * "errmsg": "ok",
  2570. * }
  2571. */
  2572. public function createKFSession($openid,$kf_account,$text=''){
  2573. $data=array(
  2574. "openid" =>$openid,
  2575. "kf_account" => $kf_account
  2576. );
  2577. if ($text) $data["text"] = $text;
  2578. if (!$this->access_token && !$this->checkAuth()) return false;
  2579. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CREATE.'access_token='.$this->access_token,self::json_encode($data));
  2580. if ($result)
  2581. {
  2582. $json = json_decode($result,true);
  2583. if (!$json || !empty($json['errcode'])) {
  2584. $this->errCode = $json['errcode'];
  2585. $this->errMsg = $json['errmsg'];
  2586. return false;
  2587. }
  2588. return $json;
  2589. }
  2590. return false;
  2591. }
  2592. /**
  2593. * 关闭指定多客服会话
  2594. * @tutorial 当用户被其他客服接待时则会失败
  2595. * @param string $openid //用户openid
  2596. * @param string $kf_account //客服账号
  2597. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2598. * @return boolean | array //成功返回json数组
  2599. * {
  2600. * "errcode": 0,
  2601. * "errmsg": "ok",
  2602. * }
  2603. */
  2604. public function closeKFSession($openid,$kf_account,$text=''){
  2605. $data=array(
  2606. "openid" =>$openid,
  2607. "kf_account" => $kf_account
  2608. );
  2609. if ($text) $data["text"] = $text;
  2610. if (!$this->access_token && !$this->checkAuth()) return false;
  2611. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CLOSE .'access_token='.$this->access_token,self::json_encode($data));
  2612. if ($result)
  2613. {
  2614. $json = json_decode($result,true);
  2615. if (!$json || !empty($json['errcode'])) {
  2616. $this->errCode = $json['errcode'];
  2617. $this->errMsg = $json['errmsg'];
  2618. return false;
  2619. }
  2620. return $json;
  2621. }
  2622. return false;
  2623. }
  2624. /**
  2625. * 获取用户会话状态
  2626. * @param string $openid //用户openid
  2627. * @return boolean | array //成功返回json数组
  2628. * {
  2629. * "errcode" : 0,
  2630. * "errmsg" : "ok",
  2631. * "kf_account" : "test1@test", //正在接待的客服
  2632. * "createtime": 123456789, //会话接入时间
  2633. * }
  2634. */
  2635. public function getKFSession($openid){
  2636. if (!$this->access_token && !$this->checkAuth()) return false;
  2637. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET .'access_token='.$this->access_token.'&openid='.$openid);
  2638. if ($result)
  2639. {
  2640. $json = json_decode($result,true);
  2641. if (!$json || !empty($json['errcode'])) {
  2642. $this->errCode = $json['errcode'];
  2643. $this->errMsg = $json['errmsg'];
  2644. return false;
  2645. }
  2646. return $json;
  2647. }
  2648. return false;
  2649. }
  2650. /**
  2651. * 获取指定客服的会话列表
  2652. * @param string $openid //用户openid
  2653. * @return boolean | array //成功返回json数组
  2654. * array(
  2655. * 'sessionlist' => array (
  2656. * array (
  2657. * 'openid'=>'OPENID', //客户 openid
  2658. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2659. * ),
  2660. * array (
  2661. * 'openid'=>'OPENID', //客户 openid
  2662. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2663. * ),
  2664. * )
  2665. * )
  2666. */
  2667. public function getKFSessionlist($kf_account){
  2668. if (!$this->access_token && !$this->checkAuth()) return false;
  2669. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_LIST .'access_token='.$this->access_token.'&kf_account='.$kf_account);
  2670. if ($result)
  2671. {
  2672. $json = json_decode($result,true);
  2673. if (!$json || !empty($json['errcode'])) {
  2674. $this->errCode = $json['errcode'];
  2675. $this->errMsg = $json['errmsg'];
  2676. return false;
  2677. }
  2678. return $json;
  2679. }
  2680. return false;
  2681. }
  2682. /**
  2683. * 获取未接入会话列表
  2684. * @param string $openid //用户openid
  2685. * @return boolean | array //成功返回json数组
  2686. * array (
  2687. * 'count' => 150 , //未接入会话数量
  2688. * 'waitcaselist' => array (
  2689. * array (
  2690. * 'openid'=>'OPENID', //客户 openid
  2691. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2692. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2693. * ),
  2694. * array (
  2695. * 'openid'=>'OPENID', //客户 openid
  2696. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2697. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2698. * )
  2699. * )
  2700. * )
  2701. */
  2702. public function getKFSessionWait(){
  2703. if (!$this->access_token && !$this->checkAuth()) return false;
  2704. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_WAIT .'access_token='.$this->access_token);
  2705. if ($result)
  2706. {
  2707. $json = json_decode($result,true);
  2708. if (!$json || !empty($json['errcode'])) {
  2709. $this->errCode = $json['errcode'];
  2710. $this->errMsg = $json['errmsg'];
  2711. return false;
  2712. }
  2713. return $json;
  2714. }
  2715. return false;
  2716. }
  2717. /**
  2718. * 添加客服账号
  2719. *
  2720. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2721. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2722. * @param string $password //客服账号明文登录密码,会自动加密
  2723. * @return boolean|array
  2724. * 成功返回结果
  2725. * {
  2726. * "errcode": 0,
  2727. * "errmsg": "ok",
  2728. * }
  2729. */
  2730. public function addKFAccount($account,$nickname,$password){
  2731. $data=array(
  2732. "kf_account" =>$account,
  2733. "nickname" => $nickname,
  2734. "password" => md5($password)
  2735. );
  2736. if (!$this->access_token && !$this->checkAuth()) return false;
  2737. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_ADD_URL.'access_token='.$this->access_token,self::json_encode($data));
  2738. if ($result)
  2739. {
  2740. $json = json_decode($result,true);
  2741. if (!$json || !empty($json['errcode'])) {
  2742. $this->errCode = $json['errcode'];
  2743. $this->errMsg = $json['errmsg'];
  2744. return false;
  2745. }
  2746. return $json;
  2747. }
  2748. return false;
  2749. }
  2750. /**
  2751. * 修改客服账号信息
  2752. *
  2753. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2754. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2755. * @param string $password //客服账号明文登录密码,会自动加密
  2756. * @return boolean|array
  2757. * 成功返回结果
  2758. * {
  2759. * "errcode": 0,
  2760. * "errmsg": "ok",
  2761. * }
  2762. */
  2763. public function updateKFAccount($account,$nickname,$password){
  2764. $data=array(
  2765. "kf_account" =>$account,
  2766. "nickname" => $nickname,
  2767. "password" => md5($password)
  2768. );
  2769. if (!$this->access_token && !$this->checkAuth()) return false;
  2770. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2771. if ($result)
  2772. {
  2773. $json = json_decode($result,true);
  2774. if (!$json || !empty($json['errcode'])) {
  2775. $this->errCode = $json['errcode'];
  2776. $this->errMsg = $json['errmsg'];
  2777. return false;
  2778. }
  2779. return $json;
  2780. }
  2781. return false;
  2782. }
  2783. /**
  2784. * 删除客服账号
  2785. *
  2786. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2787. * @return boolean|array
  2788. * 成功返回结果
  2789. * {
  2790. * "errcode": 0,
  2791. * "errmsg": "ok",
  2792. * }
  2793. */
  2794. public function deleteKFAccount($account){
  2795. if (!$this->access_token && !$this->checkAuth()) return false;
  2796. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_DEL_URL.'access_token='.$this->access_token.'&kf_account='.$account);
  2797. if ($result)
  2798. {
  2799. $json = json_decode($result,true);
  2800. if (!$json || !empty($json['errcode'])) {
  2801. $this->errCode = $json['errcode'];
  2802. $this->errMsg = $json['errmsg'];
  2803. return false;
  2804. }
  2805. return $json;
  2806. }
  2807. return false;
  2808. }
  2809. /**
  2810. * 上传客服头像
  2811. *
  2812. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2813. * @param string $imgfile //头像文件完整路径,如:'D:\user.jpg'。头像文件必须JPG格式,像素建议640*640
  2814. * @return boolean|array
  2815. * 成功返回结果
  2816. * {
  2817. * "errcode": 0,
  2818. * "errmsg": "ok",
  2819. * }
  2820. */
  2821. public function setKFHeadImg($account,$imgfile){
  2822. if (!$this->access_token && !$this->checkAuth()) return false;
  2823. $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);
  2824. if ($result)
  2825. {
  2826. $json = json_decode($result,true);
  2827. if (!$json || !empty($json['errcode'])) {
  2828. $this->errCode = $json['errcode'];
  2829. $this->errMsg = $json['errmsg'];
  2830. return false;
  2831. }
  2832. return $json;
  2833. }
  2834. return false;
  2835. }
  2836. /**
  2837. * 语义理解接口
  2838. * @param String $uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
  2839. * @param String $query 输入文本串
  2840. * @param String $category 需要使用的服务类型,多个用“,”隔开,不能为空
  2841. * @param Float $latitude 纬度坐标,与经度同时传入;与城市二选一传入
  2842. * @param Float $longitude 经度坐标,与纬度同时传入;与城市二选一传入
  2843. * @param String $city 城市名称,与经纬度二选一传入
  2844. * @param String $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入
  2845. * @return boolean|array
  2846. */
  2847. public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
  2848. if (!$this->access_token && !$this->checkAuth()) return false;
  2849. $data=array(
  2850. 'query' => $query,
  2851. 'category' => $category,
  2852. 'appid' => $this->appid,
  2853. 'uid' => ''
  2854. );
  2855. //地理坐标或城市名称二选一
  2856. if ($latitude) {
  2857. $data['latitude'] = $latitude;
  2858. $data['longitude'] = $longitude;
  2859. } elseif ($city) {
  2860. $data['city'] = $city;
  2861. } elseif ($region) {
  2862. $data['region'] = $region;
  2863. }
  2864. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
  2865. if ($result)
  2866. {
  2867. $json = json_decode($result,true);
  2868. if (!$json || !empty($json['errcode'])) {
  2869. $this->errCode = $json['errcode'];
  2870. $this->errMsg = $json['errmsg'];
  2871. return false;
  2872. }
  2873. return $json;
  2874. }
  2875. return false;
  2876. }
  2877. /**
  2878. * 创建卡券
  2879. * @param Array $data 卡券数据
  2880. * @return array|boolean 返回数组中card_id为卡券ID
  2881. */
  2882. public function createCard($data) {
  2883. if (!$this->access_token && !$this->checkAuth()) return false;
  2884. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2885. if ($result) {
  2886. $json = json_decode($result, true);
  2887. if (!$json || !empty($json['errcode'])) {
  2888. $this->errCode = $json['errcode'];
  2889. $this->errMsg = $json['errmsg'];
  2890. return false;
  2891. }
  2892. return $json;
  2893. }
  2894. return false;
  2895. }
  2896. /**
  2897. * 更改卡券信息
  2898. * 调用该接口更新信息后会重新送审,卡券状态变更为待审核。已被用户领取的卡券会实时更新票面信息。
  2899. * @param string $data
  2900. * @return boolean
  2901. */
  2902. public function updateCard($data) {
  2903. if (!$this->access_token && !$this->checkAuth()) return false;
  2904. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2905. if ($result) {
  2906. $json = json_decode($result, true);
  2907. if (!$json || !empty($json['errcode'])) {
  2908. $this->errCode = $json['errcode'];
  2909. $this->errMsg = $json['errmsg'];
  2910. return false;
  2911. }
  2912. return true;
  2913. }
  2914. return false;
  2915. }
  2916. /**
  2917. * 删除卡券
  2918. * 允许商户删除任意一类卡券。删除卡券后,该卡券对应已生成的领取用二维码、添加到卡包 JS API 均会失效。
  2919. * 注意:删除卡券不能删除已被用户领取,保存在微信客户端中的卡券,已领取的卡券依旧有效。
  2920. * @param string $card_id 卡券ID
  2921. * @return boolean
  2922. */
  2923. public function delCard($card_id) {
  2924. $data = array(
  2925. 'card_id' => $card_id,
  2926. );
  2927. if (!$this->access_token && !$this->checkAuth()) return false;
  2928. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  2929. if ($result) {
  2930. $json = json_decode($result, true);
  2931. if (!$json || !empty($json['errcode'])) {
  2932. $this->errCode = $json['errcode'];
  2933. $this->errMsg = $json['errmsg'];
  2934. return false;
  2935. }
  2936. return true;
  2937. }
  2938. return false;
  2939. }
  2940. /**
  2941. * 查询卡券详情
  2942. * @param string $card_id
  2943. * @return boolean|array 返回数组信息比较复杂,请参看卡券接口文档
  2944. */
  2945. public function getCardInfo($card_id) {
  2946. $data = array(
  2947. 'card_id' => $card_id,
  2948. );
  2949. if (!$this->access_token && !$this->checkAuth()) return false;
  2950. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  2951. if ($result) {
  2952. $json = json_decode($result, true);
  2953. if (!$json || !empty($json['errcode'])) {
  2954. $this->errCode = $json['errcode'];
  2955. $this->errMsg = $json['errmsg'];
  2956. return false;
  2957. }
  2958. return $json;
  2959. }
  2960. return false;
  2961. }
  2962. /**
  2963. * 获取颜色列表
  2964. * 获得卡券的最新颜色列表,用于创建卡券
  2965. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  2966. */
  2967. public function getCardColors() {
  2968. if (!$this->access_token && !$this->checkAuth()) return false;
  2969. $result = $this->http_get(self::API_BASE_URL_PREFIX . self::CARD_GETCOLORS . 'access_token=' . $this->access_token);
  2970. if ($result) {
  2971. $json = json_decode($result, true);
  2972. if (!$json || !empty($json['errcode'])) {
  2973. $this->errCode = $json['errcode'];
  2974. $this->errMsg = $json['errmsg'];
  2975. return false;
  2976. }
  2977. return $json;
  2978. }
  2979. return false;
  2980. }
  2981. /**
  2982. * 拉取门店列表
  2983. * 获取在公众平台上申请创建的门店列表
  2984. * @param int $offset 开始拉取的偏移,默认为0从头开始
  2985. * @param int $count 拉取的数量,默认为0拉取全部
  2986. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  2987. */
  2988. public function getCardLocations($offset=0,$count=0) {
  2989. $data=array(
  2990. 'offset'=>$offset,
  2991. 'count'=>$count
  2992. );
  2993. if (!$this->access_token && !$this->checkAuth()) return false;
  2994. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  2995. if ($result) {
  2996. $json = json_decode($result, true);
  2997. if (!$json || !empty($json['errcode'])) {
  2998. $this->errCode = $json['errcode'];
  2999. $this->errMsg = $json['errmsg'];
  3000. return false;
  3001. }
  3002. return $json;
  3003. }
  3004. return false;
  3005. }
  3006. /**
  3007. * 批量导入门店信息
  3008. * @tutorial 返回插入的门店id列表,以逗号分隔。如果有插入失败的,则为-1,请自行核查是哪个插入失败
  3009. * @param array $data 数组形式的json数据,由于内容较多,具体内容格式请查看 微信卡券接口文档
  3010. * @return boolean|string 成功返回插入的门店id列表
  3011. */
  3012. public function addCardLocations($data) {
  3013. if (!$this->access_token && !$this->checkAuth()) return false;
  3014. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHADD . 'access_token=' . $this->access_token, self::json_encode($data));
  3015. if ($result) {
  3016. $json = json_decode($result, true);
  3017. if (!$json || !empty($json['errcode'])) {
  3018. $this->errCode = $json['errcode'];
  3019. $this->errMsg = $json['errmsg'];
  3020. return false;
  3021. }
  3022. return $json;
  3023. }
  3024. return false;
  3025. }
  3026. /**
  3027. * 生成卡券二维码
  3028. * 成功则直接返回ticket值,可以用 getQRUrl($ticket) 换取二维码url
  3029. *
  3030. * @param string $cardid 卡券ID 必须
  3031. * @param string $code 指定卡券 code 码,只能被领一次。use_custom_code 字段为 true 的卡券必须填写,非自定义 code 不必填写。
  3032. * @param string $openid 指定领取者的 openid,只有该用户能领取。bind_openid 字段为 true 的卡券必须填写,非自定义 openid 不必填写。
  3033. * @param int $expire_seconds 指定二维码的有效时间,范围是 60 ~ 1800 秒。不填默认为永久有效。
  3034. * @param boolean $is_unique_code 指定下发二维码,生成的二维码随机分配一个 code,领取后不可再次扫描。填写 true 或 false。默认 false。
  3035. * @param string $balance 红包余额,以分为单位。红包类型必填(LUCKY_MONEY),其他卡券类型不填。
  3036. * @return boolean|string
  3037. */
  3038. public function createCardQrcode($card_id,$code='',$openid='',$expire_seconds=0,$is_unique_code=false,$balance='') {
  3039. $card = array(
  3040. 'card_id' => $card_id
  3041. );
  3042. $data = array(
  3043. 'action_name' => "QR_CARD"
  3044. );
  3045. if ($code)
  3046. $card['code'] = $code;
  3047. if ($openid)
  3048. $card['openid'] = $openid;
  3049. if ($is_unique_code)
  3050. $card['is_unique_code'] = $is_unique_code;
  3051. if ($balance)
  3052. $card['balance'] = $balance;
  3053. if ($expire_seconds)
  3054. $data['expire_seconds'] = $expire_seconds;
  3055. $data['action_info'] = array('card' => $card);
  3056. if (!$this->access_token && !$this->checkAuth()) return false;
  3057. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_QRCODE_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3058. if ($result) {
  3059. $json = json_decode($result, true);
  3060. if (!$json || !empty($json['errcode'])) {
  3061. $this->errCode = $json['errcode'];
  3062. $this->errMsg = $json['errmsg'];
  3063. return false;
  3064. }
  3065. return $json;
  3066. }
  3067. return false;
  3068. }
  3069. /**
  3070. * 消耗 code
  3071. * 自定义 code(use_custom_code 为 true)的优惠券,在 code 被核销时,必须调用此接口。
  3072. *
  3073. * @param string $code 要消耗的序列号
  3074. * @param string $card_id 要消耗序列号所述的 card_id,创建卡券时use_custom_code 填写 true 时必填。
  3075. * @return boolean|array
  3076. * {
  3077. * "errcode":0,
  3078. * "errmsg":"ok",
  3079. * "card":{"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"},
  3080. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA"
  3081. * }
  3082. */
  3083. public function consumeCardCode($code,$card_id='') {
  3084. $data = array('code' => $code);
  3085. if ($card_id)
  3086. $data['card_id'] = $card_id;
  3087. if (!$this->access_token && !$this->checkAuth()) return false;
  3088. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_CONSUME . 'access_token=' . $this->access_token, self::json_encode($data));
  3089. if ($result) {
  3090. $json = json_decode($result, true);
  3091. if (!$json || !empty($json['errcode'])) {
  3092. $this->errCode = $json['errcode'];
  3093. $this->errMsg = $json['errmsg'];
  3094. return false;
  3095. }
  3096. return $json;
  3097. }
  3098. return false;
  3099. }
  3100. /**
  3101. * code 解码
  3102. * @param string $encrypt_code 通过 choose_card_info 获取的加密字符串
  3103. * @return boolean|array
  3104. * {
  3105. * "errcode":0,
  3106. * "errmsg":"ok",
  3107. * "code":"751234212312"
  3108. * }
  3109. */
  3110. public function decryptCardCode($encrypt_code) {
  3111. $data = array(
  3112. 'encrypt_code' => $encrypt_code,
  3113. );
  3114. if (!$this->access_token && !$this->checkAuth()) return false;
  3115. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_DECRYPT . 'access_token=' . $this->access_token, self::json_encode($data));
  3116. if ($result) {
  3117. $json = json_decode($result, true);
  3118. if (!$json || !empty($json['errcode'])) {
  3119. $this->errCode = $json['errcode'];
  3120. $this->errMsg = $json['errmsg'];
  3121. return false;
  3122. }
  3123. return $json;
  3124. }
  3125. return false;
  3126. }
  3127. /**
  3128. * 查询 code 的有效性(非自定义 code)
  3129. * @param string $code
  3130. * @return boolean|array
  3131. * {
  3132. * "errcode":0,
  3133. * "errmsg":"ok",
  3134. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA", //用户 openid
  3135. * "card":{
  3136. * "card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc",
  3137. * "begin_time": 1404205036, //起始使用时间
  3138. * "end_time": 1404205036, //结束时间
  3139. * }
  3140. * }
  3141. */
  3142. public function checkCardCode($code) {
  3143. $data = array(
  3144. 'code' => $code,
  3145. );
  3146. if (!$this->access_token && !$this->checkAuth()) return false;
  3147. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  3148. if ($result) {
  3149. $json = json_decode($result, true);
  3150. if (!$json || !empty($json['errcode'])) {
  3151. $this->errCode = $json['errcode'];
  3152. $this->errMsg = $json['errmsg'];
  3153. return false;
  3154. }
  3155. return $json;
  3156. }
  3157. return false;
  3158. }
  3159. /**
  3160. * 批量查询卡列表
  3161. * @param $offset 开始拉取的偏移,默认为0从头开始
  3162. * @param $count 需要查询的卡片的数量(数量最大50,默认50)
  3163. * @return boolean|array
  3164. * {
  3165. * "errcode":0,
  3166. * "errmsg":"ok",
  3167. * "card_id_list":["ph_gmt7cUVrlRk8swPwx7aDyF-pg"], //卡 id 列表
  3168. * "total_num":1 //该商户名下 card_id 总数
  3169. * }
  3170. */
  3171. public function getCardIdList($offset=0,$count=50) {
  3172. if ($count>50)
  3173. $count = 50;
  3174. $data = array(
  3175. 'offset' => $offset,
  3176. 'count' => $count,
  3177. );
  3178. if (!$this->access_token && !$this->checkAuth()) return false;
  3179. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  3180. if ($result) {
  3181. $json = json_decode($result, true);
  3182. if (!$json || !empty($json['errcode'])) {
  3183. $this->errCode = $json['errcode'];
  3184. $this->errMsg = $json['errmsg'];
  3185. return false;
  3186. }
  3187. return $json;
  3188. }
  3189. return false;
  3190. }
  3191. /**
  3192. * 更改 code
  3193. * 为确保转赠后的安全性,微信允许自定义code的商户对已下发的code进行更改。
  3194. * 注:为避免用户疑惑,建议仅在发生转赠行为后(发生转赠后,微信会通过事件推送的方式告知商户被转赠的卡券code)对用户的code进行更改。
  3195. * @param string $code 卡券的 code 编码
  3196. * @param string $card_id 卡券 ID
  3197. * @param string $new_code 新的卡券 code 编码
  3198. * @return boolean
  3199. */
  3200. public function updateCardCode($code,$card_id,$new_code) {
  3201. $data = array(
  3202. 'code' => $code,
  3203. 'card_id' => $card_id,
  3204. 'new_code' => $new_code,
  3205. );
  3206. if (!$this->access_token && !$this->checkAuth()) return false;
  3207. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3208. if ($result) {
  3209. $json = json_decode($result, true);
  3210. if (!$json || !empty($json['errcode'])) {
  3211. $this->errCode = $json['errcode'];
  3212. $this->errMsg = $json['errmsg'];
  3213. return false;
  3214. }
  3215. return true;
  3216. }
  3217. return false;
  3218. }
  3219. /**
  3220. * 设置卡券失效
  3221. * 设置卡券失效的操作不可逆
  3222. * @param string $code 需要设置为失效的 code
  3223. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 的卡券不填。
  3224. * @return boolean
  3225. */
  3226. public function unavailableCardCode($code,$card_id='') {
  3227. $data = array(
  3228. 'code' => $code,
  3229. );
  3230. if ($card_id)
  3231. $data['card_id'] = $card_id;
  3232. if (!$this->access_token && !$this->checkAuth()) return false;
  3233. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UNAVAILABLE . 'access_token=' . $this->access_token, self::json_encode($data));
  3234. if ($result) {
  3235. $json = json_decode($result, true);
  3236. if (!$json || !empty($json['errcode'])) {
  3237. $this->errCode = $json['errcode'];
  3238. $this->errMsg = $json['errmsg'];
  3239. return false;
  3240. }
  3241. return true;
  3242. }
  3243. return false;
  3244. }
  3245. /**
  3246. * 库存修改
  3247. * @param string $data
  3248. * @return boolean
  3249. */
  3250. public function modifyCardStock($data) {
  3251. if (!$this->access_token && !$this->checkAuth()) return false;
  3252. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MODIFY_STOCK . 'access_token=' . $this->access_token, self::json_encode($data));
  3253. if ($result) {
  3254. $json = json_decode($result, true);
  3255. if (!$json || !empty($json['errcode'])) {
  3256. $this->errCode = $json['errcode'];
  3257. $this->errMsg = $json['errmsg'];
  3258. return false;
  3259. }
  3260. return true;
  3261. }
  3262. return false;
  3263. }
  3264. /**
  3265. * 更新门票
  3266. * @param string $data
  3267. * @return boolean
  3268. */
  3269. public function updateMeetingCard($data) {
  3270. if (!$this->access_token && !$this->checkAuth()) return false;
  3271. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEETINGCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  3272. if ($result) {
  3273. $json = json_decode($result, true);
  3274. if (!$json || !empty($json['errcode'])) {
  3275. $this->errCode = $json['errcode'];
  3276. $this->errMsg = $json['errmsg'];
  3277. return false;
  3278. }
  3279. return true;
  3280. }
  3281. return false;
  3282. }
  3283. /**
  3284. * 激活/绑定会员卡
  3285. * @param string $data 具体结构请参看卡券开发文档(6.1.1 激活/绑定会员卡)章节
  3286. * @return boolean
  3287. */
  3288. public function activateMemberCard($data) {
  3289. if (!$this->access_token && !$this->checkAuth()) return false;
  3290. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_ACTIVATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3291. if ($result) {
  3292. $json = json_decode($result, true);
  3293. if (!$json || !empty($json['errcode'])) {
  3294. $this->errCode = $json['errcode'];
  3295. $this->errMsg = $json['errmsg'];
  3296. return false;
  3297. }
  3298. return true;
  3299. }
  3300. return false;
  3301. }
  3302. /**
  3303. * 会员卡交易
  3304. * 会员卡交易后每次积分及余额变更需通过接口通知微信,便于后续消息通知及其他扩展功能。
  3305. * @param string $data 具体结构请参看卡券开发文档(6.1.2 会员卡交易)章节
  3306. * @return boolean|array
  3307. */
  3308. public function updateMemberCard($data) {
  3309. if (!$this->access_token && !$this->checkAuth()) return false;
  3310. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  3311. if ($result) {
  3312. $json = json_decode($result, true);
  3313. if (!$json || !empty($json['errcode'])) {
  3314. $this->errCode = $json['errcode'];
  3315. $this->errMsg = $json['errmsg'];
  3316. return false;
  3317. }
  3318. return $json;
  3319. }
  3320. return false;
  3321. }
  3322. /**
  3323. * 更新红包金额
  3324. * @param string $code 红包的序列号
  3325. * @param $balance 红包余额
  3326. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 可不填。
  3327. * @return boolean|array
  3328. */
  3329. public function updateLuckyMoney($code,$balance,$card_id='') {
  3330. $data = array(
  3331. 'code' => $code,
  3332. 'balance' => $balance
  3333. );
  3334. if ($card_id)
  3335. $data['card_id'] = $card_id;
  3336. if (!$this->access_token && !$this->checkAuth()) return false;
  3337. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LUCKYMONEY_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3338. if ($result) {
  3339. $json = json_decode($result, true);
  3340. if (!$json || !empty($json['errcode'])) {
  3341. $this->errCode = $json['errcode'];
  3342. $this->errMsg = $json['errmsg'];
  3343. return false;
  3344. }
  3345. return true;
  3346. }
  3347. return false;
  3348. }
  3349. /**
  3350. * 设置卡券测试白名单
  3351. * @param string $openid 测试的 openid 列表
  3352. * @param string $user 测试的微信号列表
  3353. * @return boolean
  3354. */
  3355. public function setCardTestWhiteList($openid=array(),$user=array()) {
  3356. $data = array();
  3357. if (count($openid) > 0)
  3358. $data['openid'] = $openid;
  3359. if (count($user) > 0)
  3360. $data['username'] = $user;
  3361. if (!$this->access_token && !$this->checkAuth()) return false;
  3362. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_TESTWHILELIST_SET . 'access_token=' . $this->access_token, self::json_encode($data));
  3363. if ($result) {
  3364. $json = json_decode($result, true);
  3365. if (!$json || !empty($json['errcode'])) {
  3366. $this->errCode = $json['errcode'];
  3367. $this->errMsg = $json['errmsg'];
  3368. return false;
  3369. }
  3370. return true;
  3371. }
  3372. return false;
  3373. }
  3374. /**
  3375. * 申请设备ID
  3376. * [applyShakeAroundDevice 申请配置设备所需的UUID、Major、Minor。
  3377. * 若激活率小于50%,不能新增设备。单次新增设备超过500 个,需走人工审核流程。
  3378. * 审核通过后,可用迒回的批次ID 用“查询设备列表”接口拉取本次申请的设备ID]
  3379. * @param array $data
  3380. * array(
  3381. * "quantity" => 3, //申请的设备ID 的数量,单次新增设备超过500 个,需走人工审核流程(必填)
  3382. * "apply_reason" => "测试",//申请理由(必填)
  3383. * "comment" => "测试专用", //备注(非必填)
  3384. * "poi_id" => 1234 //设备关联的门店ID(非必填)
  3385. * )
  3386. * @return boolean|mixed
  3387. * {
  3388. "data": {
  3389. "apply_id": 123,
  3390. "device_identifiers":[
  3391. {
  3392. "device_id":10100,
  3393. "uuid":"FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3394. "major":10001,
  3395. "minor":10002
  3396. }
  3397. ]
  3398. },
  3399. "errcode": 0,
  3400. "errmsg": "success."
  3401. }
  3402. apply_id:申请的批次ID,可用在“查询设备列表”接口按批次查询本次申请成功的设备ID
  3403. device_identifiers:指定的设备ID 列表
  3404. device_id:设备编号
  3405. uuid、major、minor
  3406. audit_status:审核状态。0:审核未通过、1:审核中、2:审核已通过;审核会在三个工作日内完成
  3407. audit_comment:审核备注,包括审核不通过的原因
  3408. * @access public
  3409. * @author polo<gao.bo168@gmail.com>
  3410. * @version 2015-3-25 下午1:24:06
  3411. * @copyright Show More
  3412. */
  3413. public function applyShakeAroundDevice($data){
  3414. if (!$this->access_token && !$this->checkAuth()) return false;
  3415. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_APPLYID . 'access_token=' . $this->access_token, self::json_encode($data));
  3416. $this->log($result);
  3417. if ($result) {
  3418. $json = json_decode($result, true);
  3419. if (!$json || !empty($json['errcode'])) {
  3420. $this->errCode = $json['errcode'];
  3421. $this->errMsg = $json['errmsg'];
  3422. return false;
  3423. }
  3424. return $json;
  3425. }
  3426. return false;
  3427. }
  3428. /**
  3429. * 编辑设备信息
  3430. * [updateShakeAroundDevice 编辑设备的备注信息。可用设备ID或完整的UUID、Major、Minor指定设备,二者选其一。]
  3431. * @param array $data
  3432. * array(
  3433. * "device_identifier" => array(
  3434. * "device_id" => 10011, //当提供了device_id则不需要使用uuid、major、minor,反之亦然
  3435. * "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3436. * "major" => 1002,
  3437. * "minor" => 1223
  3438. * ),
  3439. * "comment" => "测试专用", //备注(非必填)
  3440. * )
  3441. * {
  3442. "data": {
  3443. },
  3444. "errcode": 0,
  3445. "errmsg": "success."
  3446. }
  3447. * @return boolean
  3448. * @author binsee<binsee@163.com>
  3449. * @version 2015-4-20 23:45:00
  3450. */
  3451. public function updateShakeAroundDevice($data){
  3452. if (!$this->access_token && !$this->checkAuth()) return false;
  3453. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3454. $this->log($result);
  3455. if ($result) {
  3456. $json = json_decode($result, true);
  3457. if (!$json || !empty($json['errcode'])) {
  3458. $this->errCode = $json['errcode'];
  3459. $this->errMsg = $json['errmsg'];
  3460. return false;
  3461. }
  3462. return true;
  3463. }
  3464. return false;
  3465. }
  3466. /**
  3467. * 查询设备列表
  3468. * [searchShakeAroundDevice 查询已有的设备ID、UUID、Major、Minor、激活状态、备注信息、关联门店、关联页面等信息。
  3469. * 可指定设备ID 或完整的UUID、Major、Minor 查询,也可批量拉取设备信息列表。]
  3470. * @param array $data
  3471. * $data 三种格式:
  3472. * ①查询指定设备时:$data = array(
  3473. * "device_identifiers" => array(
  3474. * array(
  3475. * "device_id" => 10100,
  3476. * "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3477. * "major" => 10001,
  3478. * "minor" => 10002
  3479. * )
  3480. * )
  3481. * );
  3482. * device_identifiers:指定的设备
  3483. * device_id:设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3484. * uuid、major、minor:三个信息需填写完整,若填了设备编号,则可不填此信息
  3485. * +-------------------------------------------------------------------------------------------------------------
  3486. * ②需要分页查询或者指定范围内的设备时: $data = array(
  3487. * "begin" => 0,
  3488. * "count" => 3
  3489. * );
  3490. * begin:设备列表的起始索引值
  3491. * count:待查询的设备个数
  3492. * +-------------------------------------------------------------------------------------------------------------
  3493. * ③当需要根据批次ID 查询时: $data = array(
  3494. * "apply_id" => 1231,
  3495. * "begin" => 0,
  3496. * "count" => 3
  3497. * );
  3498. * apply_id:批次ID
  3499. * +-------------------------------------------------------------------------------------------------------------
  3500. * @return boolean|mixed
  3501. *正确迒回JSON 数据示例:
  3502. *字段说明
  3503. {
  3504. "data": {
  3505. "devices": [ //指定的设备信息列表
  3506. {
  3507. "comment": "", //设备的备注信息
  3508. "device_id": 10097, //设备编号
  3509. "major": 10001,
  3510. "minor": 12102,
  3511. "page_ids": "15369", //与此设备关联的页面ID 列表,用逗号隔开
  3512. "status": 1, //激活状态,0:未激活,1:已激活(但不活跃),2:活跃
  3513. "poi_id": 0, //门店ID
  3514. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3515. },
  3516. {
  3517. "comment": "", //设备的备注信息
  3518. "device_id": 10098, //设备编号
  3519. "major": 10001,
  3520. "minor": 12103,
  3521. "page_ids": "15368", //与此设备关联的页面ID 列表,用逗号隔开
  3522. "status": 1, //激活状态,0:未激活,1:已激活(但不活跃),2:活跃
  3523. "poi_id": 0, //门店ID
  3524. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3525. }
  3526. ],
  3527. "total_count": 151 //商户名下的设备总量
  3528. },
  3529. "errcode": 0,
  3530. "errmsg": "success."
  3531. }
  3532. * @access public
  3533. * @author polo<gao.bo168@gmail.com>
  3534. * @version 2015-3-25 下午1:45:42
  3535. * @copyright Show More
  3536. */
  3537. public function searchShakeAroundDevice($data){
  3538. if (!$this->access_token && !$this->checkAuth()) return false;
  3539. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
  3540. $this->log($result);
  3541. if ($result) {
  3542. $json = json_decode($result, true);
  3543. if (!$json || !empty($json['errcode'])) {
  3544. $this->errCode = $json['errcode'];
  3545. $this->errMsg = $json['errmsg'];
  3546. return false;
  3547. }
  3548. return $json;
  3549. }
  3550. return false;
  3551. }
  3552. /**
  3553. * [bindLocationShakeAroundDevice 配置设备与门店的关联关系]
  3554. * @param string $device_id 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3555. * @param int $poi_id 待关联的门店ID
  3556. * @param string $uuid UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息
  3557. * @param int $major
  3558. * @param int $minor
  3559. * @return boolean|mixed
  3560. * 正确返回JSON 数据示例:
  3561. * {
  3562. "data": {
  3563. },
  3564. "errcode": 0,
  3565. "errmsg": "success."
  3566. }
  3567. * @access public
  3568. * @author polo<gao.bo168@gmail.com>
  3569. * @version 2015-4-21 00:14:00
  3570. * @copyright Show More
  3571. */
  3572. public function bindLocationShakeAroundDevice($device_id,$poi_id,$uuid='',$major=0,$minor=0){
  3573. if (!$this->access_token && !$this->checkAuth()) return false;
  3574. if(!$device_id){
  3575. if(!$uuid || !$major || !$minor){
  3576. return false;
  3577. }
  3578. $device_identifier = array(
  3579. 'uuid' => $uuid,
  3580. 'major' => $major,
  3581. 'minor' => $minor
  3582. );
  3583. }else{
  3584. $device_identifier = array(
  3585. 'device_id' => $device_id
  3586. );
  3587. }
  3588. $data = array(
  3589. 'device_identifier' => $device_identifier,
  3590. 'poi_id' => $poi_id
  3591. );
  3592. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDLOCATION . 'access_token=' . $this->access_token, self::json_encode($data));
  3593. $this->log($result);
  3594. if ($result) {
  3595. $json = json_decode($result, true);
  3596. if (!$json || !empty($json['errcode'])) {
  3597. $this->errCode = $json['errcode'];
  3598. $this->errMsg = $json['errmsg'];
  3599. return false;
  3600. }
  3601. return $json; //这个可以更改为返回true
  3602. }
  3603. return false;
  3604. }
  3605. /**
  3606. * [bindPageShakeAroundDevice 配置设备与页面的关联关系。
  3607. * 支持建立或解除关联关系,也支持新增页面或覆盖页面等操作。
  3608. * 配置完成后,在此设备的信号范围内,即可摇出关联的页面信息。
  3609. * 若设备配置多个页面,则随机出现页面信息]
  3610. * @param string $device_id 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3611. * @param array $page_ids 待关联的页面列表
  3612. * @param number $bind 关联操作标志位, 0 为解除关联关系,1 为建立关联关系
  3613. * @param number $append 新增操作标志位, 0 为覆盖,1 为新增
  3614. * @param string $uuid UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息
  3615. * @param int $major
  3616. * @param int $minor
  3617. * @return boolean|mixed
  3618. * 正确返回JSON 数据示例:
  3619. * {
  3620. "data": {
  3621. },
  3622. "errcode": 0,
  3623. "errmsg": "success."
  3624. }
  3625. * @access public
  3626. * @author polo<gao.bo168@gmail.com>
  3627. * @version 2015-4-21 00:31:00
  3628. * @copyright Show More
  3629. */
  3630. public function bindPageShakeAroundDevice($device_id,$page_ids=array(),$bind=1,$append=1,$uuid='',$major=0,$minor=0){
  3631. if (!$this->access_token && !$this->checkAuth()) return false;
  3632. if(!$device_id){
  3633. if(!$uuid || !$major || !$minor){
  3634. return false;
  3635. }
  3636. $device_identifier = array(
  3637. 'uuid' => $uuid,
  3638. 'major' => $major,
  3639. 'minor' => $minor
  3640. );
  3641. }else{
  3642. $device_identifier = array(
  3643. 'device_id' => $device_id
  3644. );
  3645. }
  3646. $data = array(
  3647. 'device_identifier' => $device_identifier,
  3648. 'page_ids' => $page_ids,
  3649. 'bind' => $bind,
  3650. 'append' => $append
  3651. );
  3652. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDPAGE . 'access_token=' . $this->access_token, self::json_encode($data));
  3653. $this->log($result);
  3654. if ($result) {
  3655. $json = json_decode($result, true);
  3656. if (!$json || !empty($json['errcode'])) {
  3657. $this->errCode = $json['errcode'];
  3658. $this->errMsg = $json['errmsg'];
  3659. return false;
  3660. }
  3661. return $json;
  3662. }
  3663. return false;
  3664. }
  3665. /**
  3666. * 上传在摇一摇页面展示的图片素材
  3667. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  3668. * @param array $data {"media":'@Path\filename.jpg'} 格式限定为:jpg,jpeg,png,gif,图片大小建议120px*120 px,限制不超过200 px *200 px,图片需为正方形。
  3669. * @return boolean|array
  3670. * {
  3671. "data": {
  3672. "pic_url":"http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
  3673. },
  3674. "errcode": 0,
  3675. "errmsg": "success."
  3676. }
  3677. }
  3678. * @author binsee<binsee@163.com>
  3679. * @version 2015-4-21 00:51:00
  3680. */
  3681. public function uploadShakeAroundMedia($data){
  3682. if (!$this->access_token && !$this->checkAuth()) return false;
  3683. $result = $this->http_post(self::API_URL_PREFIX.self::SHAKEAROUND_MATERIAL_ADD.'access_token='.$this->access_token,$data,true);
  3684. if ($result)
  3685. {
  3686. $json = json_decode($result,true);
  3687. if (!$json || !empty($json['errcode'])) {
  3688. $this->errCode = $json['errcode'];
  3689. $this->errMsg = $json['errmsg'];
  3690. return false;
  3691. }
  3692. return $json;
  3693. }
  3694. return false;
  3695. }
  3696. /**
  3697. * [addShakeAroundPage 增加摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。]
  3698. * @param string $title 在摇一摇页面展示的主标题,不超过6 个字
  3699. * @param string $description 在摇一摇页面展示的副标题,不超过7 个字
  3700. * @param sting $icon_url 在摇一摇页面展示的图片, 格式限定为:jpg,jpeg,png,gif; 建议120*120 , 限制不超过200*200
  3701. * @param string $page_url 跳转链接
  3702. * @param string $comment 页面的备注信息,不超过15 个字,可不填
  3703. * @return boolean|mixed
  3704. * 正确返回JSON 数据示例:
  3705. * {
  3706. "data": {
  3707. "page_id": 28840 //新增页面的页面id
  3708. }
  3709. "errcode": 0,
  3710. "errmsg": "success."
  3711. }
  3712. * @access public
  3713. * @author polo<gao.bo168@gmail.com>
  3714. * @version 2015-3-25 下午2:57:09
  3715. * @copyright Show More
  3716. */
  3717. public function addShakeAroundPage($title,$description,$icon_url,$page_url,$comment=''){
  3718. if (!$this->access_token && !$this->checkAuth()) return false;
  3719. $data = array(
  3720. "title" => $title,
  3721. "description" => $description,
  3722. "icon_url" => $icon_url,
  3723. "page_url" => $page_url,
  3724. "comment" => $comment
  3725. );
  3726. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_ADD . 'access_token=' . $this->access_token, self::json_encode($data));
  3727. $this->log($result);
  3728. if ($result) {
  3729. $json = json_decode($result, true);
  3730. if (!$json || !empty($json['errcode'])) {
  3731. $this->errCode = $json['errcode'];
  3732. $this->errMsg = $json['errmsg'];
  3733. return false;
  3734. }
  3735. return $json;
  3736. }
  3737. return false;
  3738. }
  3739. /**
  3740. * [updateShakeAroundPage 编辑摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。]
  3741. * @param int $page_id
  3742. * @param string $title 在摇一摇页面展示的主标题,不超过6 个字
  3743. * @param string $description 在摇一摇页面展示的副标题,不超过7 个字
  3744. * @param sting $icon_url 在摇一摇页面展示的图片, 格式限定为:jpg,jpeg,png,gif; 建议120*120 , 限制不超过200*200
  3745. * @param string $page_url 跳转链接
  3746. * @param string $comment 页面的备注信息,不超过15 个字,可不填
  3747. * @return boolean|mixed
  3748. * 正确返回JSON 数据示例:
  3749. * {
  3750. "data": {
  3751. "page_id": 28840 //编辑页面的页面ID
  3752. }
  3753. "errcode": 0,
  3754. "errmsg": "success."
  3755. }
  3756. * @access public
  3757. * @author polo<gao.bo168@gmail.com>
  3758. * @version 2015-3-25 下午3:02:51
  3759. * @copyright Show More
  3760. */
  3761. public function updateShakeAroundPage($page_id,$title,$description,$icon_url,$page_url,$comment=''){
  3762. if (!$this->access_token && !$this->checkAuth()) return false;
  3763. $data = array(
  3764. "page_id" => $page_id,
  3765. "title" => $title,
  3766. "description" => $description,
  3767. "icon_url" => $icon_url,
  3768. "page_url" => $page_url,
  3769. "comment" => $comment
  3770. );
  3771. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3772. $this->log($result);
  3773. if ($result) {
  3774. $json = json_decode($result, true);
  3775. if (!$json || !empty($json['errcode'])) {
  3776. $this->errCode = $json['errcode'];
  3777. $this->errMsg = $json['errmsg'];
  3778. return false;
  3779. }
  3780. return $json;
  3781. }
  3782. return false;
  3783. }
  3784. /**
  3785. * [searchShakeAroundPage 查询已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
  3786. * 提供两种查询方式,①可指定页面ID 查询,②也可批量拉取页面列表。]
  3787. * @param array $page_ids
  3788. * @param int $begin
  3789. * @param int $count
  3790. * ①需要查询指定页面时:
  3791. * {
  3792. "page_ids":[12345, 23456, 34567]
  3793. }
  3794. * +-------------------------------------------------------------------------------------------------------------
  3795. * ②需要分页查询或者指定范围内的页面时:
  3796. * {
  3797. "begin": 0,
  3798. "count": 3
  3799. }
  3800. * +-------------------------------------------------------------------------------------------------------------
  3801. * @return boolean|mixed
  3802. * 正确返回JSON 数据示例:
  3803. {
  3804. "data": {
  3805. "pages": [
  3806. {
  3807. "comment": "just for test",
  3808. "description": "test",
  3809. "icon_url": "https://www.baidu.com/img/bd_logo1.png",
  3810. "page_id": 28840,
  3811. "page_url": "http://xw.qq.com/testapi1",
  3812. "title": "测试1"
  3813. },
  3814. {
  3815. "comment": "just for test",
  3816. "description": "test",
  3817. "icon_url": "https://www.baidu.com/img/bd_logo1.png",
  3818. "page_id": 28842,
  3819. "page_url": "http://xw.qq.com/testapi2",
  3820. "title": "测试2"
  3821. }
  3822. ],
  3823. "total_count": 2
  3824. },
  3825. "errcode": 0,
  3826. "errmsg": "success."
  3827. }
  3828. *字段说明:
  3829. *total_count 商户名下的页面总数
  3830. *page_id 摇周边页面唯一ID
  3831. *title 在摇一摇页面展示的主标题
  3832. *description 在摇一摇页面展示的副标题
  3833. *icon_url 在摇一摇页面展示的图片
  3834. *page_url 跳转链接
  3835. *comment 页面的备注信息
  3836. * @access public
  3837. * @author polo<gao.bo168@gmail.com>
  3838. * @version 2015-3-25 下午3:12:17
  3839. * @copyright Show More
  3840. */
  3841. public function searchShakeAroundPage($page_ids=array(),$begin=0,$count=1){
  3842. if (!$this->access_token && !$this->checkAuth()) return false;
  3843. if(!empty($page_ids)){
  3844. $data = array(
  3845. 'page_ids' => $page_ids
  3846. );
  3847. }else{
  3848. $data = array(
  3849. 'begin' => $begin,
  3850. 'count' => $count
  3851. );
  3852. }
  3853. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
  3854. $this->log($result);
  3855. if ($result) {
  3856. $json = json_decode($result, true);
  3857. if (!$json || !empty($json['errcode'])) {
  3858. $this->errCode = $json['errcode'];
  3859. $this->errMsg = $json['errmsg'];
  3860. return false;
  3861. }
  3862. return $json;
  3863. }
  3864. return false;
  3865. }
  3866. /**
  3867. * [deleteShakeAroundPage 删除已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
  3868. * 只有页面与设备没有关联关系时,才可被删除。]
  3869. * @param array $page_ids
  3870. * {
  3871. "page_ids":[12345,23456,34567]
  3872. }
  3873. * @return boolean|mixed
  3874. * 正确返回JSON 数据示例:
  3875. * {
  3876. "data": {
  3877. },
  3878. "errcode": 0,
  3879. "errmsg": "success."
  3880. }
  3881. * @access public
  3882. * @author polo<gao.bo168@gmail.com>
  3883. * @version 2015-3-25 下午3:23:00
  3884. * @copyright Show More
  3885. */
  3886. public function deleteShakeAroundPage($page_ids=array()){
  3887. if (!$this->access_token && !$this->checkAuth()) return false;
  3888. $data = array(
  3889. 'page_ids' => $page_ids
  3890. );
  3891. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  3892. $this->log($result);
  3893. if ($result) {
  3894. $json = json_decode($result, true);
  3895. if (!$json || !empty($json['errcode'])) {
  3896. $this->errCode = $json['errcode'];
  3897. $this->errMsg = $json['errmsg'];
  3898. return false;
  3899. }
  3900. return $json;
  3901. }
  3902. return false;
  3903. }
  3904. /**
  3905. * [getShakeInfoShakeAroundUser 获取设备信息,包括UUID、major、minor,以及距离、openID 等信息。]
  3906. * @param string $ticket 摇周边业务的ticket,可在摇到的URL 中得到,ticket生效时间为30 分钟
  3907. * @return boolean|mixed
  3908. * 正确返回JSON 数据示例:
  3909. * {
  3910. "data": {
  3911. "page_id ": 14211,
  3912. "beacon_info": {
  3913. "distance": 55.00620700469034,
  3914. "major": 10001,
  3915. "minor": 19007,
  3916. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3917. },
  3918. "openid": "oVDmXjp7y8aG2AlBuRpMZTb1-cmA"
  3919. },
  3920. "errcode": 0,
  3921. "errmsg": "success."
  3922. }
  3923. * 字段说明:
  3924. * beacon_info 设备信息,包括UUID、major、minor,以及距离
  3925. * UUID、major、minor UUID、major、minor
  3926. * distance Beacon 信号与手机的距离
  3927. * page_id 摇周边页面唯一ID
  3928. * openid 商户AppID 下用户的唯一标识
  3929. * poi_id 门店ID,有的话则返回,没有的话不会在JSON 格式内
  3930. * @access public
  3931. * @author polo<gao.bo168@gmail.com>
  3932. * @version 2015-3-25 下午3:28:20
  3933. * @copyright Show More
  3934. */
  3935. public function getShakeInfoShakeAroundUser($ticket){
  3936. if (!$this->access_token && !$this->checkAuth()) return false;
  3937. $data = array('ticket' => $ticket);
  3938. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_USER_GETSHAKEINFO . 'access_token=' . $this->access_token, self::json_encode($data));
  3939. $this->log($result);
  3940. if ($result) {
  3941. $json = json_decode($result, true);
  3942. if (!$json || !empty($json['errcode'])) {
  3943. $this->errCode = $json['errcode'];
  3944. $this->errMsg = $json['errmsg'];
  3945. return false;
  3946. }
  3947. return $json;
  3948. }
  3949. return false;
  3950. }
  3951. /**
  3952. * [deviceShakeAroundStatistics 以设备为维度的数据统计接口。
  3953. * 查询单个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数;查询的最长时间跨度为30天。]
  3954. * @param int $device_id 设备编号,若填了UUID、major、minor,即可不填设备编号,二者选其一
  3955. * @param int $begin_date 起始日期时间戳,最长时间跨度为30 天
  3956. * @param int $end_date 结束日期时间戳,最长时间跨度为30 天
  3957. * @param string $uuid UUID、major、minor,三个信息需填写完成,若填了设备编辑,即可不填此信息,二者选其一
  3958. * @param int $major
  3959. * @param int $minor
  3960. * @return boolean|mixed
  3961. * 正确返回JSON 数据示例:
  3962. * {
  3963. "data": [
  3964. {
  3965. "click_pv": 0,
  3966. "click_uv": 0,
  3967. "ftime": 1425052800,
  3968. "shake_pv": 0,
  3969. "shake_uv": 0
  3970. },
  3971. {
  3972. "click_pv": 0,
  3973. "click_uv": 0,
  3974. "ftime": 1425139200,
  3975. "shake_pv": 0,
  3976. "shake_uv": 0
  3977. }
  3978. ],
  3979. "errcode": 0,
  3980. "errmsg": "success."
  3981. }
  3982. * 字段说明:
  3983. * ftime 当天0 点对应的时间戳
  3984. * click_pv 点击摇周边消息的次数
  3985. * click_uv 点击摇周边消息的人数
  3986. * shake_pv 摇周边的次数
  3987. * shake_uv 摇周边的人数
  3988. * @access public
  3989. * @author polo<gao.bo168@gmail.com>
  3990. * @version 2015-4-21 00:39:00
  3991. * @copyright Show More
  3992. */
  3993. public function deviceShakeAroundStatistics($device_id,$begin_date,$end_date,$uuid='',$major=0,$minor=0){
  3994. if (!$this->access_token && !$this->checkAuth()) return false;
  3995. if(!$device_id){
  3996. if(!$uuid || !$major || !$minor){
  3997. return false;
  3998. }
  3999. $device_identifier = array(
  4000. 'uuid' => $uuid,
  4001. 'major' => $major,
  4002. 'minor' => $minor
  4003. );
  4004. }else{
  4005. $device_identifier = array(
  4006. 'device_id' => $device_id
  4007. );
  4008. }
  4009. $data = array(
  4010. 'device_identifier' => $device_identifier,
  4011. 'begin_date' => $begin_date,
  4012. 'end_date' => $end_date
  4013. );
  4014. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
  4015. $this->log($result);
  4016. if ($result) {
  4017. $json = json_decode($result, true);
  4018. if (!$json || !empty($json['errcode'])) {
  4019. $this->errCode = $json['errcode'];
  4020. $this->errMsg = $json['errmsg'];
  4021. return false;
  4022. }
  4023. return $json;
  4024. }
  4025. return false;
  4026. }
  4027. /**
  4028. * [pageShakeAroundStatistics 以页面为维度的数据统计接口。
  4029. * 查询单个页面通过摇周边摇出来的人数、次数,点击摇周边页面的人数、次数;查询的最长时间跨度为30天。]
  4030. * @param int $page_id 指定页面的ID
  4031. * @param int $begin_date 起始日期时间戳,最长时间跨度为30 天
  4032. * @param int $end_date 结束日期时间戳,最长时间跨度为30 天
  4033. * @return boolean|mixed
  4034. * 正确返回JSON 数据示例:
  4035. * {
  4036. "data": [
  4037. {
  4038. "click_pv": 0,
  4039. "click_uv": 0,
  4040. "ftime": 1425052800,
  4041. "shake_pv": 0,
  4042. "shake_uv": 0
  4043. },
  4044. {
  4045. "click_pv": 0,
  4046. "click_uv": 0,
  4047. "ftime": 1425139200,
  4048. "shake_pv": 0,
  4049. "shake_uv": 0
  4050. }
  4051. ],
  4052. "errcode": 0,
  4053. "errmsg": "success."
  4054. }
  4055. * 字段说明:
  4056. * ftime 当天0 点对应的时间戳
  4057. * click_pv 点击摇周边消息的次数
  4058. * click_uv 点击摇周边消息的人数
  4059. * shake_pv 摇周边的次数
  4060. * shake_uv 摇周边的人数
  4061. * @author binsee<binsee@163.com>
  4062. * @version 2015-4-21 00:43:00
  4063. */
  4064. public function pageShakeAroundStatistics($page_id,$begin_date,$end_date){
  4065. if (!$this->access_token && !$this->checkAuth()) return false;
  4066. $data = array(
  4067. 'page_id' => $page_id,
  4068. 'begin_date' => $begin_date,
  4069. 'end_date' => $end_date
  4070. );
  4071. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
  4072. $this->log($result);
  4073. if ($result) {
  4074. $json = json_decode($result, true);
  4075. if (!$json || !empty($json['errcode'])) {
  4076. $this->errCode = $json['errcode'];
  4077. $this->errMsg = $json['errmsg'];
  4078. return false;
  4079. }
  4080. return $json;
  4081. }
  4082. return false;
  4083. }
  4084. /**
  4085. * 根据订单ID获取订单详情
  4086. * @param string $order_id 订单ID
  4087. * @return order array|bool
  4088. */
  4089. public function getOrderByID($order_id){
  4090. if (!$this->access_token && !$this->checkAuth()) return false;
  4091. if (!$order_id) return false;
  4092. $data = array(
  4093. 'order_id'=>$order_id
  4094. );
  4095. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_GETBYID.'access_token='.$this->access_token, self::json_encode($data));
  4096. if ($result)
  4097. {
  4098. $json = json_decode($result,true);
  4099. if (isset($json['errcode']) && $json['errcode']) {
  4100. $this->errCode = $json['errcode'];
  4101. $this->errMsg = $json['errmsg'];
  4102. return false;
  4103. }
  4104. return $json['order'];
  4105. }
  4106. return false;
  4107. }
  4108. /**
  4109. * 根据订单状态/创建时间获取订单详情
  4110. * @param int $status 订单状态(不带该字段-全部状态, 2-待发货, 3-已发货, 5-已完成, 8-维权中, )
  4111. * @param int $begintime 订单创建时间起始时间(不带该字段则不按照时间做筛选)
  4112. * @param int $endtime 订单创建时间终止时间(不带该字段则不按照时间做筛选)
  4113. * @return order list array|bool
  4114. */
  4115. public function getOrderByFilter($status = null, $begintime = null, $endtime = null){
  4116. if (!$this->access_token && !$this->checkAuth()) return false;
  4117. $data = array();
  4118. $valid_status = array(2, 3, 5, 8);
  4119. if (is_numeric($status) && in_array($status, $valid_status)) {
  4120. $data['status'] = $status;
  4121. }
  4122. if (is_numeric($begintime) && is_numeric($endtime)) {
  4123. $data['begintime'] = $begintime;
  4124. $data['endtime'] = $endtime;
  4125. }
  4126. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_GETBYFILTER.'access_token='.$this->access_token, self::json_encode($data));
  4127. if ($result)
  4128. {
  4129. $json = json_decode($result,true);
  4130. if (isset($json['errcode']) && $json['errcode']) {
  4131. $this->errCode = $json['errcode'];
  4132. $this->errMsg = $json['errmsg'];
  4133. return false;
  4134. }
  4135. return $json['order_list'];
  4136. }
  4137. return false;
  4138. }
  4139. /**
  4140. * 设置订单发货信息
  4141. * @param string $order_id 订单 ID
  4142. * @param int $need_delivery 商品是否需要物流(0-不需要,1-需要)
  4143. * @param string $delivery_company 物流公司 ID
  4144. * @param string $delivery_track_no 运单 ID
  4145. * @param int $is_others 是否为 6.4.5 表之外的其它物流公司(0-否,1-是)
  4146. * @return bool
  4147. */
  4148. public function setOrderDelivery($order_id, $need_delivery = 0, $delivery_company = null, $delivery_track_no = null, $is_others = 0){
  4149. if (!$this->access_token && !$this->checkAuth()) return false;
  4150. if (!$order_id) return false;
  4151. $data = array();
  4152. $data['order_id'] = $order_id;
  4153. if ($need_delivery) {
  4154. $data['delivery_company'] = $delivery_company;
  4155. $data['delivery_track_no'] = $delivery_track_no;
  4156. $data['is_others'] = $is_others;
  4157. }
  4158. else {
  4159. $data['need_delivery'] = $need_delivery;
  4160. }
  4161. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_SETDELIVERY.'access_token='.$this->access_token, self::json_encode($data));
  4162. if ($result)
  4163. {
  4164. $json = json_decode($result,true);
  4165. if (isset($json['errcode']) && $json['errcode']) {
  4166. $this->errCode = $json['errcode'];
  4167. $this->errMsg = $json['errmsg'];
  4168. return false;
  4169. }
  4170. return true;
  4171. }
  4172. return false;
  4173. }
  4174. /**
  4175. * 关闭订单
  4176. * @param string $order_id 订单 ID
  4177. * @return bool
  4178. */
  4179. public function closeOrder($order_id){
  4180. if (!$this->access_token && !$this->checkAuth()) return false;
  4181. if (!$order_id) return false;
  4182. $data = array(
  4183. 'order_id'=>$order_id
  4184. );
  4185. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::MERCHANT_ORDER_CLOSE.'access_token='.$this->access_token, self::json_encode($data));
  4186. if ($result)
  4187. {
  4188. $json = json_decode($result,true);
  4189. if (isset($json['errcode']) && $json['errcode']) {
  4190. $this->errCode = $json['errcode'];
  4191. $this->errMsg = $json['errmsg'];
  4192. return false;
  4193. }
  4194. return true;
  4195. }
  4196. return false;
  4197. }
  4198. private function parseSkuInfo($skuInfo) {
  4199. $skuInfo = str_replace("\$", "", $skuInfo);
  4200. $matches = explode(";", $skuInfo);
  4201. $result = array();
  4202. foreach ($matches as $matche) {
  4203. $arrs = explode(":", $matche);
  4204. $result[$arrs[0]] = $arrs[1];
  4205. }
  4206. return $result;
  4207. }
  4208. /**
  4209. * 获取订单SkuInfo - 订单付款通知
  4210. * 当Event为 merchant_order(订单付款通知)
  4211. * @return array|boolean
  4212. */
  4213. public function getRevOrderSkuInfo(){
  4214. if (isset($this->_receive['SkuInfo'])) //订单 SkuInfo
  4215. return $this->parseSkuInfo($this->_receive['SkuInfo']);
  4216. else
  4217. return false;
  4218. }
  4219. }
  4220. /**
  4221. * PKCS7Encoder class
  4222. *
  4223. * 提供基于PKCS7算法的加解密接口.
  4224. */
  4225. class PKCS7Encoder
  4226. {
  4227. public static $block_size = 32;
  4228. /**
  4229. * 对需要加密的明文进行填充补位
  4230. * @param $text 需要进行填充补位操作的明文
  4231. * @return 补齐明文字符串
  4232. */
  4233. function encode($text)
  4234. {
  4235. $block_size = PKCS7Encoder::$block_size;
  4236. $text_length = strlen($text);
  4237. //计算需要填充的位数
  4238. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  4239. if ($amount_to_pad == 0) {
  4240. $amount_to_pad = PKCS7Encoder::block_size;
  4241. }
  4242. //获得补位所用的字符
  4243. $pad_chr = chr($amount_to_pad);
  4244. $tmp = "";
  4245. for ($index = 0; $index < $amount_to_pad; $index++) {
  4246. $tmp .= $pad_chr;
  4247. }
  4248. return $text . $tmp;
  4249. }
  4250. /**
  4251. * 对解密后的明文进行补位删除
  4252. * @param decrypted 解密后的明文
  4253. * @return 删除填充补位后的明文
  4254. */
  4255. function decode($text)
  4256. {
  4257. $pad = ord(substr($text, -1));
  4258. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  4259. $pad = 0;
  4260. }
  4261. return substr($text, 0, (strlen($text) - $pad));
  4262. }
  4263. }
  4264. /**
  4265. * Prpcrypt class
  4266. *
  4267. * 提供接收和推送给公众平台消息的加解密接口.
  4268. */
  4269. class Prpcrypt
  4270. {
  4271. public $key;
  4272. function __construct($k) {
  4273. $this->key = base64_decode($k . "=");
  4274. }
  4275. /**
  4276. * 兼容老版本php构造函数,不能在 __construct() 方法前边,否则报错
  4277. */
  4278. function Prpcrypt($k)
  4279. {
  4280. $this->key = base64_decode($k . "=");
  4281. }
  4282. /**
  4283. * 对明文进行加密
  4284. * @param string $text 需要加密的明文
  4285. * @return string 加密后的密文
  4286. */
  4287. public function encrypt($text, $appid)
  4288. {
  4289. try {
  4290. //获得16位随机字符串,填充到明文之前
  4291. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  4292. $text = $random . pack("N", strlen($text)) . $text . $appid;
  4293. // 网络字节序
  4294. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  4295. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  4296. $iv = substr($this->key, 0, 16);
  4297. //使用自定义的填充方式对明文进行补位填充
  4298. $pkc_encoder = new PKCS7Encoder;
  4299. $text = $pkc_encoder->encode($text);
  4300. mcrypt_generic_init($module, $this->key, $iv);
  4301. //加密
  4302. $encrypted = mcrypt_generic($module, $text);
  4303. mcrypt_generic_deinit($module);
  4304. mcrypt_module_close($module);
  4305. // print(base64_encode($encrypted));
  4306. //使用BASE64对加密后的字符串进行编码
  4307. return array(ErrorCode::$OK, base64_encode($encrypted));
  4308. } catch (Exception $e) {
  4309. //print $e;
  4310. return array(ErrorCode::$EncryptAESError, null);
  4311. }
  4312. }
  4313. /**
  4314. * 对密文进行解密
  4315. * @param string $encrypted 需要解密的密文
  4316. * @return string 解密得到的明文
  4317. */
  4318. public function decrypt($encrypted, $appid)
  4319. {
  4320. try {
  4321. //使用BASE64对需要解密的字符串进行解码
  4322. $ciphertext_dec = base64_decode($encrypted);
  4323. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  4324. $iv = substr($this->key, 0, 16);
  4325. mcrypt_generic_init($module, $this->key, $iv);
  4326. //解密
  4327. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  4328. mcrypt_generic_deinit($module);
  4329. mcrypt_module_close($module);
  4330. } catch (Exception $e) {
  4331. return array(ErrorCode::$DecryptAESError, null);
  4332. }
  4333. try {
  4334. //去除补位字符
  4335. $pkc_encoder = new PKCS7Encoder;
  4336. $result = $pkc_encoder->decode($decrypted);
  4337. //去除16位随机字符串,网络字节序和AppId
  4338. if (strlen($result) < 16)
  4339. return "";
  4340. $content = substr($result, 16, strlen($result));
  4341. $len_list = unpack("N", substr($content, 0, 4));
  4342. $xml_len = $len_list[1];
  4343. $xml_content = substr($content, 4, $xml_len);
  4344. $from_appid = substr($content, $xml_len + 4);
  4345. if (!$appid)
  4346. $appid = $from_appid;
  4347. //如果传入的appid是空的,则认为是订阅号,使用数据中提取出来的appid
  4348. } catch (Exception $e) {
  4349. //print $e;
  4350. return array(ErrorCode::$IllegalBuffer, null);
  4351. }
  4352. if ($from_appid != $appid)
  4353. return array(ErrorCode::$ValidateAppidError, null);
  4354. //不注释上边两行,避免传入appid是错误的情况
  4355. return array(0, $xml_content, $from_appid); //增加appid,为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
  4356. }
  4357. /**
  4358. * 随机生成16位字符串
  4359. * @return string 生成的字符串
  4360. */
  4361. function getRandomStr()
  4362. {
  4363. $str = "";
  4364. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  4365. $max = strlen($str_pol) - 1;
  4366. for ($i = 0; $i < 16; $i++) {
  4367. $str .= $str_pol[mt_rand(0, $max)];
  4368. }
  4369. return $str;
  4370. }
  4371. }
  4372. /**
  4373. * error code
  4374. * 仅用作类内部使用,不用于官方API接口的errCode码
  4375. */
  4376. class ErrorCode
  4377. {
  4378. public static $OK = 0;
  4379. public static $ValidateSignatureError = 40001;
  4380. public static $ParseXmlError = 40002;
  4381. public static $ComputeSignatureError = 40003;
  4382. public static $IllegalAesKey = 40004;
  4383. public static $ValidateAppidError = 40005;
  4384. public static $EncryptAESError = 40006;
  4385. public static $DecryptAESError = 40007;
  4386. public static $IllegalBuffer = 40008;
  4387. public static $EncodeBase64Error = 40009;
  4388. public static $DecodeBase64Error = 40010;
  4389. public static $GenReturnXmlError = 40011;
  4390. public static $errCode=array(
  4391. '0' => '处理成功',
  4392. '40001' => '校验签名失败',
  4393. '40002' => '解析xml失败',
  4394. '40003' => '计算签名失败',
  4395. '40004' => '不合法的AESKey',
  4396. '40005' => '校验AppID失败',
  4397. '40006' => 'AES加密失败',
  4398. '40007' => 'AES解密失败',
  4399. '40008' => '公众平台发送的xml不合法',
  4400. '40009' => 'Base64编码失败',
  4401. '40010' => 'Base64解码失败',
  4402. '40011' => '公众帐号生成回包xml失败'
  4403. );
  4404. public static function getErrText($err) {
  4405. if (isset(self::$errCode[$err])) {
  4406. return self::$errCode[$err];
  4407. }else {
  4408. return false;
  4409. };
  4410. }
  4411. }