wechat.class.php 103 KB

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