wechat.class.php 66 KB

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