wechat.class.php 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490
  1. <?php
  2. /**
  3. * 微信公众平台PHP-SDK, 官方API部分
  4. * @author dodge <dodgepudding@gmail.com>
  5. * @link https://github.com/dodgepudding/wechat-php-sdk
  6. * @version 1.2
  7. * usage:
  8. * $options = array(
  9. * 'token'=>'tokenaccesskey', //填写你设定的key
  10. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  11. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  12. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
  13. * 'partnerid'=>'88888888', //财付通商户身份标识
  14. * 'partnerkey'=>'', //财付通商户权限密钥Key
  15. * 'paysignkey'=>'' //商户签名密钥Key
  16. * );
  17. * $weObj = new Wechat($options);
  18. * $weObj->valid();
  19. * $type = $weObj->getRev()->getRevType();
  20. * switch($type) {
  21. * case Wechat::MSGTYPE_TEXT:
  22. * $weObj->text("hello, I'm wechat")->reply();
  23. * exit;
  24. * break;
  25. * case Wechat::MSGTYPE_EVENT:
  26. * ....
  27. * break;
  28. * case Wechat::MSGTYPE_IMAGE:
  29. * ...
  30. * break;
  31. * default:
  32. * $weObj->text("help info")->reply();
  33. * }
  34. *
  35. * //获取菜单操作:
  36. * $menu = $weObj->getMenu();
  37. * //设置菜单
  38. * $newmenu = array(
  39. * "button"=>
  40. * array(
  41. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  42. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  43. * )
  44. * );
  45. * $result = $weObj->createMenu($newmenu);
  46. */
  47. class Wechat
  48. {
  49. const MSGTYPE_TEXT = 'text';
  50. const MSGTYPE_IMAGE = 'image';
  51. const MSGTYPE_LOCATION = 'location';
  52. const MSGTYPE_LINK = 'link';
  53. const MSGTYPE_EVENT = 'event';
  54. const MSGTYPE_MUSIC = 'music';
  55. const MSGTYPE_NEWS = 'news';
  56. const MSGTYPE_VOICE = 'voice';
  57. const MSGTYPE_VIDEO = 'video';
  58. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  59. const AUTH_URL = '/token?grant_type=client_credential&';
  60. const MENU_CREATE_URL = '/menu/create?';
  61. const MENU_GET_URL = '/menu/get?';
  62. const MENU_DELETE_URL = '/menu/delete?';
  63. const CALLBACKSERVER_GET_URL = '/getcallbackip?';
  64. const QRCODE_CREATE_URL='/qrcode/create?';
  65. const QR_SCENE = 0;
  66. const QR_LIMIT_SCENE = 1;
  67. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  68. const SHORT_URL='/shorturl?';
  69. const USER_GET_URL='/user/get?';
  70. const USER_INFO_URL='/user/info?';
  71. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  72. const GROUP_GET_URL='/groups/get?';
  73. const USER_GROUP_URL='/groups/getid?';
  74. const GROUP_CREATE_URL='/groups/create?';
  75. const GROUP_UPDATE_URL='/groups/update?';
  76. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  77. const CUSTOM_SEND_URL='/message/custom/send?';
  78. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  79. const MASS_SEND_URL = '/message/mass/send?';
  80. const TEMPLATE_SEND_URL = '/message/template/send?';
  81. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  82. const MASS_DELETE_URL = '/message/mass/delete?';
  83. const MASS_PREVIEW_URL = '/message/mass/preview?';
  84. const MASS_QUERY_URL = '/message/mass/get?';
  85. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  86. const MEDIA_UPLOAD = '/media/upload?';
  87. const MEDIA_GET_URL = '/media/get?';
  88. const MEDIA_VIDEO_UPLOAD = '/media/uploadvideo?';
  89. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  90. const OAUTH_AUTHORIZE_URL = '/authorize?';
  91. const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com'; //以下API接口URL需要使用此前缀
  92. const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
  93. const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
  94. const OAUTH_USERINFO_URL = '/sns/oauth2/sns/userinfo?';
  95. const OAUTH_AUTH_URL = '/sns/auth?';
  96. const PAY_DELIVERNOTIFY = '/pay/delivernotify?';
  97. const PAY_ORDERQUERY = '/pay/orderquery?';
  98. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  99. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  100. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getonlinekflist?';
  101. const CS_KF_ACCOUNT_ADD_URL = '/customservice/kfaccount/add?';
  102. const CS_KF_ACCOUNT_UPDATE_URL = '/customservice/kfaccount/update?';
  103. const CS_KF_ACCOUNT_DEL_URL = '/customservice/kfaccount/del?';
  104. const CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL = '/customservice/kfaccount/uploadheadimg?';
  105. const SEMANTIC_API_URL= '/semantic/semproxy/search?';
  106. private $token;
  107. private $encodingAesKey;
  108. private $encrypt_type;
  109. private $appid;
  110. private $appsecret;
  111. private $access_token;
  112. private $user_token;
  113. private $partnerid;
  114. private $partnerkey;
  115. private $paysignkey;
  116. private $postxml;
  117. private $_msg;
  118. private $_funcflag = false;
  119. private $_receive;
  120. private $_text_filter = true;
  121. public $debug = false;
  122. public $errCode = 40001;
  123. public $errMsg = "no access";
  124. private $_logcallback;
  125. public function __construct($options)
  126. {
  127. $this->token = isset($options['token'])?$options['token']:'';
  128. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  129. $this->appid = isset($options['appid'])?$options['appid']:'';
  130. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  131. $this->partnerid = isset($options['partnerid'])?$options['partnerid']:'';
  132. $this->partnerkey = isset($options['partnerkey'])?$options['partnerkey']:'';
  133. $this->paysignkey = isset($options['paysignkey'])?$options['paysignkey']:'';
  134. $this->debug = isset($options['debug'])?$options['debug']:false;
  135. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  136. }
  137. /**
  138. * For weixin server validation
  139. */
  140. private function checkSignature($str='')
  141. {
  142. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  143. $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密验证则用加密验证段
  144. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  145. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  146. $token = $this->token;
  147. $tmpArr = array($token, $timestamp, $nonce,$str);
  148. sort($tmpArr, SORT_STRING);
  149. $tmpStr = implode( $tmpArr );
  150. $tmpStr = sha1( $tmpStr );
  151. if( $tmpStr == $signature ){
  152. return true;
  153. }else{
  154. return false;
  155. }
  156. }
  157. /**
  158. * For weixin server validation
  159. * @param bool $return 是否返回
  160. */
  161. public function valid($return=false)
  162. {
  163. $encryptStr="";
  164. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  165. $postStr = file_get_contents("php://input");
  166. $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  167. $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"]: '';
  168. if ($this->encrypt_type == 'aes') { //aes加密
  169. $this->log($postStr);
  170. $encryptStr = $array['Encrypt'];
  171. $pc = new Prpcrypt($this->encodingAesKey);
  172. $array = $pc->decrypt($encryptStr,$this->appid);
  173. if (!isset($array[0]) || ($array[0] != 0)) {
  174. if (!$return) {
  175. die('decrypt error!');
  176. } else {
  177. return false;
  178. }
  179. }
  180. $this->postxml = $array[1];
  181. if (!$this->appid)
  182. $this->appid = $array[2];//为了没有appid的订阅号。
  183. } else {
  184. $this->postxml = $postStr;
  185. }
  186. } elseif (isset($_GET["echostr"])) {
  187. $echoStr = $_GET["echostr"];
  188. if ($return) {
  189. if ($this->checkSignature())
  190. return $echoStr;
  191. else
  192. return false;
  193. } else {
  194. if ($this->checkSignature())
  195. die($echoStr);
  196. else
  197. die('no access');
  198. }
  199. }
  200. if (!$this->checkSignature($encryptStr)) {
  201. if ($return)
  202. return false;
  203. else
  204. die('no access');
  205. }
  206. return true;
  207. }
  208. /**
  209. * 设置发送消息
  210. * @param array $msg 消息数组
  211. * @param bool $append 是否在原消息数组追加
  212. */
  213. public function Message($msg = '',$append = false){
  214. if (is_null($msg)) {
  215. $this->_msg =array();
  216. }elseif (is_array($msg)) {
  217. if ($append)
  218. $this->_msg = array_merge($this->_msg,$msg);
  219. else
  220. $this->_msg = $msg;
  221. return $this->_msg;
  222. } else {
  223. return $this->_msg;
  224. }
  225. }
  226. public function setFuncFlag($flag) {
  227. $this->_funcflag = $flag;
  228. return $this;
  229. }
  230. private function log($log){
  231. if ($this->debug && function_exists($this->_logcallback)) {
  232. if (is_array($log)) $log = print_r($log,true);
  233. return call_user_func($this->_logcallback,$log);
  234. }
  235. }
  236. /**
  237. * 获取微信服务器发来的信息
  238. */
  239. public function getRev()
  240. {
  241. if ($this->_receive) return $this;
  242. $postStr = !empty($this->postxml)?$this->postxml:file_get_contents("php://input");
  243. //兼顾使用明文又不想调用valid()方法的情况
  244. $this->log($postStr);
  245. if (!empty($postStr)) {
  246. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  247. }
  248. return $this;
  249. }
  250. /**
  251. * 获取微信服务器发来的信息
  252. */
  253. public function getRevData()
  254. {
  255. return $this->_receive;
  256. }
  257. /**
  258. * 获取消息发送者
  259. */
  260. public function getRevFrom() {
  261. if (isset($this->_receive['FromUserName']))
  262. return $this->_receive['FromUserName'];
  263. else
  264. return false;
  265. }
  266. /**
  267. * 获取消息接受者
  268. */
  269. public function getRevTo() {
  270. if (isset($this->_receive['ToUserName']))
  271. return $this->_receive['ToUserName'];
  272. else
  273. return false;
  274. }
  275. /**
  276. * 获取接收消息的类型
  277. */
  278. public function getRevType() {
  279. if (isset($this->_receive['MsgType']))
  280. return $this->_receive['MsgType'];
  281. else
  282. return false;
  283. }
  284. /**
  285. * 获取消息ID
  286. */
  287. public function getRevID() {
  288. if (isset($this->_receive['MsgId']))
  289. return $this->_receive['MsgId'];
  290. else
  291. return false;
  292. }
  293. /**
  294. * 获取消息发送时间
  295. */
  296. public function getRevCtime() {
  297. if (isset($this->_receive['CreateTime']))
  298. return $this->_receive['CreateTime'];
  299. else
  300. return false;
  301. }
  302. /**
  303. * 获取接收消息内容正文
  304. */
  305. public function getRevContent(){
  306. if (isset($this->_receive['Content']))
  307. return $this->_receive['Content'];
  308. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  309. return $this->_receive['Recognition'];
  310. else
  311. return false;
  312. }
  313. /**
  314. * 获取接收消息图片
  315. */
  316. public function getRevPic(){
  317. if (isset($this->_receive['PicUrl']))
  318. return array(
  319. 'mediaid'=>$this->_receive['MediaId'],
  320. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  321. );
  322. else
  323. return false;
  324. }
  325. /**
  326. * 获取接收消息链接
  327. */
  328. public function getRevLink(){
  329. if (isset($this->_receive['Url'])){
  330. return array(
  331. 'url'=>$this->_receive['Url'],
  332. 'title'=>$this->_receive['Title'],
  333. 'description'=>$this->_receive['Description']
  334. );
  335. } else
  336. return false;
  337. }
  338. /**
  339. * 获取接收地理位置
  340. */
  341. public function getRevGeo(){
  342. if (isset($this->_receive['Location_X'])){
  343. return array(
  344. 'x'=>$this->_receive['Location_X'],
  345. 'y'=>$this->_receive['Location_Y'],
  346. 'scale'=>$this->_receive['Scale'],
  347. 'label'=>$this->_receive['Label']
  348. );
  349. } else
  350. return false;
  351. }
  352. /**
  353. * 获取上报地理位置事件
  354. */
  355. public function getRevEventGeo(){
  356. if (isset($this->_receive['Latitude'])){
  357. return array(
  358. 'x'=>$this->_receive['Latitude'],
  359. 'y'=>$this->_receive['Longitude'],
  360. 'precision'=>$this->_receive['Precision'],
  361. );
  362. } else
  363. return false;
  364. }
  365. /**
  366. * 获取接收事件推送
  367. */
  368. public function getRevEvent(){
  369. if (isset($this->_receive['Event'])){
  370. $array['event'] = $this->_receive['Event'];
  371. }
  372. if (isset($this->_receive['EventKey'])){
  373. $array['key'] = $this->_receive['EventKey'];
  374. }
  375. if (isset($array) && count($array) > 0) {
  376. return $array;
  377. } else {
  378. return false;
  379. }
  380. }
  381. /**
  382. * 获取自定义菜单的扫码推事件信息
  383. *
  384. * 事件类型为以下两种时则调用此方法有效
  385. * Event 事件类型,scancode_push
  386. * Event 事件类型,scancode_waitmsg
  387. *
  388. * @return: array | false
  389. * array (
  390. * 'ScanType'=>'qrcode',
  391. * 'ScanResult'=>'123123'
  392. * )
  393. */
  394. public function getRevScanInfo(){
  395. if (isset($this->_receive['ScanCodeInfo'])){
  396. if (!is_array($this->_receive['SendPicsInfo'])) {
  397. $array=(array)$this->_receive['ScanCodeInfo'];
  398. $this->_receive['ScanCodeInfo']=$array;
  399. }else {
  400. $array=$this->_receive['ScanCodeInfo'];
  401. }
  402. }
  403. if (isset($array) && count($array) > 0) {
  404. return $array;
  405. } else {
  406. return false;
  407. }
  408. }
  409. /**
  410. * 获取自定义菜单的图片发送事件信息
  411. *
  412. * 事件类型为以下三种时则调用此方法有效
  413. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  414. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  415. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  416. *
  417. * @return: array | false
  418. * array (
  419. * 'Count' => '2',
  420. * 'PicList' =>array (
  421. * 'item' =>array (
  422. * 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
  423. * 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
  424. * ),
  425. * ),
  426. * )
  427. *
  428. */
  429. public function getRevSendPicsInfo(){
  430. if (isset($this->_receive['SendPicsInfo'])){
  431. if (!is_array($this->_receive['SendPicsInfo'])) {
  432. $array=(array)$this->_receive['SendPicsInfo'];
  433. if (isset($array['PicList'])){
  434. $array['PicList']=(array)$array['PicList'];
  435. $item=$array['PicList']['item'];
  436. $array['PicList']['item']=array();
  437. foreach ( $item as $key => $value ){
  438. $array['PicList']['item'][$key]=(array)$value;
  439. }
  440. }
  441. $this->_receive['SendPicsInfo']=$array;
  442. } else {
  443. $array=$this->_receive['SendPicsInfo'];
  444. }
  445. }
  446. if (isset($array) && count($array) > 0) {
  447. return $array;
  448. } else {
  449. return false;
  450. }
  451. }
  452. /**
  453. * 获取自定义菜单的地理位置选择器事件推送
  454. *
  455. * 事件类型为以下时则可以调用此方法有效
  456. * Event 事件类型,location_select 弹出系统拍照发图的事件推送
  457. *
  458. * @return: array | false
  459. * array (
  460. * 'Location_X' => '33.731655000061',
  461. * 'Location_Y' => '113.29955200008047',
  462. * 'Scale' => '16',
  463. * 'Label' => '某某市某某区某某路',
  464. * 'Poiname' => '',
  465. * )
  466. *
  467. */
  468. public function getRevSendGeoInfo(){
  469. if (isset($this->_receive['SendLocationInfo'])){
  470. if (!is_array($this->_receive['SendLocationInfo'])) {
  471. $array=(array)$this->_receive['SendLocationInfo'];
  472. if (empty($array['Poiname'])) {
  473. $array['Poiname']="";
  474. }
  475. if (empty($array['Label'])) {
  476. $array['Label']="";
  477. }
  478. $this->_receive['SendLocationInfo']=$array;
  479. } else {
  480. $array=$this->_receive['SendLocationInfo'];
  481. }
  482. }
  483. if (isset($array) && count($array) > 0) {
  484. return $array;
  485. } else {
  486. return false;
  487. }
  488. }
  489. /**
  490. * 获取接收语音推送
  491. */
  492. public function getRevVoice(){
  493. if (isset($this->_receive['MediaId'])){
  494. return array(
  495. 'mediaid'=>$this->_receive['MediaId'],
  496. 'format'=>$this->_receive['Format'],
  497. );
  498. } else
  499. return false;
  500. }
  501. /**
  502. * 获取接收视频推送
  503. */
  504. public function getRevVideo(){
  505. if (isset($this->_receive['MediaId'])){
  506. return array(
  507. 'mediaid'=>$this->_receive['MediaId'],
  508. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  509. );
  510. } else
  511. return false;
  512. }
  513. /**
  514. * 获取接收TICKET
  515. */
  516. public function getRevTicket(){
  517. if (isset($this->_receive['Ticket'])){
  518. return $this->_receive['Ticket'];
  519. } else
  520. return false;
  521. }
  522. /**
  523. * 获取二维码的场景值
  524. */
  525. public function getRevSceneId (){
  526. if (isset($this->_receive['EventKey'])){
  527. return str_replace('qrscene_','',$this->_receive['EventKey']);
  528. } else{
  529. return false;
  530. }
  531. }
  532. /**
  533. * 获取主动推送的消息ID
  534. * 经过验证,这个和普通的消息MsgId不一样
  535. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH
  536. */
  537. public function getRevTplMsgID(){
  538. if (isset($this->_receive['MsgID'])){
  539. return $this->_receive['MsgID'];
  540. } else
  541. return false;
  542. }
  543. /**
  544. * 获取模板消息发送状态
  545. */
  546. public function getRevStatus(){
  547. if (isset($this->_receive['Status'])){
  548. return $this->_receive['Status'];
  549. } else
  550. return false;
  551. }
  552. /**
  553. * 获取群发或模板消息发送结果
  554. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH,即高级群发/模板消息
  555. */
  556. public function getRevResult(){
  557. if (isset($this->_receive['Status'])) //发送是否成功,具体的返回值请参考 高级群发/模板消息 的事件推送说明
  558. $array['Status'] = $this->_receive['Status'];
  559. if (isset($this->_receive['MsgID'])) //发送的消息id
  560. $array['MsgID'] = $this->_receive['MsgID'];
  561. //以下仅当群发消息时才会有的事件内容
  562. if (isset($this->_receive['TotalCount'])) //分组或openid列表内粉丝数量
  563. $array['TotalCount'] = $this->_receive['TotalCount'];
  564. if (isset($this->_receive['FilterCount'])) //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数
  565. $array['FilterCount'] = $this->_receive['FilterCount'];
  566. if (isset($this->_receive['SentCount'])) //发送成功的粉丝数
  567. $array['SentCount'] = $this->_receive['SentCount'];
  568. if (isset($this->_receive['ErrorCount'])) //发送失败的粉丝数
  569. $array['ErrorCount'] = $this->_receive['ErrorCount'];
  570. if (isset($array) && count($array) > 0) {
  571. return $array;
  572. } else {
  573. return false;
  574. }
  575. }
  576. public static function xmlSafeStr($str)
  577. {
  578. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  579. }
  580. /**
  581. * 数据XML编码
  582. * @param mixed $data 数据
  583. * @return string
  584. */
  585. public static function data_to_xml($data) {
  586. $xml = '';
  587. foreach ($data as $key => $val) {
  588. is_numeric($key) && $key = "item id=\"$key\"";
  589. $xml .= "<$key>";
  590. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  591. list($key, ) = explode(' ', $key);
  592. $xml .= "</$key>";
  593. }
  594. return $xml;
  595. }
  596. /**
  597. * XML编码
  598. * @param mixed $data 数据
  599. * @param string $root 根节点名
  600. * @param string $item 数字索引的子节点名
  601. * @param string $attr 根节点属性
  602. * @param string $id 数字索引子节点key转换的属性名
  603. * @param string $encoding 数据编码
  604. * @return string
  605. */
  606. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  607. if(is_array($attr)){
  608. $_attr = array();
  609. foreach ($attr as $key => $value) {
  610. $_attr[] = "{$key}=\"{$value}\"";
  611. }
  612. $attr = implode(' ', $_attr);
  613. }
  614. $attr = trim($attr);
  615. $attr = empty($attr) ? '' : " {$attr}";
  616. $xml = "<{$root}{$attr}>";
  617. $xml .= self::data_to_xml($data, $item, $id);
  618. $xml .= "</{$root}>";
  619. return $xml;
  620. }
  621. /**
  622. * 过滤文字回复\r\n换行符
  623. * @param string $text
  624. * @return string|mixed
  625. */
  626. private function _auto_text_filter($text) {
  627. if (!$this->_text_filter) return $text;
  628. return str_replace("\r\n", "\n", $text);
  629. }
  630. /**
  631. * 设置回复消息
  632. * Example: $obj->text('hello')->reply();
  633. * @param string $text
  634. */
  635. public function text($text='')
  636. {
  637. $FuncFlag = $this->_funcflag ? 1 : 0;
  638. $msg = array(
  639. 'ToUserName' => $this->getRevFrom(),
  640. 'FromUserName'=>$this->getRevTo(),
  641. 'MsgType'=>self::MSGTYPE_TEXT,
  642. 'Content'=>$this->_auto_text_filter($text),
  643. 'CreateTime'=>time(),
  644. 'FuncFlag'=>$FuncFlag
  645. );
  646. $this->Message($msg);
  647. return $this;
  648. }
  649. /**
  650. * 设置回复消息
  651. * Example: $obj->image('media_id')->reply();
  652. * @param string $mediaid
  653. */
  654. public function image($mediaid='')
  655. {
  656. $FuncFlag = $this->_funcflag ? 1 : 0;
  657. $msg = array(
  658. 'ToUserName' => $this->getRevFrom(),
  659. 'FromUserName'=>$this->getRevTo(),
  660. 'MsgType'=>self::MSGTYPE_IMAGE,
  661. 'Image'=>array('MediaId'=>$mediaid),
  662. 'CreateTime'=>time(),
  663. 'FuncFlag'=>$FuncFlag
  664. );
  665. $this->Message($msg);
  666. return $this;
  667. }
  668. /**
  669. * 设置回复消息
  670. * Example: $obj->voice('media_id')->reply();
  671. * @param string $mediaid
  672. */
  673. public function voice($mediaid='')
  674. {
  675. $FuncFlag = $this->_funcflag ? 1 : 0;
  676. $msg = array(
  677. 'ToUserName' => $this->getRevFrom(),
  678. 'FromUserName'=>$this->getRevTo(),
  679. 'MsgType'=>self::MSGTYPE_VOICE,
  680. 'Voice'=>array('MediaId'=>$mediaid),
  681. 'CreateTime'=>time(),
  682. 'FuncFlag'=>$FuncFlag
  683. );
  684. $this->Message($msg);
  685. return $this;
  686. }
  687. /**
  688. * 设置回复消息
  689. * Example: $obj->video('media_id','title','description')->reply();
  690. * @param string $mediaid
  691. */
  692. public function video($mediaid='',$title='',$description='')
  693. {
  694. $FuncFlag = $this->_funcflag ? 1 : 0;
  695. $msg = array(
  696. 'ToUserName' => $this->getRevFrom(),
  697. 'FromUserName'=>$this->getRevTo(),
  698. 'MsgType'=>self::MSGTYPE_VIDEO,
  699. 'Video'=>array(
  700. 'MediaId'=>$mediaid,
  701. 'Title'=>$title,
  702. 'Description'=>$description
  703. ),
  704. 'CreateTime'=>time(),
  705. 'FuncFlag'=>$FuncFlag
  706. );
  707. $this->Message($msg);
  708. return $this;
  709. }
  710. /**
  711. * 设置回复音乐
  712. * @param string $title
  713. * @param string $desc
  714. * @param string $musicurl
  715. * @param string $hgmusicurl
  716. */
  717. public function music($title,$desc,$musicurl,$hgmusicurl='') {
  718. $FuncFlag = $this->_funcflag ? 1 : 0;
  719. $msg = array(
  720. 'ToUserName' => $this->getRevFrom(),
  721. 'FromUserName'=>$this->getRevTo(),
  722. 'CreateTime'=>time(),
  723. 'MsgType'=>self::MSGTYPE_MUSIC,
  724. 'Music'=>array(
  725. 'Title'=>$title,
  726. 'Description'=>$desc,
  727. 'MusicUrl'=>$musicurl,
  728. 'HQMusicUrl'=>$hgmusicurl
  729. ),
  730. 'FuncFlag'=>$FuncFlag
  731. );
  732. $this->Message($msg);
  733. return $this;
  734. }
  735. /**
  736. * 设置回复图文
  737. * @param array $newsData
  738. * 数组结构:
  739. * array(
  740. * "0"=>array(
  741. * 'Title'=>'msg title',
  742. * 'Description'=>'summary text',
  743. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  744. * 'Url'=>'http://www.domain.com/1.html'
  745. * ),
  746. * "1"=>....
  747. * )
  748. */
  749. public function news($newsData=array())
  750. {
  751. $FuncFlag = $this->_funcflag ? 1 : 0;
  752. $count = count($newsData);
  753. $msg = array(
  754. 'ToUserName' => $this->getRevFrom(),
  755. 'FromUserName'=>$this->getRevTo(),
  756. 'MsgType'=>self::MSGTYPE_NEWS,
  757. 'CreateTime'=>time(),
  758. 'ArticleCount'=>$count,
  759. 'Articles'=>$newsData,
  760. 'FuncFlag'=>$FuncFlag
  761. );
  762. $this->Message($msg);
  763. return $this;
  764. }
  765. /**
  766. *
  767. * 回复微信服务器, 此函数支持链式操作
  768. * Example: $this->text('msg tips')->reply();
  769. * @param string $msg 要发送的信息, 默认取$this->_msg
  770. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  771. */
  772. public function reply($msg=array(),$return = false)
  773. {
  774. if (empty($msg))
  775. $msg = $this->_msg;
  776. $xmldata= $this->xml_encode($msg);
  777. $this->log($xmldata);
  778. if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式
  779. $pc = new Prpcrypt($this->encodingAesKey);
  780. $array = $pc->encrypt($xmldata, $this->appid);
  781. $ret = $array[0];
  782. if ($ret != 0) {
  783. $this->log('encrypt err!');
  784. return false;
  785. }
  786. $timestamp = time();
  787. $nonce = rand(77,999)*rand(605,888)*rand(11,99);
  788. $encrypt = $array[1];
  789. $tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
  790. sort($tmpArr, SORT_STRING);
  791. $signature = implode($tmpArr);
  792. $signature = sha1($signature);
  793. $xmldata = $this->generate($encrypt, $signature, $timestamp, $nonce);
  794. $this->log($xmldata);
  795. }
  796. if ($return)
  797. return $xmldata;
  798. else
  799. echo $xmldata;
  800. }
  801. /**
  802. * xml格式加密,仅请求为加密方式时再用
  803. */
  804. private function generate($encrypt, $signature, $timestamp, $nonce)
  805. {
  806. //格式化加密信息
  807. $format = "<xml>
  808. <Encrypt><![CDATA[%s]]></Encrypt>
  809. <MsgSignature><![CDATA[%s]]></MsgSignature>
  810. <TimeStamp>%s</TimeStamp>
  811. <Nonce><![CDATA[%s]]></Nonce>
  812. </xml>";
  813. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  814. }
  815. /**
  816. * GET 请求
  817. * @param string $url
  818. */
  819. private function http_get($url){
  820. $oCurl = curl_init();
  821. if(stripos($url,"https://")!==FALSE){
  822. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  823. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  824. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  825. }
  826. curl_setopt($oCurl, CURLOPT_URL, $url);
  827. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  828. $sContent = curl_exec($oCurl);
  829. $aStatus = curl_getinfo($oCurl);
  830. curl_close($oCurl);
  831. if(intval($aStatus["http_code"])==200){
  832. return $sContent;
  833. }else{
  834. return false;
  835. }
  836. }
  837. /**
  838. * POST 请求
  839. * @param string $url
  840. * @param array $param
  841. * @param boolean $post_file 是否文件上传
  842. * @return string content
  843. */
  844. private function http_post($url,$param,$post_file=false){
  845. $oCurl = curl_init();
  846. if(stripos($url,"https://")!==FALSE){
  847. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  848. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  849. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  850. }
  851. if (is_string($param) || $post_file) {
  852. $strPOST = $param;
  853. } else {
  854. $aPOST = array();
  855. foreach($param as $key=>$val){
  856. $aPOST[] = $key."=".urlencode($val);
  857. }
  858. $strPOST = join("&", $aPOST);
  859. }
  860. curl_setopt($oCurl, CURLOPT_URL, $url);
  861. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  862. curl_setopt($oCurl, CURLOPT_POST,true);
  863. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  864. $sContent = curl_exec($oCurl);
  865. $aStatus = curl_getinfo($oCurl);
  866. curl_close($oCurl);
  867. if(intval($aStatus["http_code"])==200){
  868. return $sContent;
  869. }else{
  870. return false;
  871. }
  872. }
  873. /**
  874. * 通用auth验证方法,暂时仅用于菜单更新操作
  875. * @param string $appid
  876. * @param string $appsecret
  877. * @param string $token 手动指定access_token,非必要情况不建议用
  878. */
  879. public function checkAuth($appid='',$appsecret='',$token=''){
  880. if (!$appid || !$appsecret) {
  881. $appid = $this->appid;
  882. $appsecret = $this->appsecret;
  883. }
  884. if ($token) { //手动指定token,优先使用
  885. $this->access_token=$token;
  886. return $this->access_token;
  887. }
  888. //TODO: get the cache access_token
  889. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  890. if ($result)
  891. {
  892. $json = json_decode($result,true);
  893. if (!$json || isset($json['errcode'])) {
  894. $this->errCode = $json['errcode'];
  895. $this->errMsg = $json['errmsg'];
  896. return false;
  897. }
  898. $this->access_token = $json['access_token'];
  899. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  900. //TODO: cache access_token
  901. return $this->access_token;
  902. }
  903. return false;
  904. }
  905. /**
  906. * 删除验证数据
  907. * @param string $appid
  908. */
  909. public function resetAuth($appid=''){
  910. if (!$appid) $appid = $this->appid;
  911. $this->access_token = '';
  912. //TODO: remove cache
  913. return true;
  914. }
  915. /**
  916. * 微信api不支持中文转义的json结构
  917. * @param array $arr
  918. */
  919. static function json_encode($arr) {
  920. $parts = array ();
  921. $is_list = false;
  922. //Find out if the given array is a numerical array
  923. $keys = array_keys ( $arr );
  924. $max_length = count ( $arr ) - 1;
  925. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  926. $is_list = true;
  927. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  928. if ($i != $keys [$i]) { //A key fails at position check.
  929. $is_list = false; //It is an associative array.
  930. break;
  931. }
  932. }
  933. }
  934. foreach ( $arr as $key => $value ) {
  935. if (is_array ( $value )) { //Custom handling for arrays
  936. if ($is_list)
  937. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  938. else
  939. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  940. } else {
  941. $str = '';
  942. if (! $is_list)
  943. $str = '"' . $key . '":';
  944. //Custom handling for multiple data types
  945. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  946. $str .= $value; //Numbers
  947. elseif ($value === false)
  948. $str .= 'false'; //The booleans
  949. elseif ($value === true)
  950. $str .= 'true';
  951. else
  952. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  953. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  954. $parts [] = $str;
  955. }
  956. }
  957. $json = implode ( ',', $parts );
  958. if ($is_list)
  959. return '[' . $json . ']'; //Return numerical JSON
  960. return '{' . $json . '}'; //Return associative JSON
  961. }
  962. /**
  963. * 获取微信服务器IP地址列表
  964. * @return array('127.0.0.1','127.0.0.1')
  965. */
  966. public function getServerIp(){
  967. if (!$this->access_token && !$this->checkAuth()) return false;
  968. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  969. if ($result)
  970. {
  971. $json = json_decode($result,true);
  972. if (!$json || isset($json['errcode'])) {
  973. $this->errCode = $json['errcode'];
  974. $this->errMsg = $json['errmsg'];
  975. return false;
  976. }
  977. return $json['ip_list'];
  978. }
  979. return false;
  980. }
  981. /**
  982. * 创建菜单(认证后的订阅号可用)
  983. * @param array $data 菜单数组数据
  984. * example:
  985. * array (
  986. * 'button' => array (
  987. * 0 => array (
  988. * 'name' => '扫码',
  989. * 'sub_button' => array (
  990. * 0 => array (
  991. * 'type' => 'scancode_waitmsg',
  992. * 'name' => '扫码带提示',
  993. * 'key' => 'rselfmenu_0_0',
  994. * ),
  995. * 1 => array (
  996. * 'type' => 'scancode_push',
  997. * 'name' => '扫码推事件',
  998. * 'key' => 'rselfmenu_0_1',
  999. * ),
  1000. * ),
  1001. * ),
  1002. * 1 => array (
  1003. * 'name' => '发图',
  1004. * 'sub_button' => array (
  1005. * 0 => array (
  1006. * 'type' => 'pic_sysphoto',
  1007. * 'name' => '系统拍照发图',
  1008. * 'key' => 'rselfmenu_1_0',
  1009. * ),
  1010. * 1 => array (
  1011. * 'type' => 'pic_photo_or_album',
  1012. * 'name' => '拍照或者相册发图',
  1013. * 'key' => 'rselfmenu_1_1',
  1014. * )
  1015. * ),
  1016. * ),
  1017. * 2 => array (
  1018. * 'type' => 'location_select',
  1019. * 'name' => '发送位置',
  1020. * 'key' => 'rselfmenu_2_0'
  1021. * ),
  1022. * ),
  1023. * )
  1024. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  1025. * 1、click:点击推事件
  1026. * 2、view:跳转URL
  1027. * 3、scancode_push:扫码推事件
  1028. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1029. * 5、pic_sysphoto:弹出系统拍照发图
  1030. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1031. * 7、pic_weixin:弹出微信相册发图器
  1032. * 8、location_select:弹出地理位置选择器
  1033. */
  1034. public function createMenu($data){
  1035. if (!$this->access_token && !$this->checkAuth()) return false;
  1036. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1037. if ($result)
  1038. {
  1039. $json = json_decode($result,true);
  1040. if (!$json || !empty($json['errcode'])) {
  1041. $this->errCode = $json['errcode'];
  1042. $this->errMsg = $json['errmsg'];
  1043. return false;
  1044. }
  1045. return true;
  1046. }
  1047. return false;
  1048. }
  1049. /**
  1050. * 获取菜单(认证后的订阅号可用)
  1051. * @return array('menu'=>array(....s))
  1052. */
  1053. public function getMenu(){
  1054. if (!$this->access_token && !$this->checkAuth()) return false;
  1055. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  1056. if ($result)
  1057. {
  1058. $json = json_decode($result,true);
  1059. if (!$json || isset($json['errcode'])) {
  1060. $this->errCode = $json['errcode'];
  1061. $this->errMsg = $json['errmsg'];
  1062. return false;
  1063. }
  1064. return $json;
  1065. }
  1066. return false;
  1067. }
  1068. /**
  1069. * 删除菜单(认证后的订阅号可用)
  1070. * @return boolean
  1071. */
  1072. public function deleteMenu(){
  1073. if (!$this->access_token && !$this->checkAuth()) return false;
  1074. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  1075. if ($result)
  1076. {
  1077. $json = json_decode($result,true);
  1078. if (!$json || !empty($json['errcode'])) {
  1079. $this->errCode = $json['errcode'];
  1080. $this->errMsg = $json['errmsg'];
  1081. return false;
  1082. }
  1083. return true;
  1084. }
  1085. return false;
  1086. }
  1087. /**
  1088. * 上传多媒体文件(认证后的订阅号可用)
  1089. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1090. * @param array $data {"media":'@Path\filename.jpg'}
  1091. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1092. * @return boolean|array
  1093. */
  1094. public function uploadMedia($data, $type){
  1095. if (!$this->access_token && !$this->checkAuth()) return false;
  1096. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1097. if ($result)
  1098. {
  1099. $json = json_decode($result,true);
  1100. if (!$json || !empty($json['errcode'])) {
  1101. $this->errCode = $json['errcode'];
  1102. $this->errMsg = $json['errmsg'];
  1103. return false;
  1104. }
  1105. return $json;
  1106. }
  1107. return false;
  1108. }
  1109. /**
  1110. * 根据媒体文件ID获取媒体文件(认证后的订阅号可用)
  1111. * @param string $media_id 媒体文件id
  1112. * @return raw data
  1113. */
  1114. public function getMedia($media_id){
  1115. if (!$this->access_token && !$this->checkAuth()) return false;
  1116. $result = $this->http_get(self::UPLOAD_MEDIA_URL.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1117. if ($result)
  1118. {
  1119. $json = json_decode($result,true);
  1120. if (isset($json['errcode'])) {
  1121. $this->errCode = $json['errcode'];
  1122. $this->errMsg = $json['errmsg'];
  1123. return false;
  1124. }
  1125. return $result;
  1126. }
  1127. return false;
  1128. }
  1129. /**
  1130. * 上传图文消息素材(认证后的订阅号可用)
  1131. * @param array $data 消息结构{"articles":[{...}]}
  1132. * @return boolean|array
  1133. */
  1134. public function uploadArticles($data){
  1135. if (!$this->access_token && !$this->checkAuth()) return false;
  1136. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1137. if ($result)
  1138. {
  1139. $json = json_decode($result,true);
  1140. if (!$json || !empty($json['errcode'])) {
  1141. $this->errCode = $json['errcode'];
  1142. $this->errMsg = $json['errmsg'];
  1143. return false;
  1144. }
  1145. return $json;
  1146. }
  1147. return false;
  1148. }
  1149. /**
  1150. * 上传视频素材(认证后的订阅号可用)
  1151. * @param array $data 消息结构
  1152. * {
  1153. * "media_id"=>"", //通过上传媒体接口得到的MediaId
  1154. * "title"=>"TITLE", //视频标题
  1155. * "description"=>"Description" //视频描述
  1156. * }
  1157. * @return boolean|array
  1158. * {
  1159. * "type":"video",
  1160. * "media_id":"mediaid",
  1161. * "created_at":1398848981
  1162. * }
  1163. */
  1164. public function uploadMpVideo($data){
  1165. if (!$this->access_token && !$this->checkAuth()) return false;
  1166. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_VIDEO_UPLOAD.'access_token='.$this->access_token,self::json_encode($data));
  1167. if ($result)
  1168. {
  1169. $json = json_decode($result,true);
  1170. if (!$json || !empty($json['errcode'])) {
  1171. $this->errCode = $json['errcode'];
  1172. $this->errMsg = $json['errmsg'];
  1173. return false;
  1174. }
  1175. return $json;
  1176. }
  1177. return false;
  1178. }
  1179. /**
  1180. * 高级群发消息, 根据OpenID列表群发图文消息(订阅号不可用)
  1181. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1182. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1183. * @param array $data 消息结构
  1184. * {
  1185. * "touser"=>array(
  1186. * "OPENID1",
  1187. * "OPENID2"
  1188. * ),
  1189. * "msgtype"=>"mpvideo",
  1190. * // 在下面5种类型中选择对应的参数内容
  1191. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1192. * // text => array ( "content" => "hello")
  1193. * }
  1194. * @return boolean|array
  1195. */
  1196. public function sendMassMessage($data){
  1197. if (!$this->access_token && !$this->checkAuth()) return false;
  1198. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1199. if ($result)
  1200. {
  1201. $json = json_decode($result,true);
  1202. if (!$json || !empty($json['errcode'])) {
  1203. $this->errCode = $json['errcode'];
  1204. $this->errMsg = $json['errmsg'];
  1205. return false;
  1206. }
  1207. return $json;
  1208. }
  1209. return false;
  1210. }
  1211. /**
  1212. * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用)
  1213. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1214. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1215. * @param array $data 消息结构
  1216. * {
  1217. * "filter"=>array(
  1218. * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id
  1219. * "group_id"=>"2" //群发的分组id
  1220. * ),
  1221. * "msgtype"=>"mpvideo",
  1222. * // 在下面5种类型中选择对应的参数内容
  1223. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1224. * // text => array ( "content" => "hello")
  1225. * }
  1226. * @return boolean|array
  1227. */
  1228. public function sendGroupMassMessage($data){
  1229. if (!$this->access_token && !$this->checkAuth()) return false;
  1230. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1231. if ($result)
  1232. {
  1233. $json = json_decode($result,true);
  1234. if (!$json || !empty($json['errcode'])) {
  1235. $this->errCode = $json['errcode'];
  1236. $this->errMsg = $json['errmsg'];
  1237. return false;
  1238. }
  1239. return $json;
  1240. }
  1241. return false;
  1242. }
  1243. /**
  1244. * 高级群发消息, 删除群发图文消息(认证后的订阅号可用)
  1245. * @param int $msg_id 消息id
  1246. * @return boolean|array
  1247. */
  1248. public function deleteMassMessage($msg_id){
  1249. if (!$this->access_token && !$this->checkAuth()) return false;
  1250. $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)));
  1251. if ($result)
  1252. {
  1253. $json = json_decode($result,true);
  1254. if (!$json || !empty($json['errcode'])) {
  1255. $this->errCode = $json['errcode'];
  1256. $this->errMsg = $json['errmsg'];
  1257. return false;
  1258. }
  1259. return true;
  1260. }
  1261. return false;
  1262. }
  1263. /**
  1264. * 高级群发消息, 预览群发消息(认证后的订阅号可用)
  1265. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1266. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1267. * @param array $data 消息结构
  1268. * {
  1269. * "touser"=>"OPENID",
  1270. * "msgtype"=>"mpvideo",
  1271. * // 在下面5种类型中选择对应的参数内容
  1272. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1273. * // text => array ( "content" => "hello")
  1274. * }
  1275. * @return boolean|array
  1276. */
  1277. public function previewMassMessage($data){
  1278. if (!$this->access_token && !$this->checkAuth()) return false;
  1279. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_PREVIEW_URL.'access_token='.$this->access_token,self::json_encode($data));
  1280. if ($result)
  1281. {
  1282. $json = json_decode($result,true);
  1283. if (!$json || !empty($json['errcode'])) {
  1284. $this->errCode = $json['errcode'];
  1285. $this->errMsg = $json['errmsg'];
  1286. return false;
  1287. }
  1288. return $json;
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用)
  1294. * @param int $msg_id 消息id
  1295. * @return boolean|array
  1296. * {
  1297. * "msg_id":201053012, //群发消息后返回的消息id
  1298. * "msg_status":"SEND_SUCCESS" //消息发送后的状态,SEND_SUCCESS表示发送成功
  1299. * }
  1300. */
  1301. public function queryMassMessage($msg_id){
  1302. if (!$this->access_token && !$this->checkAuth()) return false;
  1303. $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)));
  1304. if ($result)
  1305. {
  1306. $json = json_decode($result,true);
  1307. if (!$json || !empty($json['errcode'])) {
  1308. $this->errCode = $json['errcode'];
  1309. $this->errMsg = $json['errmsg'];
  1310. return false;
  1311. }
  1312. return true;
  1313. }
  1314. return false;
  1315. }
  1316. /**
  1317. * 创建二维码ticket
  1318. * @param int $scene_id 自定义追踪id
  1319. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
  1320. * @param int $expire 临时二维码有效期,最大为1800秒
  1321. * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800,'url'=>'二维码图片解析后的地址')
  1322. */
  1323. public function getQRCode($scene_id,$type=0,$expire=1800){
  1324. if (!$this->access_token && !$this->checkAuth()) return false;
  1325. $data = array(
  1326. 'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
  1327. 'expire_seconds'=>$expire,
  1328. 'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
  1329. );
  1330. if ($type == 1) {
  1331. unset($data['expire_seconds']);
  1332. }
  1333. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1334. if ($result)
  1335. {
  1336. $json = json_decode($result,true);
  1337. if (!$json || !empty($json['errcode'])) {
  1338. $this->errCode = $json['errcode'];
  1339. $this->errMsg = $json['errmsg'];
  1340. return false;
  1341. }
  1342. return $json;
  1343. }
  1344. return false;
  1345. }
  1346. /**
  1347. * 获取二维码图片
  1348. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  1349. * @return string url 返回http地址
  1350. */
  1351. public function getQRUrl($ticket) {
  1352. return self::QRCODE_IMG_URL.$ticket;
  1353. }
  1354. /**
  1355. * 长链接转短链接接口
  1356. * @param string $long_url 传入要转换的长url
  1357. * @return boolean|string url 成功则返回转换后的短url
  1358. */
  1359. public function getShortUrl($long_url){
  1360. if (!$this->access_token && !$this->checkAuth()) return false;
  1361. $data = array(
  1362. 'action'=>'long2short',
  1363. 'long_url'=>$long_url
  1364. );
  1365. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  1366. if ($result)
  1367. {
  1368. $json = json_decode($result,true);
  1369. if (!$json || !empty($json['errcode'])) {
  1370. $this->errCode = $json['errcode'];
  1371. $this->errMsg = $json['errmsg'];
  1372. return false;
  1373. }
  1374. return $json['short_url'];
  1375. }
  1376. return false;
  1377. }
  1378. /**
  1379. * 批量获取关注用户列表
  1380. * @param unknown $next_openid
  1381. */
  1382. public function getUserList($next_openid=''){
  1383. if (!$this->access_token && !$this->checkAuth()) return false;
  1384. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  1385. if ($result)
  1386. {
  1387. $json = json_decode($result,true);
  1388. if (isset($json['errcode'])) {
  1389. $this->errCode = $json['errcode'];
  1390. $this->errMsg = $json['errmsg'];
  1391. return false;
  1392. }
  1393. return $json;
  1394. }
  1395. return false;
  1396. }
  1397. /**
  1398. * 获取关注者详细信息
  1399. * @param string $openid
  1400. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  1401. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1402. */
  1403. public function getUserInfo($openid){
  1404. if (!$this->access_token && !$this->checkAuth()) return false;
  1405. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  1406. if ($result)
  1407. {
  1408. $json = json_decode($result,true);
  1409. if (isset($json['errcode'])) {
  1410. $this->errCode = $json['errcode'];
  1411. $this->errMsg = $json['errmsg'];
  1412. return false;
  1413. }
  1414. return $json;
  1415. }
  1416. return false;
  1417. }
  1418. /**
  1419. * 设置用户备注名
  1420. * @param string $openid
  1421. * @param string $remark 备注名
  1422. * @return boolean|array
  1423. */
  1424. public function updateUserRemark($openid,$remark){
  1425. if (!$this->access_token && !$this->checkAuth()) return false;
  1426. $data = array(
  1427. 'openid'=>$openid,
  1428. 'remark'=>$remark
  1429. );
  1430. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
  1431. if ($result)
  1432. {
  1433. $json = json_decode($result,true);
  1434. if (!$json || !empty($json['errcode'])) {
  1435. $this->errCode = $json['errcode'];
  1436. $this->errMsg = $json['errmsg'];
  1437. return false;
  1438. }
  1439. return $json;
  1440. }
  1441. return false;
  1442. }
  1443. /**
  1444. * 获取用户分组列表
  1445. * @return boolean|array
  1446. */
  1447. public function getGroup(){
  1448. if (!$this->access_token && !$this->checkAuth()) return false;
  1449. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  1450. if ($result)
  1451. {
  1452. $json = json_decode($result,true);
  1453. if (isset($json['errcode'])) {
  1454. $this->errCode = $json['errcode'];
  1455. $this->errMsg = $json['errmsg'];
  1456. return false;
  1457. }
  1458. return $json;
  1459. }
  1460. return false;
  1461. }
  1462. /**
  1463. * 获取用户所在分组
  1464. * @param string $openid
  1465. * @return boolean|int 成功则返回用户分组id
  1466. */
  1467. public function getUserGroup($openid){
  1468. if (!$this->access_token && !$this->checkAuth()) return false;
  1469. $data = array(
  1470. 'openid'=>$openid
  1471. );
  1472. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1473. if ($result)
  1474. {
  1475. $json = json_decode($result,true);
  1476. if (!$json || !empty($json['errcode'])) {
  1477. $this->errCode = $json['errcode'];
  1478. $this->errMsg = $json['errmsg'];
  1479. return false;
  1480. } else
  1481. if (isset($json['groupid'])) return $json['groupid'];
  1482. }
  1483. return false;
  1484. }
  1485. /**
  1486. * 新增自定分组
  1487. * @param string $name 分组名称
  1488. * @return boolean|array
  1489. */
  1490. public function createGroup($name){
  1491. if (!$this->access_token && !$this->checkAuth()) return false;
  1492. $data = array(
  1493. 'group'=>array('name'=>$name)
  1494. );
  1495. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1496. if ($result)
  1497. {
  1498. $json = json_decode($result,true);
  1499. if (!$json || !empty($json['errcode'])) {
  1500. $this->errCode = $json['errcode'];
  1501. $this->errMsg = $json['errmsg'];
  1502. return false;
  1503. }
  1504. return $json;
  1505. }
  1506. return false;
  1507. }
  1508. /**
  1509. * 更改分组名称
  1510. * @param int $groupid 分组id
  1511. * @param string $name 分组名称
  1512. * @return boolean|array
  1513. */
  1514. public function updateGroup($groupid,$name){
  1515. if (!$this->access_token && !$this->checkAuth()) return false;
  1516. $data = array(
  1517. 'group'=>array('id'=>$groupid,'name'=>$name)
  1518. );
  1519. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1520. if ($result)
  1521. {
  1522. $json = json_decode($result,true);
  1523. if (!$json || !empty($json['errcode'])) {
  1524. $this->errCode = $json['errcode'];
  1525. $this->errMsg = $json['errmsg'];
  1526. return false;
  1527. }
  1528. return $json;
  1529. }
  1530. return false;
  1531. }
  1532. /**
  1533. * 移动用户分组
  1534. * @param int $groupid 分组id
  1535. * @param string $openid 用户openid
  1536. * @return boolean|array
  1537. */
  1538. public function updateGroupMembers($groupid,$openid){
  1539. if (!$this->access_token && !$this->checkAuth()) return false;
  1540. $data = array(
  1541. 'openid'=>$openid,
  1542. 'to_groupid'=>$groupid
  1543. );
  1544. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1545. if ($result)
  1546. {
  1547. $json = json_decode($result,true);
  1548. if (!$json || !empty($json['errcode'])) {
  1549. $this->errCode = $json['errcode'];
  1550. $this->errMsg = $json['errmsg'];
  1551. return false;
  1552. }
  1553. return $json;
  1554. }
  1555. return false;
  1556. }
  1557. /**
  1558. * 发送客服消息
  1559. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  1560. * @return boolean|array
  1561. */
  1562. public function sendCustomMessage($data){
  1563. if (!$this->access_token && !$this->checkAuth()) return false;
  1564. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1565. if ($result)
  1566. {
  1567. $json = json_decode($result,true);
  1568. if (!$json || !empty($json['errcode'])) {
  1569. $this->errCode = $json['errcode'];
  1570. $this->errMsg = $json['errmsg'];
  1571. return false;
  1572. }
  1573. return $json;
  1574. }
  1575. return false;
  1576. }
  1577. /**
  1578. * oauth 授权跳转接口
  1579. * @param string $callback 回调URI
  1580. * @return string
  1581. */
  1582. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  1583. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1584. }
  1585. /**
  1586. * 通过code获取Access Token
  1587. * @return array {access_token,expires_in,refresh_token,openid,scope}
  1588. */
  1589. public function getOauthAccessToken(){
  1590. $code = isset($_GET['code'])?$_GET['code']:'';
  1591. if (!$code) return false;
  1592. $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');
  1593. if ($result)
  1594. {
  1595. $json = json_decode($result,true);
  1596. if (!$json || !empty($json['errcode'])) {
  1597. $this->errCode = $json['errcode'];
  1598. $this->errMsg = $json['errmsg'];
  1599. return false;
  1600. }
  1601. $this->user_token = $json['access_token'];
  1602. return $json;
  1603. }
  1604. return false;
  1605. }
  1606. /**
  1607. * 刷新access token并续期
  1608. * @param string $refresh_token
  1609. * @return boolean|mixed
  1610. */
  1611. public function getOauthRefreshToken($refresh_token){
  1612. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  1613. if ($result)
  1614. {
  1615. $json = json_decode($result,true);
  1616. if (!$json || !empty($json['errcode'])) {
  1617. $this->errCode = $json['errcode'];
  1618. $this->errMsg = $json['errmsg'];
  1619. return false;
  1620. }
  1621. $this->user_token = $json['access_token'];
  1622. return $json;
  1623. }
  1624. return false;
  1625. }
  1626. /**
  1627. * 获取授权后的用户资料
  1628. * @param string $access_token
  1629. * @param string $openid
  1630. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  1631. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1632. */
  1633. public function getOauthUserinfo($access_token,$openid){
  1634. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  1635. if ($result)
  1636. {
  1637. $json = json_decode($result,true);
  1638. if (!$json || !empty($json['errcode'])) {
  1639. $this->errCode = $json['errcode'];
  1640. $this->errMsg = $json['errmsg'];
  1641. return false;
  1642. }
  1643. return $json;
  1644. }
  1645. return false;
  1646. }
  1647. /**
  1648. * 检验授权凭证是否有效
  1649. * @param string $access_token
  1650. * @param string $openid
  1651. * @return boolean 是否有效
  1652. */
  1653. public function getOauthAuth($access_token,$openid){
  1654. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  1655. if ($result)
  1656. {
  1657. $json = json_decode($result,true);
  1658. if (!$json || !empty($json['errcode'])) {
  1659. $this->errCode = $json['errcode'];
  1660. $this->errMsg = $json['errmsg'];
  1661. return false;
  1662. } else
  1663. if ($json['errcode']==0) return true;
  1664. }
  1665. return false;
  1666. }
  1667. /**
  1668. * 获取签名
  1669. * @param array $arrdata 签名数组
  1670. * @param string $method 签名方法
  1671. * @return boolean|string 签名值
  1672. */
  1673. public function getSignature($arrdata,$method="sha1") {
  1674. if (!function_exists($method)) return false;
  1675. ksort($arrdata);
  1676. $paramstring = "";
  1677. foreach($arrdata as $key => $value)
  1678. {
  1679. if(strlen($paramstring) == 0)
  1680. $paramstring .= $key . "=" . $value;
  1681. else
  1682. $paramstring .= "&" . $key . "=" . $value;
  1683. }
  1684. $paySign = $method($paramstring);
  1685. return $paySign;
  1686. }
  1687. /**
  1688. * 生成随机字串
  1689. * @param number $length 长度,默认为16,最长为32字节
  1690. * @return string
  1691. */
  1692. public function generateNonceStr($length=16){
  1693. // 密码字符集,可任意添加你需要的字符
  1694. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1695. $str = "";
  1696. for($i = 0; $i < $length; $i++)
  1697. {
  1698. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1699. }
  1700. return $str;
  1701. }
  1702. /**
  1703. * 生成原生支付url
  1704. * @param number $productid 商品编号,最长为32字节
  1705. * @return string
  1706. */
  1707. public function createNativeUrl($productid){
  1708. $nativeObj["appid"] = $this->appid;
  1709. $nativeObj["appkey"] = $this->paysignkey;
  1710. $nativeObj["productid"] = urlencode($productid);
  1711. $nativeObj["timestamp"] = time();
  1712. $nativeObj["noncestr"] = $this->generateNonceStr();
  1713. $nativeObj["sign"] = $this->getSignature($nativeObj);
  1714. unset($nativeObj["appkey"]);
  1715. $bizString = "";
  1716. foreach($nativeObj as $key => $value)
  1717. {
  1718. if(strlen($bizString) == 0)
  1719. $bizString .= $key . "=" . $value;
  1720. else
  1721. $bizString .= "&" . $key . "=" . $value;
  1722. }
  1723. return "weixin://wxpay/bizpayurl?".$bizString;
  1724. //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX
  1725. }
  1726. /**
  1727. * 生成订单package字符串
  1728. * @param string $out_trade_no 必填,商户系统内部的订单号,32个字符内,确保在商户系统唯一
  1729. * @param string $body 必填,商品描述,128 字节以下
  1730. * @param int $total_fee 必填,订单总金额,单位为分
  1731. * @param string $notify_url 必填,支付完成通知回调接口,255 字节以内
  1732. * @param string $spbill_create_ip 必填,用户终端IP,IPV4字串,15字节内
  1733. * @param int $fee_type 必填,现金支付币种,默认1:人民币
  1734. * @param string $bank_type 必填,银行通道类型,默认WX
  1735. * @param string $input_charset 必填,传入参数字符编码,默认UTF-8,取值有UTF-8和GBK
  1736. * @param string $time_start 交易起始时间,订单生成时间,格式yyyyMMddHHmmss
  1737. * @param string $time_expire 交易结束时间,也是订单失效时间
  1738. * @param int $transport_fee 物流费用,单位为分
  1739. * @param int $product_fee 商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee
  1740. * @param string $goods_tag 商品标记,优惠券时可能用到
  1741. * @param string $attach 附加数据,notify接口原样返回
  1742. * @return string
  1743. */
  1744. public function createPackage($out_trade_no,$body,$total_fee,$notify_url,$spbill_create_ip,$fee_type=1,$bank_type="WX",$input_charset="UTF-8",$time_start="",$time_expire="",$transport_fee="",$product_fee="",$goods_tag="",$attach=""){
  1745. $arrdata = array("bank_type" => $bank_type, "body" => $body, "partner" => $this->partnerid, "out_trade_no" => $out_trade_no, "total_fee" => $total_fee, "fee_type" => $fee_type, "notify_url" => $notify_url, "spbill_create_ip" => $spbill_create_ip, "input_charset" => $input_charset);
  1746. if ($time_start) $arrdata['time_start'] = $time_start;
  1747. if ($time_expire) $arrdata['time_expire'] = $time_expire;
  1748. if ($transport_fee) $arrdata['transport_fee'] = $transport_fee;
  1749. if ($product_fee) $arrdata['product_fee'] = $product_fee;
  1750. if ($goods_tag) $arrdata['goods_tag'] = $goods_tag;
  1751. if ($attach) $arrdata['attach'] = $attach;
  1752. ksort($arrdata);
  1753. $paramstring = "";
  1754. foreach($arrdata as $key => $value)
  1755. {
  1756. if(strlen($paramstring) == 0)
  1757. $paramstring .= $key . "=" . $value;
  1758. else
  1759. $paramstring .= "&" . $key . "=" . $value;
  1760. }
  1761. $stringSignTemp = $paramstring . "&key=" . $this->partnerkey;
  1762. $signValue = strtoupper(md5($stringSignTemp));
  1763. $package = http_build_query($arrdata) . "&sign=" . $signValue;
  1764. return $package;
  1765. }
  1766. /**
  1767. * 支付签名(paySign)生成方法
  1768. * @param string $package 订单详情字串
  1769. * @param string $timeStamp 当前时间戳(需与JS输出的一致)
  1770. * @param string $nonceStr 随机串(需与JS输出的一致)
  1771. * @return string 返回签名字串
  1772. */
  1773. public function getPaySign($package, $timeStamp, $nonceStr){
  1774. $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey);
  1775. $paySign = $this->getSignature($arrdata);
  1776. return $paySign;
  1777. }
  1778. /**
  1779. * 回调通知签名验证
  1780. * @param array $orderxml 返回的orderXml的数组表示,留空则自动从post数据获取
  1781. * @return boolean
  1782. */
  1783. public function checkOrderSignature($orderxml=''){
  1784. if (!$orderxml) {
  1785. $postStr = file_get_contents("php://input");
  1786. if (!empty($postStr)) {
  1787. $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  1788. } else return false;
  1789. }
  1790. $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']);
  1791. $paySign = $this->getSignature($arrdata);
  1792. if ($paySign!=$orderxml['AppSignature']) return false;
  1793. return true;
  1794. }
  1795. /**
  1796. * 发货通知
  1797. * @param string $openid 用户open_id
  1798. * @param string $transid 交易单号
  1799. * @param string $out_trade_no 第三方订单号
  1800. * @param int $status 0:发货失败;1:已发货
  1801. * @param string $msg 失败原因
  1802. * @return boolean|array
  1803. */
  1804. public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
  1805. if (!$this->access_token && !$this->checkAuth()) return false;
  1806. $postdata = array(
  1807. "appid"=>$this->appid,
  1808. "appkey"=>$this->paysignkey,
  1809. "openid"=>$openid,
  1810. "transid"=>strval($transid),
  1811. "out_trade_no"=>strval($out_trade_no),
  1812. "deliver_timestamp"=>strval(time()),
  1813. "deliver_status"=>strval($status),
  1814. "deliver_msg"=>$msg,
  1815. );
  1816. $postdata['app_signature'] = $this->getSignature($postdata);
  1817. $postdata['sign_method'] = 'sha1';
  1818. unset($postdata['appkey']);
  1819. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
  1820. if ($result)
  1821. {
  1822. $json = json_decode($result,true);
  1823. if (!$json || !empty($json['errcode'])) {
  1824. $this->errCode = $json['errcode'];
  1825. $this->errMsg = $json['errmsg'];
  1826. return false;
  1827. }
  1828. return $json;
  1829. }
  1830. return false;
  1831. }
  1832. /**
  1833. * 查询订单信息
  1834. * @param string $out_trade_no 订单号
  1835. * @return boolean|array
  1836. */
  1837. public function getPayOrder($out_trade_no) {
  1838. if (!$this->access_token && !$this->checkAuth()) return false;
  1839. $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}"));
  1840. $postdata = array(
  1841. "appid"=>$this->appid,
  1842. "appkey"=>$this->paysignkey,
  1843. "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign",
  1844. "timestamp"=>strval(time()),
  1845. );
  1846. $postdata['app_signature'] = $this->getSignature($postdata);
  1847. $postdata['sign_method'] = 'sha1';
  1848. unset($postdata['appkey']);
  1849. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata));
  1850. if ($result)
  1851. {
  1852. $json = json_decode($result,true);
  1853. if (!$json || !empty($json['errcode'])) {
  1854. $this->errCode = $json['errcode'];
  1855. $this->errMsg = $json['errmsg'].json_encode($postdata);
  1856. return false;
  1857. }
  1858. return $json["order_info"];
  1859. }
  1860. return false;
  1861. }
  1862. /**
  1863. * 获取收货地址JS的签名
  1864. * @tutorial 参考weixin.js脚本的WeixinJS.editAddress方法调用
  1865. * @param string $appId
  1866. * @param string $url
  1867. * @param int $timeStamp
  1868. * @param string $nonceStr
  1869. * @param string $user_token
  1870. * @return Ambigous <boolean, string>
  1871. */
  1872. public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){
  1873. if (!$user_token) $user_token = $this->user_token;
  1874. if (!$user_token) {
  1875. $this->errMsg = 'no user access token found!';
  1876. return false;
  1877. }
  1878. $url = htmlspecialchars_decode($url);
  1879. $arrdata = array(
  1880. 'appid'=>$this->appid,
  1881. 'url'=>$url,
  1882. 'timestamp'=>strval($timeStamp),
  1883. 'noncestr'=>$nonceStr,
  1884. 'accesstoken'=>$user_token
  1885. );
  1886. return $this->getSignature($arrdata);
  1887. }
  1888. /**
  1889. * 发送模板消息
  1890. * @param array $data 消息结构
  1891. * {
  1892. "touser":"OPENID",
  1893. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  1894. "url":"http://weixin.qq.com/download",
  1895. "topcolor":"#FF0000",
  1896. "data":{
  1897. "参数名1": {
  1898. "value":"参数",
  1899. "color":"#173177" //参数颜色
  1900. },
  1901. "Date":{
  1902. "value":"06月07日 19时24分",
  1903. "color":"#173177"
  1904. },
  1905. "CardNumber":{
  1906. "value":"0426",
  1907. "color":"#173177"
  1908. },
  1909. "Type":{
  1910. "value":"消费",
  1911. "color":"#173177"
  1912. }
  1913. }
  1914. }
  1915. * @return boolean|array
  1916. */
  1917. public function sendTemplateMessage($data){
  1918. if (!$this->access_token && !$this->checkAuth()) return false;
  1919. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_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;
  1928. }
  1929. return false;
  1930. }
  1931. /**
  1932. * 获取多客服会话记录
  1933. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  1934. * @return boolean|array
  1935. */
  1936. public function getCustomServiceMessage($data){
  1937. if (!$this->access_token && !$this->checkAuth()) return false;
  1938. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  1939. if ($result)
  1940. {
  1941. $json = json_decode($result,true);
  1942. if (!$json || !empty($json['errcode'])) {
  1943. $this->errCode = $json['errcode'];
  1944. $this->errMsg = $json['errmsg'];
  1945. return false;
  1946. }
  1947. return $json;
  1948. }
  1949. return false;
  1950. }
  1951. /**
  1952. * 转发多客服消息
  1953. * Example: $obj->transfer_customer_service($customer_account)->reply();
  1954. * @param string $customer_account 转发到指定客服帐号:test1@test
  1955. */
  1956. public function transfer_customer_service($customer_account = '')
  1957. {
  1958. $msg = array(
  1959. 'ToUserName' => $this->getRevFrom(),
  1960. 'FromUserName'=>$this->getRevTo(),
  1961. 'CreateTime'=>time(),
  1962. 'MsgType'=>'transfer_customer_service',
  1963. );
  1964. if (!$customer_account) {
  1965. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  1966. }
  1967. $this->Message($msg);
  1968. return $this;
  1969. }
  1970. /**
  1971. * 获取多客服客服基本信息
  1972. *
  1973. * @return boolean|array
  1974. */
  1975. public function getCustomServiceKFlist(){
  1976. if (!$this->access_token && !$this->checkAuth()) return false;
  1977. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  1978. if ($result)
  1979. {
  1980. $json = json_decode($result,true);
  1981. if (!$json || !empty($json['errcode'])) {
  1982. $this->errCode = $json['errcode'];
  1983. $this->errMsg = $json['errmsg'];
  1984. return false;
  1985. }
  1986. return $json;
  1987. }
  1988. return false;
  1989. }
  1990. /**
  1991. * 获取多客服在线客服接待信息
  1992. *
  1993. * @return boolean|array {
  1994. "kf_online_list": [
  1995. {
  1996. "kf_account": "test1@test", //客服账号@微信别名
  1997. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  1998. "kf_id": "1001", //客服工号
  1999. "auto_accept": 0, //客服设置的最大自动接入数
  2000. "accepted_case": 1 //客服当前正在接待的会话数
  2001. }
  2002. ]
  2003. }
  2004. */
  2005. public function getCustomServiceOnlineKFlist(){
  2006. if (!$this->access_token && !$this->checkAuth()) return false;
  2007. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  2008. if ($result)
  2009. {
  2010. $json = json_decode($result,true);
  2011. if (!$json || !empty($json['errcode'])) {
  2012. $this->errCode = $json['errcode'];
  2013. $this->errMsg = $json['errmsg'];
  2014. return false;
  2015. }
  2016. return $json;
  2017. }
  2018. return false;
  2019. }
  2020. /**
  2021. * 添加客服账号
  2022. *
  2023. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2024. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2025. * @param string $password //客服账号明文登录密码,会自动加密
  2026. * @return boolean|array
  2027. * 成功返回结果
  2028. * {
  2029. * "errcode": 0,
  2030. * "errmsg": "ok",
  2031. * }
  2032. */
  2033. public function addKFAccount($account,$nickname,$password){
  2034. $data=array(
  2035. "kf_account" =>$account,
  2036. "nickname" => $nickname,
  2037. "password" => md5($password)
  2038. );
  2039. if (!$this->access_token && !$this->checkAuth()) return false;
  2040. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_ADD_URL.'access_token='.$this->access_token,self::json_encode($data));
  2041. if ($result)
  2042. {
  2043. $json = json_decode($result,true);
  2044. if (!$json || !empty($json['errcode'])) {
  2045. $this->errCode = $json['errcode'];
  2046. $this->errMsg = $json['errmsg'];
  2047. return false;
  2048. }
  2049. return $json;
  2050. }
  2051. return false;
  2052. }
  2053. /**
  2054. * 修改客服账号信息
  2055. *
  2056. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2057. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2058. * @param string $password //客服账号明文登录密码,会自动加密
  2059. * @return boolean|array
  2060. * 成功返回结果
  2061. * {
  2062. * "errcode": 0,
  2063. * "errmsg": "ok",
  2064. * }
  2065. */
  2066. public function updateKFAccount($account,$nickname,$password){
  2067. $data=array(
  2068. "kf_account" =>$account,
  2069. "nickname" => $nickname,
  2070. "password" => md5($password)
  2071. );
  2072. if (!$this->access_token && !$this->checkAuth()) return false;
  2073. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2074. if ($result)
  2075. {
  2076. $json = json_decode($result,true);
  2077. if (!$json || !empty($json['errcode'])) {
  2078. $this->errCode = $json['errcode'];
  2079. $this->errMsg = $json['errmsg'];
  2080. return false;
  2081. }
  2082. return $json;
  2083. }
  2084. return false;
  2085. }
  2086. /**
  2087. * 删除客服账号
  2088. *
  2089. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2090. * @return boolean|array
  2091. * 成功返回结果
  2092. * {
  2093. * "errcode": 0,
  2094. * "errmsg": "ok",
  2095. * }
  2096. */
  2097. public function deleteKFAccount($account){
  2098. if (!$this->access_token && !$this->checkAuth()) return false;
  2099. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_DEL_URL.'access_token='.$this->access_token.'&kf_account='.$account);
  2100. if ($result)
  2101. {
  2102. $json = json_decode($result,true);
  2103. if (!$json || !empty($json['errcode'])) {
  2104. $this->errCode = $json['errcode'];
  2105. $this->errMsg = $json['errmsg'];
  2106. return false;
  2107. }
  2108. return $json;
  2109. }
  2110. return false;
  2111. }
  2112. /**
  2113. * 上传客服头像
  2114. *
  2115. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2116. * @param string $imgfile //头像文件完整路径,如:'D:\user.jpg'。头像文件必须JPG格式,像素建议640*640
  2117. * @return boolean|array
  2118. * 成功返回结果
  2119. * {
  2120. * "errcode": 0,
  2121. * "errmsg": "ok",
  2122. * }
  2123. */
  2124. public function setKFHeadImg($account,$imgfile){
  2125. if (!$this->access_token && !$this->checkAuth()) return false;
  2126. $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);
  2127. if ($result)
  2128. {
  2129. $json = json_decode($result,true);
  2130. if (!$json || !empty($json['errcode'])) {
  2131. $this->errCode = $json['errcode'];
  2132. $this->errMsg = $json['errmsg'];
  2133. return false;
  2134. }
  2135. return $json;
  2136. }
  2137. return false;
  2138. }
  2139. /**
  2140. * 语义理解接口
  2141. * @param String $uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
  2142. * @param String $query 输入文本串
  2143. * @param String $category 需要使用的服务类型,多个用“,”隔开,不能为空
  2144. * @param Float $latitude 纬度坐标,与经度同时传入;与城市二选一传入
  2145. * @param Float $longitude 经度坐标,与纬度同时传入;与城市二选一传入
  2146. * @param String $city 城市名称,与经纬度二选一传入
  2147. * @param String $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入
  2148. * @return boolean|array
  2149. */
  2150. public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
  2151. if (!$this->access_token && !$this->checkAuth()) return false;
  2152. $data=array(
  2153. 'query' => $query,
  2154. 'category' => $category,
  2155. 'appid' => $this->appid,
  2156. 'uid' => ''
  2157. );
  2158. //地理坐标或城市名称二选一
  2159. if ($latitude) {
  2160. $data['latitude'] = $latitude;
  2161. $data['longitude'] = $longitude;
  2162. } elseif ($city) {
  2163. $data['city'] = $city;
  2164. } elseif ($region) {
  2165. $data['region'] = $region;
  2166. }
  2167. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
  2168. if ($result)
  2169. {
  2170. $json = json_decode($result,true);
  2171. if (!$json || !empty($json['errcode'])) {
  2172. $this->errCode = $json['errcode'];
  2173. $this->errMsg = $json['errmsg'];
  2174. return false;
  2175. }
  2176. return $json;
  2177. }
  2178. return false;
  2179. }
  2180. }
  2181. /**
  2182. * PKCS7Encoder class
  2183. *
  2184. * 提供基于PKCS7算法的加解密接口.
  2185. */
  2186. class PKCS7Encoder
  2187. {
  2188. public static $block_size = 32;
  2189. /**
  2190. * 对需要加密的明文进行填充补位
  2191. * @param $text 需要进行填充补位操作的明文
  2192. * @return 补齐明文字符串
  2193. */
  2194. function encode($text)
  2195. {
  2196. $block_size = PKCS7Encoder::$block_size;
  2197. $text_length = strlen($text);
  2198. //计算需要填充的位数
  2199. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  2200. if ($amount_to_pad == 0) {
  2201. $amount_to_pad = PKCS7Encoder::block_size;
  2202. }
  2203. //获得补位所用的字符
  2204. $pad_chr = chr($amount_to_pad);
  2205. $tmp = "";
  2206. for ($index = 0; $index < $amount_to_pad; $index++) {
  2207. $tmp .= $pad_chr;
  2208. }
  2209. return $text . $tmp;
  2210. }
  2211. /**
  2212. * 对解密后的明文进行补位删除
  2213. * @param decrypted 解密后的明文
  2214. * @return 删除填充补位后的明文
  2215. */
  2216. function decode($text)
  2217. {
  2218. $pad = ord(substr($text, -1));
  2219. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  2220. $pad = 0;
  2221. }
  2222. return substr($text, 0, (strlen($text) - $pad));
  2223. }
  2224. }
  2225. /**
  2226. * Prpcrypt class
  2227. *
  2228. * 提供接收和推送给公众平台消息的加解密接口.
  2229. */
  2230. class Prpcrypt
  2231. {
  2232. public $key;
  2233. function Prpcrypt($k)
  2234. {
  2235. $this->key = base64_decode($k . "=");
  2236. }
  2237. /**
  2238. * 对明文进行加密
  2239. * @param string $text 需要加密的明文
  2240. * @return string 加密后的密文
  2241. */
  2242. public function encrypt($text, $appid)
  2243. {
  2244. try {
  2245. //获得16位随机字符串,填充到明文之前
  2246. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  2247. $text = $random . pack("N", strlen($text)) . $text . $appid;
  2248. // 网络字节序
  2249. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  2250. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2251. $iv = substr($this->key, 0, 16);
  2252. //使用自定义的填充方式对明文进行补位填充
  2253. $pkc_encoder = new PKCS7Encoder;
  2254. $text = $pkc_encoder->encode($text);
  2255. mcrypt_generic_init($module, $this->key, $iv);
  2256. //加密
  2257. $encrypted = mcrypt_generic($module, $text);
  2258. mcrypt_generic_deinit($module);
  2259. mcrypt_module_close($module);
  2260. // print(base64_encode($encrypted));
  2261. //使用BASE64对加密后的字符串进行编码
  2262. return array(ErrorCode::$OK, base64_encode($encrypted));
  2263. } catch (Exception $e) {
  2264. //print $e;
  2265. return array(ErrorCode::$EncryptAESError, null);
  2266. }
  2267. }
  2268. /**
  2269. * 对密文进行解密
  2270. * @param string $encrypted 需要解密的密文
  2271. * @return string 解密得到的明文
  2272. */
  2273. public function decrypt($encrypted, $appid)
  2274. {
  2275. try {
  2276. //使用BASE64对需要解密的字符串进行解码
  2277. $ciphertext_dec = base64_decode($encrypted);
  2278. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2279. $iv = substr($this->key, 0, 16);
  2280. mcrypt_generic_init($module, $this->key, $iv);
  2281. //解密
  2282. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  2283. mcrypt_generic_deinit($module);
  2284. mcrypt_module_close($module);
  2285. } catch (Exception $e) {
  2286. return array(ErrorCode::$DecryptAESError, null);
  2287. }
  2288. try {
  2289. //去除补位字符
  2290. $pkc_encoder = new PKCS7Encoder;
  2291. $result = $pkc_encoder->decode($decrypted);
  2292. //去除16位随机字符串,网络字节序和AppId
  2293. if (strlen($result) < 16)
  2294. return "";
  2295. $content = substr($result, 16, strlen($result));
  2296. $len_list = unpack("N", substr($content, 0, 4));
  2297. $xml_len = $len_list[1];
  2298. $xml_content = substr($content, 4, $xml_len);
  2299. $from_appid = substr($content, $xml_len + 4);
  2300. if (!$appid)
  2301. $appid = $from_appid;
  2302. //如果传入的appid是空的,则认为是订阅号,使用数据中提取出来的appid
  2303. } catch (Exception $e) {
  2304. //print $e;
  2305. return array(ErrorCode::$IllegalBuffer, null);
  2306. }
  2307. if ($from_appid != $appid)
  2308. return array(ErrorCode::$ValidateAppidError, null);
  2309. //不注释上边两行,避免传入appid是错误的情况
  2310. return array(0, $xml_content, $from_appid); //增加appid,为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
  2311. }
  2312. /**
  2313. * 随机生成16位字符串
  2314. * @return string 生成的字符串
  2315. */
  2316. function getRandomStr()
  2317. {
  2318. $str = "";
  2319. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  2320. $max = strlen($str_pol) - 1;
  2321. for ($i = 0; $i < 16; $i++) {
  2322. $str .= $str_pol[mt_rand(0, $max)];
  2323. }
  2324. return $str;
  2325. }
  2326. }
  2327. /**
  2328. * error code
  2329. * 仅用作类内部使用,不用于官方API接口的errCode码
  2330. */
  2331. class ErrorCode
  2332. {
  2333. public static $OK = 0;
  2334. public static $ValidateSignatureError = 40001;
  2335. public static $ParseXmlError = 40002;
  2336. public static $ComputeSignatureError = 40003;
  2337. public static $IllegalAesKey = 40004;
  2338. public static $ValidateAppidError = 40005;
  2339. public static $EncryptAESError = 40006;
  2340. public static $DecryptAESError = 40007;
  2341. public static $IllegalBuffer = 40008;
  2342. public static $EncodeBase64Error = 40009;
  2343. public static $DecodeBase64Error = 40010;
  2344. public static $GenReturnXmlError = 40011;
  2345. public static $errCode=array(
  2346. '0' => '处理成功',
  2347. '40001' => '校验签名失败',
  2348. '40002' => '解析xml失败',
  2349. '40003' => '计算签名失败',
  2350. '40004' => '不合法的AESKey',
  2351. '40005' => '校验AppID失败',
  2352. '40006' => 'AES加密失败',
  2353. '40007' => 'AES解密失败',
  2354. '40008' => '公众平台发送的xml不合法',
  2355. '40009' => 'Base64编码失败',
  2356. '40010' => 'Base64解码失败',
  2357. '40011' => '公众帐号生成回包xml失败'
  2358. );
  2359. public static function getErrText($err) {
  2360. if (isset(self::$errCode[$err])) {
  2361. return self::$errCode[$err];
  2362. }else {
  2363. return false;
  2364. };
  2365. }
  2366. }