Wechat.class.php 44 KB

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