wechat.class.php 159 KB

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