wechat.class.php 119 KB

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