Wechat.class.php 44 KB

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