wechat.class.php 47 KB

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