Wechat.class.php 44 KB

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