wechat.class.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  11. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
  12. * 'partnerid'=>'88888888', //财付通商户身份标识
  13. * 'partnerkey'=>'', //财付通商户权限密钥Key
  14. * 'paysignkey'=>'' //商户签名密钥Key
  15. * );
  16. * $weObj = new Wechat($options);
  17. * $weObj->valid();
  18. * $type = $weObj->getRev()->getRevType();
  19. * switch($type) {
  20. * case Wechat::MSGTYPE_TEXT:
  21. * $weObj->text("hello, I'm wechat")->reply();
  22. * exit;
  23. * break;
  24. * case Wechat::MSGTYPE_EVENT:
  25. * ....
  26. * break;
  27. * case Wechat::MSGTYPE_IMAGE:
  28. * ...
  29. * break;
  30. * default:
  31. * $weObj->text("help info")->reply();
  32. * }
  33. *
  34. * //获取菜单操作:
  35. * $menu = $weObj->getMenu();
  36. * //设置菜单
  37. * $newmenu = array(
  38. * "button"=>
  39. * array(
  40. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  41. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  42. * )
  43. * );
  44. * $result = $weObj->createMenu($newmenu);
  45. */
  46. class Wechat
  47. {
  48. const MSGTYPE_TEXT = 'text';
  49. const MSGTYPE_IMAGE = 'image';
  50. const MSGTYPE_LOCATION = 'location';
  51. const MSGTYPE_LINK = 'link';
  52. const MSGTYPE_EVENT = 'event';
  53. const MSGTYPE_MUSIC = 'music';
  54. const MSGTYPE_NEWS = 'news';
  55. const MSGTYPE_VOICE = 'voice';
  56. const MSGTYPE_VIDEO = 'video';
  57. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  58. const AUTH_URL = '/token?grant_type=client_credential&';
  59. const MENU_CREATE_URL = '/menu/create?';
  60. const MENU_GET_URL = '/menu/get?';
  61. const MENU_DELETE_URL = '/menu/delete?';
  62. const MEDIA_GET_URL = '/media/get?';
  63. const QRCODE_CREATE_URL='/qrcode/create?';
  64. const QR_SCENE = 0;
  65. const QR_LIMIT_SCENE = 1;
  66. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  67. const SHORT_URL='/shorturl?';
  68. const USER_GET_URL='/user/get?';
  69. const USER_INFO_URL='/user/info?';
  70. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  71. const GROUP_GET_URL='/groups/get?';
  72. const USER_GROUP_URL='/groups/getid?';
  73. const GROUP_CREATE_URL='/groups/create?';
  74. const GROUP_UPDATE_URL='/groups/update?';
  75. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  76. const CUSTOM_SEND_URL='/message/custom/send?';
  77. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  78. const MASS_SEND_URL = '/message/mass/send?';
  79. const TEMPLATE_SEND_URL = '/message/template/send?';
  80. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  81. const MASS_DELETE_URL = '/message/mass/delete?';
  82. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  83. const MEDIA_UPLOAD = '/media/upload?';
  84. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  85. const OAUTH_AUTHORIZE_URL = '/authorize?';
  86. const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2';
  87. const OAUTH_TOKEN_URL = '/access_token?';
  88. const OAUTH_REFRESH_URL = '/refresh_token?';
  89. const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
  90. const OAUTH_AUTH_URL = 'https://api.weixin.qq.com/sns/auth?';
  91. const PAY_DELIVERNOTIFY = 'https://api.weixin.qq.com/pay/delivernotify?';
  92. const PAY_ORDERQUERY = 'https://api.weixin.qq.com/pay/orderquery?';
  93. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  94. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  95. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getkflist?';
  96. private $token;
  97. private $appid;
  98. private $appsecret;
  99. private $access_token;
  100. private $user_token;
  101. private $partnerid;
  102. private $partnerkey;
  103. private $paysignkey;
  104. private $_msg;
  105. private $_funcflag = false;
  106. private $_receive;
  107. private $_text_filter = true;
  108. public $debug = false;
  109. public $errCode = 40001;
  110. public $errMsg = "no access";
  111. private $_logcallback;
  112. public function __construct($options)
  113. {
  114. $this->token = isset($options['token'])?$options['token']:'';
  115. $this->appid = isset($options['appid'])?$options['appid']:'';
  116. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  117. $this->partnerid = isset($options['partnerid'])?$options['partnerid']:'';
  118. $this->partnerkey = isset($options['partnerkey'])?$options['partnerkey']:'';
  119. $this->paysignkey = isset($options['paysignkey'])?$options['paysignkey']:'';
  120. $this->debug = isset($options['debug'])?$options['debug']:false;
  121. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  122. }
  123. /**
  124. * For weixin server validation
  125. */
  126. private function checkSignature()
  127. {
  128. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  129. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  130. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  131. $token = $this->token;
  132. $tmpArr = array($token, $timestamp, $nonce);
  133. sort($tmpArr, SORT_STRING);
  134. $tmpStr = implode( $tmpArr );
  135. $tmpStr = sha1( $tmpStr );
  136. if( $tmpStr == $signature ){
  137. return true;
  138. }else{
  139. return false;
  140. }
  141. }
  142. /**
  143. * For weixin server validation
  144. * @param bool $return 是否返回
  145. */
  146. public function valid($return=false)
  147. {
  148. $echoStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
  149. if ($return) {
  150. if ($echoStr) {
  151. if ($this->checkSignature())
  152. return $echoStr;
  153. else
  154. return false;
  155. } else
  156. return $this->checkSignature();
  157. } else {
  158. if ($echoStr) {
  159. if ($this->checkSignature())
  160. die($echoStr);
  161. else
  162. die('no access');
  163. } else {
  164. if ($this->checkSignature())
  165. return true;
  166. else
  167. die('no access');
  168. }
  169. }
  170. return false;
  171. }
  172. /**
  173. * 设置发送消息
  174. * @param array $msg 消息数组
  175. * @param bool $append 是否在原消息数组追加
  176. */
  177. public function Message($msg = '',$append = false){
  178. if (is_null($msg)) {
  179. $this->_msg =array();
  180. }elseif (is_array($msg)) {
  181. if ($append)
  182. $this->_msg = array_merge($this->_msg,$msg);
  183. else
  184. $this->_msg = $msg;
  185. return $this->_msg;
  186. } else {
  187. return $this->_msg;
  188. }
  189. }
  190. public function setFuncFlag($flag) {
  191. $this->_funcflag = $flag;
  192. return $this;
  193. }
  194. private function log($log){
  195. if ($this->debug && function_exists($this->_logcallback)) {
  196. if (is_array($log)) $log = print_r($log,true);
  197. return call_user_func($this->_logcallback,$log);
  198. }
  199. }
  200. /**
  201. * 获取微信服务器发来的信息
  202. */
  203. public function getRev()
  204. {
  205. if ($this->_receive) return $this;
  206. $postStr = file_get_contents("php://input");
  207. $this->log($postStr);
  208. if (!empty($postStr)) {
  209. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  210. }
  211. return $this;
  212. }
  213. /**
  214. * 获取微信服务器发来的信息
  215. */
  216. public function getRevData()
  217. {
  218. return $this->_receive;
  219. }
  220. /**
  221. * 获取消息发送者
  222. */
  223. public function getRevFrom() {
  224. if (isset($this->_receive['FromUserName']))
  225. return $this->_receive['FromUserName'];
  226. else
  227. return false;
  228. }
  229. /**
  230. * 获取消息接受者
  231. */
  232. public function getRevTo() {
  233. if (isset($this->_receive['ToUserName']))
  234. return $this->_receive['ToUserName'];
  235. else
  236. return false;
  237. }
  238. /**
  239. * 获取接收消息的类型
  240. */
  241. public function getRevType() {
  242. if (isset($this->_receive['MsgType']))
  243. return $this->_receive['MsgType'];
  244. else
  245. return false;
  246. }
  247. /**
  248. * 获取消息ID
  249. */
  250. public function getRevID() {
  251. if (isset($this->_receive['MsgId']))
  252. return $this->_receive['MsgId'];
  253. else
  254. return false;
  255. }
  256. /**
  257. * 获取消息发送时间
  258. */
  259. public function getRevCtime() {
  260. if (isset($this->_receive['CreateTime']))
  261. return $this->_receive['CreateTime'];
  262. else
  263. return false;
  264. }
  265. /**
  266. * 获取接收消息内容正文
  267. */
  268. public function getRevContent(){
  269. if (isset($this->_receive['Content']))
  270. return $this->_receive['Content'];
  271. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  272. return $this->_receive['Recognition'];
  273. else
  274. return false;
  275. }
  276. /**
  277. * 获取接收消息图片
  278. */
  279. public function getRevPic(){
  280. if (isset($this->_receive['PicUrl']))
  281. return $this->_receive['PicUrl'];
  282. else
  283. return false;
  284. }
  285. /**
  286. * 获取接收消息链接
  287. */
  288. public function getRevLink(){
  289. if (isset($this->_receive['Url'])){
  290. return array(
  291. 'url'=>$this->_receive['Url'],
  292. 'title'=>$this->_receive['Title'],
  293. 'description'=>$this->_receive['Description']
  294. );
  295. } else
  296. return false;
  297. }
  298. /**
  299. * 获取接收地理位置
  300. */
  301. public function getRevGeo(){
  302. if (isset($this->_receive['Location_X'])){
  303. return array(
  304. 'x'=>$this->_receive['Location_X'],
  305. 'y'=>$this->_receive['Location_Y'],
  306. 'scale'=>$this->_receive['Scale'],
  307. 'label'=>$this->_receive['Label']
  308. );
  309. } else
  310. return false;
  311. }
  312. /**
  313. * 获取上报地理位置事件
  314. */
  315. public function getRevEventGeo(){
  316. if (isset($this->_receive['Latitude'])){
  317. return array(
  318. 'x'=>$this->_receive['Latitude'],
  319. 'y'=>$this->_receive['Longitude'],
  320. 'precision'=>$this->_receive['Precision'],
  321. );
  322. } else
  323. return false;
  324. }
  325. /**
  326. * 获取接收事件推送
  327. */
  328. public function getRevEvent(){
  329. if (isset($this->_receive['Event'])){
  330. $array['event'] = $this->_receive['Event'];
  331. }
  332. if (isset($this->_receive['EventKey'])){
  333. $array['key'] = $this->_receive['EventKey'];
  334. }
  335. if (isset($array) && count($array) > 0) {
  336. return $array;
  337. } else {
  338. return false;
  339. }
  340. }
  341. /**
  342. * 获取接收语音推送
  343. */
  344. public function getRevVoice(){
  345. if (isset($this->_receive['MediaId'])){
  346. return array(
  347. 'mediaid'=>$this->_receive['MediaId'],
  348. 'format'=>$this->_receive['Format'],
  349. );
  350. } else
  351. return false;
  352. }
  353. /**
  354. * 获取接收视频推送
  355. */
  356. public function getRevVideo(){
  357. if (isset($this->_receive['MediaId'])){
  358. return array(
  359. 'mediaid'=>$this->_receive['MediaId'],
  360. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  361. );
  362. } else
  363. return false;
  364. }
  365. /**
  366. * 获取接收TICKET
  367. */
  368. public function getRevTicket(){
  369. if (isset($this->_receive['Ticket'])){
  370. return $this->_receive['Ticket'];
  371. } else
  372. return false;
  373. }
  374. /**
  375. * 获取二维码的场景值
  376. */
  377. public function getRevSceneId (){
  378. if (isset($this->_receive['EventKey'])){
  379. return str_replace('qrscene_','',$this->_receive['EventKey']);
  380. } else{
  381. return false;
  382. }
  383. }
  384. /**
  385. * 获取模板消息ID
  386. * 经过验证,这个和普通的消息MsgId不一样
  387. */
  388. public function getRevTplMsgID(){
  389. if (isset($this->_receive['MsgID'])){
  390. return $this->_receive['MsgID'];
  391. } else
  392. return false;
  393. }
  394. /**
  395. * 获取模板消息发送状态
  396. */
  397. public function getRevStatus(){
  398. if (isset($this->_receive['Status'])){
  399. return $this->_receive['Status'];
  400. } else
  401. return false;
  402. }
  403. public static function xmlSafeStr($str)
  404. {
  405. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  406. }
  407. /**
  408. * 数据XML编码
  409. * @param mixed $data 数据
  410. * @return string
  411. */
  412. public static function data_to_xml($data) {
  413. $xml = '';
  414. foreach ($data as $key => $val) {
  415. is_numeric($key) && $key = "item id=\"$key\"";
  416. $xml .= "<$key>";
  417. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  418. list($key, ) = explode(' ', $key);
  419. $xml .= "</$key>";
  420. }
  421. return $xml;
  422. }
  423. /**
  424. * XML编码
  425. * @param mixed $data 数据
  426. * @param string $root 根节点名
  427. * @param string $item 数字索引的子节点名
  428. * @param string $attr 根节点属性
  429. * @param string $id 数字索引子节点key转换的属性名
  430. * @param string $encoding 数据编码
  431. * @return string
  432. */
  433. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  434. if(is_array($attr)){
  435. $_attr = array();
  436. foreach ($attr as $key => $value) {
  437. $_attr[] = "{$key}=\"{$value}\"";
  438. }
  439. $attr = implode(' ', $_attr);
  440. }
  441. $attr = trim($attr);
  442. $attr = empty($attr) ? '' : " {$attr}";
  443. $xml = "<{$root}{$attr}>";
  444. $xml .= self::data_to_xml($data, $item, $id);
  445. $xml .= "</{$root}>";
  446. return $xml;
  447. }
  448. /**
  449. * 过滤文字回复\r\n换行符
  450. * @param string $text
  451. * @return string|mixed
  452. */
  453. private function _auto_text_filter($text) {
  454. if (!$this->_text_filter) return $text;
  455. return str_replace("\r\n", "\n", $text);
  456. }
  457. /**
  458. * 设置回复消息
  459. * Examle: $obj->text('hello')->reply();
  460. * @param string $text
  461. */
  462. public function text($text='')
  463. {
  464. $FuncFlag = $this->_funcflag ? 1 : 0;
  465. $msg = array(
  466. 'ToUserName' => $this->getRevFrom(),
  467. 'FromUserName'=>$this->getRevTo(),
  468. 'MsgType'=>self::MSGTYPE_TEXT,
  469. 'Content'=>$this->_auto_text_filter($text),
  470. 'CreateTime'=>time(),
  471. 'FuncFlag'=>$FuncFlag
  472. );
  473. $this->Message($msg);
  474. return $this;
  475. }
  476. /**
  477. * 设置回复音乐
  478. * @param string $title
  479. * @param string $desc
  480. * @param string $musicurl
  481. * @param string $hgmusicurl
  482. */
  483. public function music($title,$desc,$musicurl,$hgmusicurl='') {
  484. $FuncFlag = $this->_funcflag ? 1 : 0;
  485. $msg = array(
  486. 'ToUserName' => $this->getRevFrom(),
  487. 'FromUserName'=>$this->getRevTo(),
  488. 'CreateTime'=>time(),
  489. 'MsgType'=>self::MSGTYPE_MUSIC,
  490. 'Music'=>array(
  491. 'Title'=>$title,
  492. 'Description'=>$desc,
  493. 'MusicUrl'=>$musicurl,
  494. 'HQMusicUrl'=>$hgmusicurl
  495. ),
  496. 'FuncFlag'=>$FuncFlag
  497. );
  498. $this->Message($msg);
  499. return $this;
  500. }
  501. /**
  502. * 设置回复图文
  503. * @param array $newsData
  504. * 数组结构:
  505. * array(
  506. * "0"=>array(
  507. * 'Title'=>'msg title',
  508. * 'Description'=>'summary text',
  509. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  510. * 'Url'=>'http://www.domain.com/1.html'
  511. * ),
  512. * "1"=>....
  513. * )
  514. */
  515. public function news($newsData=array())
  516. {
  517. $FuncFlag = $this->_funcflag ? 1 : 0;
  518. $count = count($newsData);
  519. $msg = array(
  520. 'ToUserName' => $this->getRevFrom(),
  521. 'FromUserName'=>$this->getRevTo(),
  522. 'MsgType'=>self::MSGTYPE_NEWS,
  523. 'CreateTime'=>time(),
  524. 'ArticleCount'=>$count,
  525. 'Articles'=>$newsData,
  526. 'FuncFlag'=>$FuncFlag
  527. );
  528. $this->Message($msg);
  529. return $this;
  530. }
  531. /**
  532. *
  533. * 回复微信服务器, 此函数支持链式操作
  534. * Example: $this->text('msg tips')->reply();
  535. * @param string $msg 要发送的信息, 默认取$this->_msg
  536. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  537. */
  538. public function reply($msg=array(),$return = false)
  539. {
  540. if (empty($msg))
  541. $msg = $this->_msg;
  542. $xmldata= $this->xml_encode($msg);
  543. $this->log($xmldata);
  544. if ($return)
  545. return $xmldata;
  546. else
  547. echo $xmldata;
  548. }
  549. /**
  550. * GET 请求
  551. * @param string $url
  552. */
  553. private function http_get($url){
  554. $oCurl = curl_init();
  555. if(stripos($url,"https://")!==FALSE){
  556. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  557. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  558. }
  559. curl_setopt($oCurl, CURLOPT_URL, $url);
  560. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  561. $sContent = curl_exec($oCurl);
  562. $aStatus = curl_getinfo($oCurl);
  563. curl_close($oCurl);
  564. if(intval($aStatus["http_code"])==200){
  565. return $sContent;
  566. }else{
  567. return false;
  568. }
  569. }
  570. /**
  571. * POST 请求
  572. * @param string $url
  573. * @param array $param
  574. * @return string content
  575. */
  576. private function http_post($url,$param){
  577. $oCurl = curl_init();
  578. if(stripos($url,"https://")!==FALSE){
  579. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  580. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  581. }
  582. if (is_string($param)) {
  583. $strPOST = $param;
  584. } else {
  585. $aPOST = array();
  586. foreach($param as $key=>$val){
  587. $aPOST[] = $key."=".urlencode($val);
  588. }
  589. $strPOST = join("&", $aPOST);
  590. }
  591. curl_setopt($oCurl, CURLOPT_URL, $url);
  592. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  593. curl_setopt($oCurl, CURLOPT_POST,true);
  594. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  595. $sContent = curl_exec($oCurl);
  596. $aStatus = curl_getinfo($oCurl);
  597. curl_close($oCurl);
  598. if(intval($aStatus["http_code"])==200){
  599. return $sContent;
  600. }else{
  601. return false;
  602. }
  603. }
  604. /**
  605. * 通用auth验证方法,暂时仅用于菜单更新操作
  606. * @param string $appid
  607. * @param string $appsecret
  608. */
  609. public function checkAuth($appid='',$appsecret=''){
  610. if (!$appid || !$appsecret) {
  611. $appid = $this->appid;
  612. $appsecret = $this->appsecret;
  613. }
  614. //TODO: get the cache access_token
  615. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  616. if ($result)
  617. {
  618. $json = json_decode($result,true);
  619. if (!$json || isset($json['errcode'])) {
  620. $this->errCode = $json['errcode'];
  621. $this->errMsg = $json['errmsg'];
  622. return false;
  623. }
  624. $this->access_token = $json['access_token'];
  625. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  626. //TODO: cache access_token
  627. return $this->access_token;
  628. }
  629. return false;
  630. }
  631. /**
  632. * 删除验证数据
  633. * @param string $appid
  634. */
  635. public function resetAuth($appid=''){
  636. if (!$appid) $appid = $this->appid;
  637. $this->access_token = '';
  638. //TODO: remove cache
  639. return true;
  640. }
  641. /**
  642. * 微信api不支持中文转义的json结构
  643. * @param array $arr
  644. */
  645. static function json_encode($arr) {
  646. $parts = array ();
  647. $is_list = false;
  648. //Find out if the given array is a numerical array
  649. $keys = array_keys ( $arr );
  650. $max_length = count ( $arr ) - 1;
  651. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  652. $is_list = true;
  653. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  654. if ($i != $keys [$i]) { //A key fails at position check.
  655. $is_list = false; //It is an associative array.
  656. break;
  657. }
  658. }
  659. }
  660. foreach ( $arr as $key => $value ) {
  661. if (is_array ( $value )) { //Custom handling for arrays
  662. if ($is_list)
  663. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  664. else
  665. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  666. } else {
  667. $str = '';
  668. if (! $is_list)
  669. $str = '"' . $key . '":';
  670. //Custom handling for multiple data types
  671. if (is_numeric ( $value ) && $value<2000000000)
  672. $str .= $value; //Numbers
  673. elseif ($value === false)
  674. $str .= 'false'; //The booleans
  675. elseif ($value === true)
  676. $str .= 'true';
  677. else
  678. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  679. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  680. $parts [] = $str;
  681. }
  682. }
  683. $json = implode ( ',', $parts );
  684. if ($is_list)
  685. return '[' . $json . ']'; //Return numerical JSON
  686. return '{' . $json . '}'; //Return associative JSON
  687. }
  688. /**
  689. * 创建菜单
  690. * @param array $data 菜单数组数据
  691. * example:
  692. {
  693. "button":[
  694. {
  695. "type":"click",
  696. "name":"今日歌曲",
  697. "key":"MENU_KEY_MUSIC"
  698. },
  699. {
  700. "type":"view",
  701. "name":"歌手简介",
  702. "url":"http://www.qq.com/"
  703. },
  704. {
  705. "name":"菜单",
  706. "sub_button":[
  707. {
  708. "type":"click",
  709. "name":"hello word",
  710. "key":"MENU_KEY_MENU"
  711. },
  712. {
  713. "type":"click",
  714. "name":"赞一下我们",
  715. "key":"MENU_KEY_GOOD"
  716. }]
  717. }]
  718. }
  719. */
  720. public function createMenu($data){
  721. if (!$this->access_token && !$this->checkAuth()) return false;
  722. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  723. if ($result)
  724. {
  725. $json = json_decode($result,true);
  726. if (!$json || !empty($json['errcode'])) {
  727. $this->errCode = $json['errcode'];
  728. $this->errMsg = $json['errmsg'];
  729. return false;
  730. }
  731. return true;
  732. }
  733. return false;
  734. }
  735. /**
  736. * 获取菜单
  737. * @return array('menu'=>array(....s))
  738. */
  739. public function getMenu(){
  740. if (!$this->access_token && !$this->checkAuth()) return false;
  741. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  742. if ($result)
  743. {
  744. $json = json_decode($result,true);
  745. if (!$json || isset($json['errcode'])) {
  746. $this->errCode = $json['errcode'];
  747. $this->errMsg = $json['errmsg'];
  748. return false;
  749. }
  750. return $json;
  751. }
  752. return false;
  753. }
  754. /**
  755. * 删除菜单
  756. * @return boolean
  757. */
  758. public function deleteMenu(){
  759. if (!$this->access_token && !$this->checkAuth()) return false;
  760. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  761. if ($result)
  762. {
  763. $json = json_decode($result,true);
  764. if (!$json || !empty($json['errcode'])) {
  765. $this->errCode = $json['errcode'];
  766. $this->errMsg = $json['errmsg'];
  767. return false;
  768. }
  769. return true;
  770. }
  771. return false;
  772. }
  773. /**
  774. * 上传多媒体文件
  775. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  776. * @param array $data {"media":'@Path\filename.jpg'}
  777. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  778. * @return boolean|array
  779. */
  780. public function uploadMedia($data, $type){
  781. if (!$this->access_token && !$this->checkAuth()) return false;
  782. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data);
  783. if ($result)
  784. {
  785. $json = json_decode($result,true);
  786. if (!$json || !empty($json['errcode'])) {
  787. $this->errCode = $json['errcode'];
  788. $this->errMsg = $json['errmsg'];
  789. return false;
  790. }
  791. return $json;
  792. }
  793. return false;
  794. }
  795. /**
  796. * 根据媒体文件ID获取媒体文件
  797. * @param string $media_id 媒体文件id
  798. * @return raw data
  799. */
  800. public function getMedia($media_id){
  801. if (!$this->access_token && !$this->checkAuth()) return false;
  802. $result = $this->http_get(self::UPLOAD_MEDIA_URL.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  803. if ($result)
  804. {
  805. $json = json_decode($result,true);
  806. if (isset($json['errcode'])) {
  807. $this->errCode = $json['errcode'];
  808. $this->errMsg = $json['errmsg'];
  809. return false;
  810. }
  811. return $json;
  812. }
  813. return false;
  814. }
  815. /**
  816. * 上传图文消息素材
  817. * @param array $data 消息结构{"articles":[{...}]}
  818. * @return boolean|array
  819. */
  820. public function uploadArticles($data){
  821. if (!$this->access_token && !$this->checkAuth()) return false;
  822. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  823. if ($result)
  824. {
  825. $json = json_decode($result,true);
  826. if (!$json || !empty($json['errcode'])) {
  827. $this->errCode = $json['errcode'];
  828. $this->errMsg = $json['errmsg'];
  829. return false;
  830. }
  831. return $json;
  832. }
  833. return false;
  834. }
  835. /**
  836. * 高级群发消息, 根据OpenID列表群发图文消息
  837. * @param array $data 消息结构{ "touser":[ "OPENID1", "OPENID2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  838. * @return boolean|array
  839. */
  840. public function sendMassMessage($data){
  841. if (!$this->access_token && !$this->checkAuth()) return false;
  842. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  843. if ($result)
  844. {
  845. $json = json_decode($result,true);
  846. if (!$json || !empty($json['errcode'])) {
  847. $this->errCode = $json['errcode'];
  848. $this->errMsg = $json['errmsg'];
  849. return false;
  850. }
  851. return $json;
  852. }
  853. return false;
  854. }
  855. /**
  856. * 高级群发消息, 根据群组id群发图文消息
  857. * @param array $data 消息结构{ "filter":[ "group_id": "2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  858. * @return boolean|array
  859. */
  860. public function sendGroupMassMessage($data){
  861. if (!$this->access_token && !$this->checkAuth()) return false;
  862. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  863. if ($result)
  864. {
  865. $json = json_decode($result,true);
  866. if (!$json || !empty($json['errcode'])) {
  867. $this->errCode = $json['errcode'];
  868. $this->errMsg = $json['errmsg'];
  869. return false;
  870. }
  871. return $json;
  872. }
  873. return false;
  874. }
  875. /**
  876. * 高级群发消息, 删除群发图文消息
  877. * @param int $msg_id 消息id
  878. * @return boolean|array
  879. */
  880. public function deleteMassMessage($msg_id){
  881. if (!$this->access_token && !$this->checkAuth()) return false;
  882. $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)));
  883. if ($result)
  884. {
  885. $json = json_decode($result,true);
  886. if (!$json || !empty($json['errcode'])) {
  887. $this->errCode = $json['errcode'];
  888. $this->errMsg = $json['errmsg'];
  889. return false;
  890. }
  891. return true;
  892. }
  893. return false;
  894. }
  895. /**
  896. * 创建二维码ticket
  897. * @param int $scene_id 自定义追踪id
  898. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
  899. * @param int $expire 临时二维码有效期,最大为1800秒
  900. * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800,'url'=>'二维码图片解析后的地址')
  901. */
  902. public function getQRCode($scene_id,$type=0,$expire=1800){
  903. if (!$this->access_token && !$this->checkAuth()) return false;
  904. $data = array(
  905. 'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
  906. 'expire_seconds'=>$expire,
  907. 'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
  908. );
  909. if ($type == 1) {
  910. unset($data['expire_seconds']);
  911. }
  912. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  913. if ($result)
  914. {
  915. $json = json_decode($result,true);
  916. if (!$json || !empty($json['errcode'])) {
  917. $this->errCode = $json['errcode'];
  918. $this->errMsg = $json['errmsg'];
  919. return false;
  920. }
  921. return $json;
  922. }
  923. return false;
  924. }
  925. /**
  926. * 获取二维码图片
  927. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  928. * @return string url 返回http地址
  929. */
  930. public function getQRUrl($ticket) {
  931. return self::QRCODE_IMG_URL.$ticket;
  932. }
  933. /**
  934. * 长链接转短链接接口
  935. * @param string $long_url 传入要转换的长url
  936. * @return boolean|string url 成功则返回转换后的短url
  937. */
  938. public function getShortUrl($long_url){
  939. if (!$this->access_token && !$this->checkAuth()) return false;
  940. $data = array(
  941. 'action'=>'long2short',
  942. 'long_url'=>$long_url
  943. );
  944. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  945. if ($result)
  946. {
  947. $json = json_decode($result,true);
  948. if (!$json || !empty($json['errcode'])) {
  949. $this->errCode = $json['errcode'];
  950. $this->errMsg = $json['errmsg'];
  951. return false;
  952. }
  953. return $json['short_url'];
  954. }
  955. return false;
  956. }
  957. /**
  958. * 批量获取关注用户列表
  959. * @param unknown $next_openid
  960. */
  961. public function getUserList($next_openid=''){
  962. if (!$this->access_token && !$this->checkAuth()) return false;
  963. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  964. if ($result)
  965. {
  966. $json = json_decode($result,true);
  967. if (isset($json['errcode'])) {
  968. $this->errCode = $json['errcode'];
  969. $this->errMsg = $json['errmsg'];
  970. return false;
  971. }
  972. return $json;
  973. }
  974. return false;
  975. }
  976. /**
  977. * 获取关注者详细信息
  978. * @param string $openid
  979. * @return array
  980. */
  981. public function getUserInfo($openid){
  982. if (!$this->access_token && !$this->checkAuth()) return false;
  983. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  984. if ($result)
  985. {
  986. $json = json_decode($result,true);
  987. if (isset($json['errcode'])) {
  988. $this->errCode = $json['errcode'];
  989. $this->errMsg = $json['errmsg'];
  990. return false;
  991. }
  992. return $json;
  993. }
  994. return false;
  995. }
  996. /**
  997. * 设置用户备注名
  998. * @param string $openid
  999. * @param string $remark 备注名
  1000. * @return boolean|array
  1001. */
  1002. public function updateUserRemark($openid,$remark){
  1003. if (!$this->access_token && !$this->checkAuth()) return false;
  1004. $data = array(
  1005. 'openid'=>$openid,
  1006. 'remark'=>$remark
  1007. );
  1008. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,$data);
  1009. if ($result)
  1010. {
  1011. $json = json_decode($result,true);
  1012. if (!$json || !empty($json['errcode'])) {
  1013. $this->errCode = $json['errcode'];
  1014. $this->errMsg = $json['errmsg'];
  1015. return false;
  1016. }
  1017. return $json;
  1018. }
  1019. return false;
  1020. }
  1021. /**
  1022. * 获取用户分组列表
  1023. * @return boolean|array
  1024. */
  1025. public function getGroup(){
  1026. if (!$this->access_token && !$this->checkAuth()) return false;
  1027. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  1028. if ($result)
  1029. {
  1030. $json = json_decode($result,true);
  1031. if (isset($json['errcode'])) {
  1032. $this->errCode = $json['errcode'];
  1033. $this->errMsg = $json['errmsg'];
  1034. return false;
  1035. }
  1036. return $json;
  1037. }
  1038. return false;
  1039. }
  1040. /**
  1041. * 获取用户所在分组
  1042. * @param string $openid
  1043. * @return boolean|int 成功则返回用户分组id
  1044. */
  1045. public function getUserGroup($openid){
  1046. if (!$this->access_token && !$this->checkAuth()) return false;
  1047. $data = array(
  1048. 'openid'=>$openid
  1049. );
  1050. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1051. if ($result)
  1052. {
  1053. $json = json_decode($result,true);
  1054. if (!$json || !empty($json['errcode'])) {
  1055. $this->errCode = $json['errcode'];
  1056. $this->errMsg = $json['errmsg'];
  1057. return false;
  1058. } else
  1059. if (isset($json['groupid'])) return $json['groupid'];
  1060. }
  1061. return false;
  1062. }
  1063. /**
  1064. * 新增自定分组
  1065. * @param string $name 分组名称
  1066. * @return boolean|array
  1067. */
  1068. public function createGroup($name){
  1069. if (!$this->access_token && !$this->checkAuth()) return false;
  1070. $data = array(
  1071. 'group'=>array('name'=>$name)
  1072. );
  1073. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1074. if ($result)
  1075. {
  1076. $json = json_decode($result,true);
  1077. if (!$json || !empty($json['errcode'])) {
  1078. $this->errCode = $json['errcode'];
  1079. $this->errMsg = $json['errmsg'];
  1080. return false;
  1081. }
  1082. return $json;
  1083. }
  1084. return false;
  1085. }
  1086. /**
  1087. * 更改分组名称
  1088. * @param int $groupid 分组id
  1089. * @param string $name 分组名称
  1090. * @return boolean|array
  1091. */
  1092. public function updateGroup($groupid,$name){
  1093. if (!$this->access_token && !$this->checkAuth()) return false;
  1094. $data = array(
  1095. 'group'=>array('id'=>$groupid,'name'=>$name)
  1096. );
  1097. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1098. if ($result)
  1099. {
  1100. $json = json_decode($result,true);
  1101. if (!$json || !empty($json['errcode'])) {
  1102. $this->errCode = $json['errcode'];
  1103. $this->errMsg = $json['errmsg'];
  1104. return false;
  1105. }
  1106. return $json;
  1107. }
  1108. return false;
  1109. }
  1110. /**
  1111. * 移动用户分组
  1112. * @param int $groupid 分组id
  1113. * @param string $openid 用户openid
  1114. * @return boolean|array
  1115. */
  1116. public function updateGroupMembers($groupid,$openid){
  1117. if (!$this->access_token && !$this->checkAuth()) return false;
  1118. $data = array(
  1119. 'openid'=>$openid,
  1120. 'to_groupid'=>$groupid
  1121. );
  1122. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1123. if ($result)
  1124. {
  1125. $json = json_decode($result,true);
  1126. if (!$json || !empty($json['errcode'])) {
  1127. $this->errCode = $json['errcode'];
  1128. $this->errMsg = $json['errmsg'];
  1129. return false;
  1130. }
  1131. return $json;
  1132. }
  1133. return false;
  1134. }
  1135. /**
  1136. * 发送客服消息
  1137. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  1138. * @return boolean|array
  1139. */
  1140. public function sendCustomMessage($data){
  1141. if (!$this->access_token && !$this->checkAuth()) return false;
  1142. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1143. if ($result)
  1144. {
  1145. $json = json_decode($result,true);
  1146. if (!$json || !empty($json['errcode'])) {
  1147. $this->errCode = $json['errcode'];
  1148. $this->errMsg = $json['errmsg'];
  1149. return false;
  1150. }
  1151. return $json;
  1152. }
  1153. return false;
  1154. }
  1155. /**
  1156. * oauth 授权跳转接口
  1157. * @param string $callback 回调URI
  1158. * @return string
  1159. */
  1160. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  1161. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1162. }
  1163. /**
  1164. * 通过code获取Access Token
  1165. * @return array {access_token,expires_in,refresh_token,openid,scope}
  1166. */
  1167. public function getOauthAccessToken(){
  1168. $code = isset($_GET['code'])?$_GET['code']:'';
  1169. if (!$code) return false;
  1170. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  1171. if ($result)
  1172. {
  1173. $json = json_decode($result,true);
  1174. if (!$json || !empty($json['errcode'])) {
  1175. $this->errCode = $json['errcode'];
  1176. $this->errMsg = $json['errmsg'];
  1177. return false;
  1178. }
  1179. $this->user_token = $json['access_token'];
  1180. return $json;
  1181. }
  1182. return false;
  1183. }
  1184. /**
  1185. * 刷新access token并续期
  1186. * @param string $refresh_token
  1187. * @return boolean|mixed
  1188. */
  1189. public function getOauthRefreshToken($refresh_token){
  1190. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  1191. if ($result)
  1192. {
  1193. $json = json_decode($result,true);
  1194. if (!$json || !empty($json['errcode'])) {
  1195. $this->errCode = $json['errcode'];
  1196. $this->errMsg = $json['errmsg'];
  1197. return false;
  1198. }
  1199. $this->user_token = $json['access_token'];
  1200. return $json;
  1201. }
  1202. return false;
  1203. }
  1204. /**
  1205. * 获取授权后的用户资料
  1206. * @param string $access_token
  1207. * @param string $openid
  1208. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege}
  1209. */
  1210. public function getOauthUserinfo($access_token,$openid){
  1211. $result = $this->http_get(self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  1212. if ($result)
  1213. {
  1214. $json = json_decode($result,true);
  1215. if (!$json || !empty($json['errcode'])) {
  1216. $this->errCode = $json['errcode'];
  1217. $this->errMsg = $json['errmsg'];
  1218. return false;
  1219. }
  1220. return $json;
  1221. }
  1222. return false;
  1223. }
  1224. /**
  1225. * 检验授权凭证是否有效
  1226. * @param string $access_token
  1227. * @param string $openid
  1228. * @return boolean 是否有效
  1229. */
  1230. public function getOauthAuth($access_token,$openid){
  1231. $result = $this->http_get(self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  1232. if ($result)
  1233. {
  1234. $json = json_decode($result,true);
  1235. if (!$json || !empty($json['errcode'])) {
  1236. $this->errCode = $json['errcode'];
  1237. $this->errMsg = $json['errmsg'];
  1238. return false;
  1239. } else
  1240. if ($json['errcode']==0) return true;
  1241. }
  1242. return false;
  1243. }
  1244. /**
  1245. * 获取签名
  1246. * @param array $arrdata 签名数组
  1247. * @param string $method 签名方法
  1248. * @return boolean|string 签名值
  1249. */
  1250. public function getSignature($arrdata,$method="sha1") {
  1251. if (!function_exists($method)) return false;
  1252. ksort($arrdata);
  1253. $paramstring = "";
  1254. foreach($arrdata as $key => $value)
  1255. {
  1256. if(strlen($paramstring) == 0)
  1257. $paramstring .= $key . "=" . $value;
  1258. else
  1259. $paramstring .= "&" . $key . "=" . $value;
  1260. }
  1261. $paySign = $method($paramstring);
  1262. return $paySign;
  1263. }
  1264. /**
  1265. * 生成随机字串
  1266. * @param number $length 长度,默认为16,最长为32字节
  1267. * @return string
  1268. */
  1269. public function generateNonceStr($length=16){
  1270. // 密码字符集,可任意添加你需要的字符
  1271. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1272. $str = "";
  1273. for($i = 0; $i < $length; $i++)
  1274. {
  1275. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1276. }
  1277. return $str;
  1278. }
  1279. /**
  1280. * 生成原生支付url
  1281. * @param number $productid 商品编号,最长为32字节
  1282. * @return string
  1283. */
  1284. public function createNativeUrl($productid){
  1285. $nativeObj["appid"] = $this->appid;
  1286. $nativeObj["appkey"] = $this->paysignkey;
  1287. $nativeObj["productid"] = urlencode($productid);
  1288. $nativeObj["timestamp"] = time();
  1289. $nativeObj["noncestr"] = $this->generateNonceStr();
  1290. $nativeObj["sign"] = $this->getSignature($nativeObj);
  1291. unset($nativeObj["appkey"]);
  1292. $bizString = "";
  1293. foreach($nativeObj as $key => $value)
  1294. {
  1295. if(strlen($bizString) == 0)
  1296. $bizString .= $key . "=" . $value;
  1297. else
  1298. $bizString .= "&" . $key . "=" . $value;
  1299. }
  1300. return "weixin://wxpay/bizpayurl?".$bizString;
  1301. //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX
  1302. }
  1303. /**
  1304. * 生成订单package字符串
  1305. * @param string $out_trade_no 必填,商户系统内部的订单号,32个字符内,确保在商户系统唯一
  1306. * @param string $body 必填,商品描述,128 字节以下
  1307. * @param int $total_fee 必填,订单总金额,单位为分
  1308. * @param string $notify_url 必填,支付完成通知回调接口,255 字节以内
  1309. * @param string $spbill_create_ip 必填,用户终端IP,IPV4字串,15字节内
  1310. * @param int $fee_type 必填,现金支付币种,默认1:人民币
  1311. * @param string $bank_type 必填,银行通道类型,默认WX
  1312. * @param string $input_charset 必填,传入参数字符编码,默认UTF-8,取值有UTF-8和GBK
  1313. * @param string $time_start 交易起始时间,订单生成时间,格式yyyyMMddHHmmss
  1314. * @param string $time_expire 交易结束时间,也是订单失效时间
  1315. * @param int $transport_fee 物流费用,单位为分
  1316. * @param int $product_fee 商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee
  1317. * @param string $goods_tag 商品标记,优惠券时可能用到
  1318. * @param string $attach 附加数据,notify接口原样返回
  1319. * @return string
  1320. */
  1321. 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=""){
  1322. $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);
  1323. if ($time_start) $arrdata['time_start'] = $time_start;
  1324. if ($time_expire) $arrdata['time_expire'] = $time_expire;
  1325. if ($transport_fee) $arrdata['transport_fee'] = $transport_fee;
  1326. if ($product_fee) $arrdata['product_fee'] = $product_fee;
  1327. if ($goods_tag) $arrdata['goods_tag'] = $goods_tag;
  1328. if ($attach) $arrdata['attach'] = $attach;
  1329. ksort($arrdata);
  1330. $paramstring = "";
  1331. foreach($arrdata as $key => $value)
  1332. {
  1333. if(strlen($paramstring) == 0)
  1334. $paramstring .= $key . "=" . $value;
  1335. else
  1336. $paramstring .= "&" . $key . "=" . $value;
  1337. }
  1338. $stringSignTemp = $paramstring . "&key=" . $this->partnerkey;
  1339. $signValue = strtoupper(md5($stringSignTemp));
  1340. $package = http_build_query($arrdata) . "&sign=" . $signValue;
  1341. return $package;
  1342. }
  1343. /**
  1344. * 支付签名(paySign)生成方法
  1345. * @param string $package 订单详情字串
  1346. * @param string $timeStamp 当前时间戳(需与JS输出的一致)
  1347. * @param string $nonceStr 随机串(需与JS输出的一致)
  1348. * @return string 返回签名字串
  1349. */
  1350. public function getPaySign($package, $timeStamp, $nonceStr){
  1351. $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey);
  1352. $paySign = $this->getSignature($arrdata);
  1353. return $paySign;
  1354. }
  1355. /**
  1356. * 回调通知签名验证
  1357. * @param array $orderxml 返回的orderXml的数组表示,留空则自动从post数据获取
  1358. * @return boolean
  1359. */
  1360. public function checkOrderSignature($orderxml=''){
  1361. if (!$orderxml) {
  1362. $postStr = file_get_contents("php://input");
  1363. if (!empty($postStr)) {
  1364. $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  1365. } else return false;
  1366. }
  1367. $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']);
  1368. $paySign = $this->getSignature($arrdata);
  1369. if ($paySign!=$orderxml['AppSignature']) return false;
  1370. return true;
  1371. }
  1372. /**
  1373. * 发货通知
  1374. * @param string $openid 用户open_id
  1375. * @param string $transid 交易单号
  1376. * @param string $out_trade_no 第三方订单号
  1377. * @param int $status 0:发货失败;1:已发货
  1378. * @param string $msg 失败原因
  1379. * @return boolean|array
  1380. */
  1381. public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
  1382. if (!$this->access_token && !$this->checkAuth()) return false;
  1383. $postdata = array(
  1384. "appid"=>$this->appid,
  1385. "appkey"=>$this->paysignkey,
  1386. "openid"=>$openid,
  1387. "transid"=>strval($transid),
  1388. "out_trade_no"=>strval($out_trade_no),
  1389. "deliver_timestamp"=>strval(time()),
  1390. "deliver_status"=>strval($status),
  1391. "deliver_msg"=>$msg,
  1392. );
  1393. $postdata['app_signature'] = $this->getSignature($postdata);
  1394. $postdata['sign_method'] = 'sha1';
  1395. unset($postdata['appkey']);
  1396. $result = $this->http_post(self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
  1397. if ($result)
  1398. {
  1399. $json = json_decode($result,true);
  1400. if (!$json || !empty($json['errcode'])) {
  1401. $this->errCode = $json['errcode'];
  1402. $this->errMsg = $json['errmsg'];
  1403. return false;
  1404. }
  1405. return $json;
  1406. }
  1407. return false;
  1408. }
  1409. /**
  1410. * 查询订单信息
  1411. * @param string $out_trade_no 订单号
  1412. * @return boolean|array
  1413. */
  1414. public function getPayOrder($out_trade_no) {
  1415. if (!$this->access_token && !$this->checkAuth()) return false;
  1416. $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}"));
  1417. $postdata = array(
  1418. "appid"=>$this->appid,
  1419. "appkey"=>$this->paysignkey,
  1420. "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign",
  1421. "timestamp"=>strval(time()),
  1422. );
  1423. $postdata['app_signature'] = $this->getSignature($postdata);
  1424. $postdata['sign_method'] = 'sha1';
  1425. unset($postdata['appkey']);
  1426. $result = $this->http_post(self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata));
  1427. if ($result)
  1428. {
  1429. $json = json_decode($result,true);
  1430. if (!$json || !empty($json['errcode'])) {
  1431. $this->errCode = $json['errcode'];
  1432. $this->errMsg = $json['errmsg'].json_encode($postdata);
  1433. return false;
  1434. }
  1435. return $json["order_info"];
  1436. }
  1437. return false;
  1438. }
  1439. /**
  1440. * 获取收货地址JS的签名
  1441. * @tutorial 参考weixin.js脚本的WeixinJS.editAddress方法调用
  1442. * @param string $appId
  1443. * @param string $url
  1444. * @param int $timeStamp
  1445. * @param string $nonceStr
  1446. * @param string $user_token
  1447. * @return Ambigous <boolean, string>
  1448. */
  1449. public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){
  1450. if (!$user_token) $user_token = $this->user_token;
  1451. if (!$user_token) {
  1452. $this->errMsg = 'no user access token found!';
  1453. return false;
  1454. }
  1455. $url = htmlspecialchars_decode($url);
  1456. $arrdata = array(
  1457. 'appid'=>$this->appid,
  1458. 'url'=>$url,
  1459. 'timestamp'=>strval($timeStamp),
  1460. 'noncestr'=>$nonceStr,
  1461. 'accesstoken'=>$user_token
  1462. );
  1463. return $this->getSignature($arrdata);
  1464. }
  1465. /**
  1466. * 发送模板消息
  1467. * @param array $data 消息结构
  1468. * {
  1469. "touser":"OPENID",
  1470. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  1471. "url":"http://weixin.qq.com/download",
  1472. "topcolor":"#FF0000",
  1473. "data":{
  1474. "参数名1": {
  1475. "value":"参数",
  1476. "color":"#173177" //参数颜色
  1477. },
  1478. "Date":{
  1479. "value":"06月07日 19时24分",
  1480. "color":"#173177"
  1481. },
  1482. "CardNumber":{
  1483. "value":"0426",
  1484. "color":"#173177"
  1485. },
  1486. "Type":{
  1487. "value":"消费",
  1488. "color":"#173177"
  1489. }
  1490. }
  1491. }
  1492. * @return boolean|array
  1493. */
  1494. public function sendTemplateMessage($data){
  1495. if (!$this->access_token && !$this->checkAuth()) return false;
  1496. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1497. if($result){
  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 array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  1511. * @return boolean|array
  1512. */
  1513. public function getCustomServiceMessage($data){
  1514. if (!$this->access_token && !$this->checkAuth()) return false;
  1515. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  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. }
  1524. return $json;
  1525. }
  1526. return false;
  1527. }
  1528. /**
  1529. * 转发多客服消息
  1530. * Examle: $obj->transfer_customer_service($customer_account)->reply();
  1531. * @param string $customer_account 转发到指定客服帐号:test1@test
  1532. */
  1533. public function transfer_customer_service($customer_account = '')
  1534. {
  1535. $msg = array(
  1536. 'ToUserName' => $this->getRevFrom(),
  1537. 'FromUserName'=>$this->getRevTo(),
  1538. 'CreateTime'=>time(),
  1539. 'MsgType'=>'transfer_customer_service',
  1540. );
  1541. if (!$customer_account) {
  1542. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  1543. }
  1544. $this->Message($msg);
  1545. return $this;
  1546. }
  1547. /**
  1548. * 获取多客服客服基本信息
  1549. *
  1550. * @return boolean|array
  1551. */
  1552. public function getCustomServiceKFlist(){
  1553. if (!$this->access_token && !$this->checkAuth()) return false;
  1554. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  1555. if ($result)
  1556. {
  1557. $json = json_decode($result,true);
  1558. if (!$json || !empty($json['errcode'])) {
  1559. $this->errCode = $json['errcode'];
  1560. $this->errMsg = $json['errmsg'];
  1561. return false;
  1562. }
  1563. return $json;
  1564. }
  1565. return false;
  1566. }
  1567. /**
  1568. * 获取多客服在线客服接待信息
  1569. *
  1570. * @return boolean|array {
  1571. "kf_online_list": [
  1572. {
  1573. "kf_account": "test1@test", //客服账号@微信别名
  1574. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  1575. "kf_id": "1001", //客服工号
  1576. "auto_accept": 0, //客服设置的最大自动接入数
  1577. "accepted_case": 1 //客服当前正在接待的会话数
  1578. }
  1579. ]
  1580. }
  1581. */
  1582. public function getCustomServiceOnlineKFlist(){
  1583. if (!$this->access_token && !$this->checkAuth()) return false;
  1584. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  1585. if ($result)
  1586. {
  1587. $json = json_decode($result,true);
  1588. if (!$json || !empty($json['errcode'])) {
  1589. $this->errCode = $json['errcode'];
  1590. $this->errMsg = $json['errmsg'];
  1591. return false;
  1592. }
  1593. return $json;
  1594. }
  1595. return false;
  1596. }
  1597. }