Wechat.php 111 KB

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