wechat.class.php 41 KB

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