Wechat.class.php 104 KB

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