wechat.class.php 78 KB

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