Wechat.php 111 KB

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