wechat.class.php 46 KB

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