wechat.class.php 104 KB

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