wechat.class.php 110 KB

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