Wechat.class.php 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213
  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. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  11. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  12. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
  13. * 'partnerid'=>'88888888', //财付通商户身份标识
  14. * 'partnerkey'=>'', //财付通商户权限密钥Key
  15. * 'paysignkey'=>'' //商户签名密钥Key
  16. * );
  17. * $weObj = new Wechat($options);
  18. * $weObj->valid();
  19. * $type = $weObj->getRev()->getRevType();
  20. * switch($type) {
  21. * case Wechat::MSGTYPE_TEXT:
  22. * $weObj->text("hello, I'm wechat")->reply();
  23. * exit;
  24. * break;
  25. * case Wechat::MSGTYPE_EVENT:
  26. * ....
  27. * break;
  28. * case Wechat::MSGTYPE_IMAGE:
  29. * ...
  30. * break;
  31. * default:
  32. * $weObj->text("help info")->reply();
  33. * }
  34. *
  35. * //获取菜单操作:
  36. * $menu = $weObj->getMenu();
  37. * //设置菜单
  38. * $newmenu = array(
  39. * "button"=>
  40. * array(
  41. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  42. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  43. * )
  44. * );
  45. * $result = $weObj->createMenu($newmenu);
  46. */
  47. class Wechat
  48. {
  49. const MSGTYPE_TEXT = 'text';
  50. const MSGTYPE_IMAGE = 'image';
  51. const MSGTYPE_LOCATION = 'location';
  52. const MSGTYPE_LINK = 'link';
  53. const MSGTYPE_EVENT = 'event';
  54. const MSGTYPE_MUSIC = 'music';
  55. const MSGTYPE_NEWS = 'news';
  56. const MSGTYPE_VOICE = 'voice';
  57. const MSGTYPE_VIDEO = 'video';
  58. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  59. const AUTH_URL = '/token?grant_type=client_credential&';
  60. const MENU_CREATE_URL = '/menu/create?';
  61. const MENU_GET_URL = '/menu/get?';
  62. const MENU_DELETE_URL = '/menu/delete?';
  63. const MEDIA_GET_URL = '/media/get?';
  64. const QRCODE_CREATE_URL='/qrcode/create?';
  65. const QR_SCENE = 0;
  66. const QR_LIMIT_SCENE = 1;
  67. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  68. const SHORT_URL='/shorturl?';
  69. const USER_GET_URL='/user/get?';
  70. const USER_INFO_URL='/user/info?';
  71. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  72. const GROUP_GET_URL='/groups/get?';
  73. const USER_GROUP_URL='/groups/getid?';
  74. const GROUP_CREATE_URL='/groups/create?';
  75. const GROUP_UPDATE_URL='/groups/update?';
  76. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  77. const CUSTOM_SEND_URL='/message/custom/send?';
  78. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  79. const MASS_SEND_URL = '/message/mass/send?';
  80. const TEMPLATE_SEND_URL = '/message/template/send?';
  81. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  82. const MASS_DELETE_URL = '/message/mass/delete?';
  83. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  84. const MEDIA_UPLOAD = '/media/upload?';
  85. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  86. const OAUTH_AUTHORIZE_URL = '/authorize?';
  87. const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2';
  88. const OAUTH_TOKEN_URL = '/access_token?';
  89. const OAUTH_REFRESH_URL = '/refresh_token?';
  90. const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
  91. const OAUTH_AUTH_URL = 'https://api.weixin.qq.com/sns/auth?';
  92. const PAY_DELIVERNOTIFY = 'https://api.weixin.qq.com/pay/delivernotify?';
  93. const PAY_ORDERQUERY = 'https://api.weixin.qq.com/pay/orderquery?';
  94. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  95. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  96. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getkflist?';
  97. const SEMANTIC_API_URL= 'https://api.weixin.qq.com/semantic/semproxy/search?';
  98. private $token;
  99. private $encodingAesKey;
  100. private $encrypt_type;
  101. private $appid;
  102. private $appsecret;
  103. private $access_token;
  104. private $user_token;
  105. private $partnerid;
  106. private $partnerkey;
  107. private $paysignkey;
  108. private $postxml;
  109. private $_msg;
  110. private $_funcflag = false;
  111. private $_receive;
  112. private $_text_filter = true;
  113. public $debug = false;
  114. public $errCode = 40001;
  115. public $errMsg = "no access";
  116. private $_logcallback;
  117. public function __construct($options)
  118. {
  119. $this->token = isset($options['token'])?$options['token']:'';
  120. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  121. $this->appid = isset($options['appid'])?$options['appid']:'';
  122. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  123. $this->partnerid = isset($options['partnerid'])?$options['partnerid']:'';
  124. $this->partnerkey = isset($options['partnerkey'])?$options['partnerkey']:'';
  125. $this->paysignkey = isset($options['paysignkey'])?$options['paysignkey']:'';
  126. $this->debug = isset($options['debug'])?$options['debug']:false;
  127. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  128. }
  129. /**
  130. * For weixin server validation
  131. */
  132. private function checkSignature($str='')
  133. {
  134. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  135. $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密验证则用加密验证段
  136. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  137. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  138. $token = $this->token;
  139. $tmpArr = array($token, $timestamp, $nonce,$str);
  140. sort($tmpArr, SORT_STRING);
  141. $tmpStr = implode( $tmpArr );
  142. $tmpStr = sha1( $tmpStr );
  143. if( $tmpStr == $signature ){
  144. return true;
  145. }else{
  146. return false;
  147. }
  148. }
  149. /**
  150. * For weixin server validation
  151. * @param bool $return 是否返回
  152. */
  153. public function valid($return=false)
  154. {
  155. $encryptStr="";
  156. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  157. $postStr = file_get_contents("php://input");
  158. $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  159. $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"]: '';
  160. if ($this->encrypt_type == 'aes') { //aes加密
  161. $this->log($postStr);
  162. $encryptStr = $array['Encrypt'];
  163. $pc = new Prpcrypt($this->encodingAesKey);
  164. $array = $pc->decrypt($encryptStr,$this->appid);
  165. if (!isset($array[0]) || ($array[0] != 0)) {
  166. if (!$return) {
  167. die('解密失败!');
  168. } else {
  169. return false;
  170. }
  171. }
  172. $this->postxml = $array[1];
  173. if (!$this->appid)
  174. $this->appid = $array[2];//为了没有appid的订阅号。
  175. } else {
  176. $this->postxml = $postStr;
  177. }
  178. } else {
  179. $echoStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
  180. }
  181. if ($return) {
  182. if (isset($echoStr)) {
  183. if ($this->checkSignature($encryptStr))
  184. return $echoStr;
  185. else
  186. return false;
  187. } else
  188. return $this->checkSignature($encryptStr);
  189. } else {
  190. if (isset($echoStr)) {
  191. if ($this->checkSignature($encryptStr))
  192. die($echoStr);
  193. else
  194. die('no access');
  195. } else {
  196. if ($this->checkSignature($encryptStr))
  197. return true;
  198. else
  199. die('no access');
  200. }
  201. }
  202. return false;
  203. }
  204. /**
  205. * 设置发送消息
  206. * @param array $msg 消息数组
  207. * @param bool $append 是否在原消息数组追加
  208. */
  209. public function Message($msg = '',$append = false){
  210. if (is_null($msg)) {
  211. $this->_msg =array();
  212. }elseif (is_array($msg)) {
  213. if ($append)
  214. $this->_msg = array_merge($this->_msg,$msg);
  215. else
  216. $this->_msg = $msg;
  217. return $this->_msg;
  218. } else {
  219. return $this->_msg;
  220. }
  221. }
  222. public function setFuncFlag($flag) {
  223. $this->_funcflag = $flag;
  224. return $this;
  225. }
  226. private function log($log){
  227. if ($this->debug ) {
  228. if (function_exists($this->_logcallback)) {
  229. if (is_array($log)) $log = print_r($log,true);
  230. return call_user_func($this->_logcallback,$log);
  231. }elseif (class_exists('Log')) {
  232. Log::write('wechat:'.$log, Log::DEBUG);
  233. }
  234. }
  235. return false;
  236. }
  237. /**
  238. * 获取微信服务器发来的信息
  239. */
  240. public function getRev()
  241. {
  242. if ($this->_receive) return $this;
  243. $postStr = !empty($this->postxml)?$this->postxml:file_get_contents("php://input");
  244. //兼顾使用明文又不想调用valid()方法的情况
  245. $this->log($postStr);
  246. if (!empty($postStr)) {
  247. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  248. }
  249. return $this;
  250. }
  251. /**
  252. * 获取微信服务器发来的信息
  253. */
  254. public function getRevData()
  255. {
  256. return $this->_receive;
  257. }
  258. /**
  259. * 获取消息发送者
  260. */
  261. public function getRevFrom() {
  262. if (isset($this->_receive['FromUserName']))
  263. return $this->_receive['FromUserName'];
  264. else
  265. return false;
  266. }
  267. /**
  268. * 获取消息接受者
  269. */
  270. public function getRevTo() {
  271. if (isset($this->_receive['ToUserName']))
  272. return $this->_receive['ToUserName'];
  273. else
  274. return false;
  275. }
  276. /**
  277. * 获取接收消息的类型
  278. */
  279. public function getRevType() {
  280. if (isset($this->_receive['MsgType']))
  281. return $this->_receive['MsgType'];
  282. else
  283. return false;
  284. }
  285. /**
  286. * 获取消息ID
  287. */
  288. public function getRevID() {
  289. if (isset($this->_receive['MsgId']))
  290. return $this->_receive['MsgId'];
  291. else
  292. return false;
  293. }
  294. /**
  295. * 获取消息发送时间
  296. */
  297. public function getRevCtime() {
  298. if (isset($this->_receive['CreateTime']))
  299. return $this->_receive['CreateTime'];
  300. else
  301. return false;
  302. }
  303. /**
  304. * 获取接收消息内容正文
  305. */
  306. public function getRevContent(){
  307. if (isset($this->_receive['Content']))
  308. return $this->_receive['Content'];
  309. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  310. return $this->_receive['Recognition'];
  311. else
  312. return false;
  313. }
  314. /**
  315. * 获取接收消息图片
  316. */
  317. public function getRevPic(){
  318. if (isset($this->_receive['PicUrl']))
  319. return array(
  320. 'mediaid'=>$this->_receive['MediaId'],
  321. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  322. );
  323. else
  324. return false;
  325. }
  326. /**
  327. * 获取接收消息链接
  328. */
  329. public function getRevLink(){
  330. if (isset($this->_receive['Url'])){
  331. return array(
  332. 'url'=>$this->_receive['Url'],
  333. 'title'=>$this->_receive['Title'],
  334. 'description'=>$this->_receive['Description']
  335. );
  336. } else
  337. return false;
  338. }
  339. /**
  340. * 获取接收地理位置
  341. */
  342. public function getRevGeo(){
  343. if (isset($this->_receive['Location_X'])){
  344. return array(
  345. 'x'=>$this->_receive['Location_X'],
  346. 'y'=>$this->_receive['Location_Y'],
  347. 'scale'=>$this->_receive['Scale'],
  348. 'label'=>$this->_receive['Label']
  349. );
  350. } else
  351. return false;
  352. }
  353. /**
  354. * 获取上报地理位置事件
  355. */
  356. public function getRevEventGeo(){
  357. if (isset($this->_receive['Latitude'])){
  358. return array(
  359. 'x'=>$this->_receive['Latitude'],
  360. 'y'=>$this->_receive['Longitude'],
  361. 'precision'=>$this->_receive['Precision'],
  362. );
  363. } else
  364. return false;
  365. }
  366. /**
  367. * 获取接收事件推送
  368. */
  369. public function getRevEvent(){
  370. if (isset($this->_receive['Event'])){
  371. $array['event'] = $this->_receive['Event'];
  372. }
  373. if (isset($this->_receive['EventKey'])){
  374. $array['key'] = $this->_receive['EventKey'];
  375. }
  376. if (isset($array) && count($array) > 0) {
  377. return $array;
  378. } else {
  379. return false;
  380. }
  381. }
  382. /**
  383. * 获取自定义菜单的扫码推事件信息
  384. *
  385. * 事件类型为以下两种时则调用此方法有效
  386. * Event 事件类型,scancode_push
  387. * Event 事件类型,scancode_waitmsg
  388. *
  389. * @return: array | false
  390. * array (
  391. * 'ScanType'=>'qrcode',
  392. * 'ScanResult'=>'123123'
  393. * )
  394. */
  395. public function getRevScanInfo(){
  396. if (isset($this->_receive['ScanCodeInfo'])){
  397. if (!is_array($this->_receive['SendPicsInfo'])) {
  398. $array=(array)$this->_receive['ScanCodeInfo'];
  399. $this->_receive['ScanCodeInfo']=$array;
  400. }else {
  401. $array=$this->_receive['ScanCodeInfo'];
  402. }
  403. }
  404. if (isset($array) && count($array) > 0) {
  405. return $array;
  406. } else {
  407. return false;
  408. }
  409. }
  410. /**
  411. * 获取自定义菜单的图片发送事件信息
  412. *
  413. * 事件类型为以下三种时则调用此方法有效
  414. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  415. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  416. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  417. *
  418. * @return: array | false
  419. * array (
  420. * 'Count' => '2',
  421. * 'PicList' =>array (
  422. * 'item' =>array (
  423. * 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
  424. * 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
  425. * ),
  426. * ),
  427. * )
  428. *
  429. */
  430. public function getRevSendPicsInfo(){
  431. if (isset($this->_receive['SendPicsInfo'])){
  432. if (!is_array($this->_receive['SendPicsInfo'])) {
  433. $array=(array)$this->_receive['SendPicsInfo'];
  434. if (isset($array['PicList'])){
  435. $array['PicList']=(array)$array['PicList'];
  436. $item=$array['PicList']['item'];
  437. $array['PicList']['item']=array();
  438. foreach ( $item as $key => $value ){
  439. $array['PicList']['item'][$key]=(array)$value;
  440. }
  441. }
  442. $this->_receive['SendPicsInfo']=$array;
  443. } else {
  444. $array=$this->_receive['SendPicsInfo'];
  445. }
  446. }
  447. if (isset($array) && count($array) > 0) {
  448. return $array;
  449. } else {
  450. return false;
  451. }
  452. }
  453. /**
  454. * 获取自定义菜单的地理位置选择器事件推送
  455. *
  456. * 事件类型为以下时则可以调用此方法有效
  457. * Event 事件类型,location_select 弹出系统拍照发图的事件推送
  458. *
  459. * @return: array | false
  460. * array (
  461. * 'Location_X' => '33.731655000061',
  462. * 'Location_Y' => '113.29955200008047',
  463. * 'Scale' => '16',
  464. * 'Label' => '某某市某某区某某路',
  465. * 'Poiname' => '',
  466. * )
  467. *
  468. */
  469. public function getRevSendGeoInfo(){
  470. if (isset($this->_receive['SendLocationInfo'])){
  471. if (!is_array($this->_receive['SendLocationInfo'])) {
  472. $array=(array)$this->_receive['SendLocationInfo'];
  473. if (empty($array['Poiname'])) {
  474. $array['Poiname']="";
  475. }
  476. if (empty($array['Label'])) {
  477. $array['Label']="";
  478. }
  479. $this->_receive['SendLocationInfo']=$array;
  480. } else {
  481. $array=$this->_receive['SendLocationInfo'];
  482. }
  483. }
  484. if (isset($array) && count($array) > 0) {
  485. return $array;
  486. } else {
  487. return false;
  488. }
  489. }
  490. /**
  491. * 获取接收语音推送
  492. */
  493. public function getRevVoice(){
  494. if (isset($this->_receive['MediaId'])){
  495. return array(
  496. 'mediaid'=>$this->_receive['MediaId'],
  497. 'format'=>$this->_receive['Format'],
  498. );
  499. } else
  500. return false;
  501. }
  502. /**
  503. * 获取接收视频推送
  504. */
  505. public function getRevVideo(){
  506. if (isset($this->_receive['MediaId'])){
  507. return array(
  508. 'mediaid'=>$this->_receive['MediaId'],
  509. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  510. );
  511. } else
  512. return false;
  513. }
  514. /**
  515. * 获取接收TICKET
  516. */
  517. public function getRevTicket(){
  518. if (isset($this->_receive['Ticket'])){
  519. return $this->_receive['Ticket'];
  520. } else
  521. return false;
  522. }
  523. /**
  524. * 获取二维码的场景值
  525. */
  526. public function getRevSceneId (){
  527. if (isset($this->_receive['EventKey'])){
  528. return str_replace('qrscene_','',$this->_receive['EventKey']);
  529. } else{
  530. return false;
  531. }
  532. }
  533. /**
  534. * 获取模板消息ID
  535. * 经过验证,这个和普通的消息MsgId不一样
  536. */
  537. public function getRevTplMsgID(){
  538. if (isset($this->_receive['MsgID'])){
  539. return $this->_receive['MsgID'];
  540. } else
  541. return false;
  542. }
  543. /**
  544. * 获取模板消息发送状态
  545. */
  546. public function getRevStatus(){
  547. if (isset($this->_receive['Status'])){
  548. return $this->_receive['Status'];
  549. } else
  550. return false;
  551. }
  552. public static function xmlSafeStr($str)
  553. {
  554. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  555. }
  556. /**
  557. * 数据XML编码
  558. * @param mixed $data 数据
  559. * @return string
  560. */
  561. public static function data_to_xml($data) {
  562. $xml = '';
  563. foreach ($data as $key => $val) {
  564. is_numeric($key) && $key = "item id=\"$key\"";
  565. $xml .= "<$key>";
  566. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  567. list($key, ) = explode(' ', $key);
  568. $xml .= "</$key>";
  569. }
  570. return $xml;
  571. }
  572. /**
  573. * XML编码
  574. * @param mixed $data 数据
  575. * @param string $root 根节点名
  576. * @param string $item 数字索引的子节点名
  577. * @param string $attr 根节点属性
  578. * @param string $id 数字索引子节点key转换的属性名
  579. * @param string $encoding 数据编码
  580. * @return string
  581. */
  582. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  583. if(is_array($attr)){
  584. $_attr = array();
  585. foreach ($attr as $key => $value) {
  586. $_attr[] = "{$key}=\"{$value}\"";
  587. }
  588. $attr = implode(' ', $_attr);
  589. }
  590. $attr = trim($attr);
  591. $attr = empty($attr) ? '' : " {$attr}";
  592. $xml = "<{$root}{$attr}>";
  593. $xml .= self::data_to_xml($data, $item, $id);
  594. $xml .= "</{$root}>";
  595. return $xml;
  596. }
  597. /**
  598. * 过滤文字回复\r\n换行符
  599. * @param string $text
  600. * @return string|mixed
  601. */
  602. private function _auto_text_filter($text) {
  603. if (!$this->_text_filter) return $text;
  604. return str_replace("\r\n", "\n", $text);
  605. }
  606. /**
  607. * 设置回复消息
  608. * Examle: $obj->text('hello')->reply();
  609. * @param string $text
  610. */
  611. public function text($text='')
  612. {
  613. $FuncFlag = $this->_funcflag ? 1 : 0;
  614. $msg = array(
  615. 'ToUserName' => $this->getRevFrom(),
  616. 'FromUserName'=>$this->getRevTo(),
  617. 'MsgType'=>self::MSGTYPE_TEXT,
  618. 'Content'=>$this->_auto_text_filter($text),
  619. 'CreateTime'=>time(),
  620. 'FuncFlag'=>$FuncFlag
  621. );
  622. $this->Message($msg);
  623. return $this;
  624. }
  625. /**
  626. * 设置回复消息
  627. * Examle: $obj->image('media_id')->reply();
  628. * @param string $mediaid
  629. */
  630. public function image($mediaid='')
  631. {
  632. $FuncFlag = $this->_funcflag ? 1 : 0;
  633. $msg = array(
  634. 'ToUserName' => $this->getRevFrom(),
  635. 'FromUserName'=>$this->getRevTo(),
  636. 'MsgType'=>self::MSGTYPE_IMAGE,
  637. 'Image'=>array('MediaId'=>$mediaid),
  638. 'CreateTime'=>time(),
  639. 'FuncFlag'=>$FuncFlag
  640. );
  641. $this->Message($msg);
  642. return $this;
  643. }
  644. /**
  645. * 设置回复消息
  646. * Examle: $obj->voice('media_id')->reply();
  647. * @param string $mediaid
  648. */
  649. public function voice($mediaid='')
  650. {
  651. $FuncFlag = $this->_funcflag ? 1 : 0;
  652. $msg = array(
  653. 'ToUserName' => $this->getRevFrom(),
  654. 'FromUserName'=>$this->getRevTo(),
  655. 'MsgType'=>self::MSGTYPE_IMAGE,
  656. 'Voice'=>array('MediaId'=>$mediaid),
  657. 'CreateTime'=>time(),
  658. 'FuncFlag'=>$FuncFlag
  659. );
  660. $this->Message($msg);
  661. return $this;
  662. }
  663. /**
  664. * 设置回复消息
  665. * Examle: $obj->video('media_id','title','description')->reply();
  666. * @param string $mediaid
  667. */
  668. public function video($mediaid='',$title,$description)
  669. {
  670. $FuncFlag = $this->_funcflag ? 1 : 0;
  671. $msg = array(
  672. 'ToUserName' => $this->getRevFrom(),
  673. 'FromUserName'=>$this->getRevTo(),
  674. 'MsgType'=>self::MSGTYPE_IMAGE,
  675. 'Video'=>array(
  676. 'MediaId'=>$mediaid,
  677. 'Title'=>$mediaid,
  678. 'Description'=>$mediaid,
  679. ),
  680. 'CreateTime'=>time(),
  681. 'FuncFlag'=>$FuncFlag
  682. );
  683. $this->Message($msg);
  684. return $this;
  685. }
  686. /**
  687. * 设置回复音乐
  688. * @param string $title
  689. * @param string $desc
  690. * @param string $musicurl
  691. * @param string $hgmusicurl
  692. */
  693. public function music($title,$desc,$musicurl,$hgmusicurl='') {
  694. $FuncFlag = $this->_funcflag ? 1 : 0;
  695. $msg = array(
  696. 'ToUserName' => $this->getRevFrom(),
  697. 'FromUserName'=>$this->getRevTo(),
  698. 'CreateTime'=>time(),
  699. 'MsgType'=>self::MSGTYPE_MUSIC,
  700. 'Music'=>array(
  701. 'Title'=>$title,
  702. 'Description'=>$desc,
  703. 'MusicUrl'=>$musicurl,
  704. 'HQMusicUrl'=>$hgmusicurl
  705. ),
  706. 'FuncFlag'=>$FuncFlag
  707. );
  708. $this->Message($msg);
  709. return $this;
  710. }
  711. /**
  712. * 设置回复图文
  713. * @param array $newsData
  714. * 数组结构:
  715. * array(
  716. * "0"=>array(
  717. * 'Title'=>'msg title',
  718. * 'Description'=>'summary text',
  719. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  720. * 'Url'=>'http://www.domain.com/1.html'
  721. * ),
  722. * "1"=>....
  723. * )
  724. */
  725. public function news($newsData=array())
  726. {
  727. $FuncFlag = $this->_funcflag ? 1 : 0;
  728. $count = count($newsData);
  729. $msg = array(
  730. 'ToUserName' => $this->getRevFrom(),
  731. 'FromUserName'=>$this->getRevTo(),
  732. 'MsgType'=>self::MSGTYPE_NEWS,
  733. 'CreateTime'=>time(),
  734. 'ArticleCount'=>$count,
  735. 'Articles'=>$newsData,
  736. 'FuncFlag'=>$FuncFlag
  737. );
  738. $this->Message($msg);
  739. return $this;
  740. }
  741. /**
  742. *
  743. * 回复微信服务器, 此函数支持链式操作
  744. * Example: $this->text('msg tips')->reply();
  745. * @param string $msg 要发送的信息, 默认取$this->_msg
  746. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  747. */
  748. public function reply($msg=array(),$return = false)
  749. {
  750. if (empty($msg))
  751. $msg = $this->_msg;
  752. $xmldata= $this->xml_encode($msg);
  753. $this->log($xmldata);
  754. if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式
  755. $pc = new Prpcrypt($this->encodingAesKey);
  756. $array = $pc->encrypt($xmldata, $this->appid);
  757. $ret = $array[0];
  758. if ($ret != 0) {
  759. $this->log('encrypt err!');
  760. return false;
  761. }
  762. $timestamp = time();
  763. $nonce = rand(77,999)*rand(605,888)*rand(11,99);
  764. $encrypt = $array[1];
  765. $tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
  766. sort($tmpArr, SORT_STRING);
  767. $signature = implode($tmpArr);
  768. $signature = sha1($signature);
  769. $xmldata = $this->generate($encrypt, $signature, $timestamp, $nonce);
  770. $this->log($xmldata);
  771. }
  772. if ($return)
  773. return $xmldata;
  774. else
  775. echo $xmldata;
  776. }
  777. /**
  778. * xml格式加密,仅请求为加密方式时再用
  779. */
  780. private function generate($encrypt, $signature, $timestamp, $nonce)
  781. {
  782. //格式化加密信息
  783. $format = "<xml>
  784. <Encrypt><![CDATA[%s]]></Encrypt>
  785. <MsgSignature><![CDATA[%s]]></MsgSignature>
  786. <TimeStamp>%s</TimeStamp>
  787. <Nonce><![CDATA[%s]]></Nonce>
  788. </xml>";
  789. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  790. }
  791. /**
  792. * GET 请求
  793. * @param string $url
  794. */
  795. private function http_get($url){
  796. $oCurl = curl_init();
  797. if(stripos($url,"https://")!==FALSE){
  798. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  799. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  800. }
  801. curl_setopt($oCurl, CURLOPT_URL, $url);
  802. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  803. $sContent = curl_exec($oCurl);
  804. $aStatus = curl_getinfo($oCurl);
  805. curl_close($oCurl);
  806. if(intval($aStatus["http_code"])==200){
  807. return $sContent;
  808. }else{
  809. return false;
  810. }
  811. }
  812. /**
  813. * POST 请求
  814. * @param string $url
  815. * @param array $param
  816. * @param boolean $post_file 是否文件上传
  817. * @return string content
  818. */
  819. private function http_post($url,$param,$post_file=false){
  820. $oCurl = curl_init();
  821. if(stripos($url,"https://")!==FALSE){
  822. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  823. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  824. }
  825. if (is_string($param) || $post_file) {
  826. $strPOST = $param;
  827. } else {
  828. $aPOST = array();
  829. foreach($param as $key=>$val){
  830. $aPOST[] = $key."=".urlencode($val);
  831. }
  832. $strPOST = join("&", $aPOST);
  833. }
  834. curl_setopt($oCurl, CURLOPT_URL, $url);
  835. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  836. curl_setopt($oCurl, CURLOPT_POST,true);
  837. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  838. $sContent = curl_exec($oCurl);
  839. $aStatus = curl_getinfo($oCurl);
  840. curl_close($oCurl);
  841. if(intval($aStatus["http_code"])==200){
  842. return $sContent;
  843. }else{
  844. return false;
  845. }
  846. }
  847. /**
  848. * 通用auth验证方法,暂时仅用于菜单更新操作
  849. * @param string $appid
  850. * @param string $appsecret
  851. * @param string $token 手动指定access_token,非必要情况不建议用
  852. */
  853. public function checkAuth($appid='',$appsecret='',$token=''){
  854. if (!$appid || !$appsecret) {
  855. $appid = $this->appid;
  856. $appsecret = $this->appsecret;
  857. }
  858. $authname = 'wechat_access_token'.$appid;
  859. if ($token) { //手动指定token,优先使用
  860. $this->access_token=$token;
  861. return $this->access_token;
  862. }
  863. if ($rs = S($authname)) {
  864. $this->access_token = $rs;
  865. return $rs;
  866. }
  867. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  868. if ($result)
  869. {
  870. $json = json_decode($result,true);
  871. if (!$json || isset($json['errcode'])) {
  872. $this->errCode = $json['errcode'];
  873. $this->errMsg = $json['errmsg'];
  874. return false;
  875. }
  876. $this->access_token = $json['access_token'];
  877. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  878. S($authname,$this->access_token,$expire);
  879. return $this->access_token;
  880. }
  881. return false;
  882. }
  883. /**
  884. * 删除验证数据
  885. * @param string $appid
  886. */
  887. public function resetAuth($appid=''){
  888. if (!$appid) $appid = $this->appid;
  889. $this->access_token = '';
  890. $authname = 'wechat_access_token'.$appid;
  891. S($authname,null);
  892. return true;
  893. }
  894. /**
  895. * 微信api不支持中文转义的json结构
  896. * @param array $arr
  897. */
  898. static function json_encode($arr) {
  899. $parts = array ();
  900. $is_list = false;
  901. //Find out if the given array is a numerical array
  902. $keys = array_keys ( $arr );
  903. $max_length = count ( $arr ) - 1;
  904. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  905. $is_list = true;
  906. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  907. if ($i != $keys [$i]) { //A key fails at position check.
  908. $is_list = false; //It is an associative array.
  909. break;
  910. }
  911. }
  912. }
  913. foreach ( $arr as $key => $value ) {
  914. if (is_array ( $value )) { //Custom handling for arrays
  915. if ($is_list)
  916. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  917. else
  918. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  919. } else {
  920. $str = '';
  921. if (! $is_list)
  922. $str = '"' . $key . '":';
  923. //Custom handling for multiple data types
  924. if (is_numeric ( $value ) && $value<2000000000)
  925. $str .= $value; //Numbers
  926. elseif ($value === false)
  927. $str .= 'false'; //The booleans
  928. elseif ($value === true)
  929. $str .= 'true';
  930. else
  931. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  932. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  933. $parts [] = $str;
  934. }
  935. }
  936. $json = implode ( ',', $parts );
  937. if ($is_list)
  938. return '[' . $json . ']'; //Return numerical JSON
  939. return '{' . $json . '}'; //Return associative JSON
  940. }
  941. /**
  942. * 创建菜单
  943. * @param array $data 菜单数组数据
  944. * example:
  945. * array (
  946. * 'button' => array (
  947. * 0 => array (
  948. * 'name' => '扫码',
  949. * 'sub_button' => array (
  950. * 0 => array (
  951. * 'type' => 'scancode_waitmsg',
  952. * 'name' => '扫码带提示',
  953. * 'key' => 'rselfmenu_0_0',
  954. * ),
  955. * 1 => array (
  956. * 'type' => 'scancode_push',
  957. * 'name' => '扫码推事件',
  958. * 'key' => 'rselfmenu_0_1',
  959. * ),
  960. * ),
  961. * ),
  962. * 1 => array (
  963. * 'name' => '发图',
  964. * 'sub_button' => array (
  965. * 0 => array (
  966. * 'type' => 'pic_sysphoto',
  967. * 'name' => '系统拍照发图',
  968. * 'key' => 'rselfmenu_1_0',
  969. * ),
  970. * 1 => array (
  971. * 'type' => 'pic_photo_or_album',
  972. * 'name' => '拍照或者相册发图',
  973. * 'key' => 'rselfmenu_1_1',
  974. * )
  975. * ),
  976. * ),
  977. * 2 => array (
  978. * 'type' => 'location_select',
  979. * 'name' => '发送位置',
  980. * 'key' => 'rselfmenu_2_0'
  981. * ),
  982. * ),
  983. * )
  984. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  985. * 1、click:点击推事件
  986. * 2、view:跳转URL
  987. * 3、scancode_push:扫码推事件
  988. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  989. * 5、pic_sysphoto:弹出系统拍照发图
  990. * 6、pic_photo_or_album:弹出拍照或者相册发图
  991. * 7、pic_weixin:弹出微信相册发图器
  992. * 8、location_select:弹出地理位置选择器
  993. */
  994. public function createMenu($data){
  995. if (!$this->access_token && !$this->checkAuth()) return false;
  996. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  997. if ($result)
  998. {
  999. $json = json_decode($result,true);
  1000. if (!$json || !empty($json['errcode'])) {
  1001. $this->errCode = $json['errcode'];
  1002. $this->errMsg = $json['errmsg'];
  1003. return false;
  1004. }
  1005. return true;
  1006. }
  1007. return false;
  1008. }
  1009. /**
  1010. * 获取菜单
  1011. * @return array('menu'=>array(....s))
  1012. */
  1013. public function getMenu(){
  1014. if (!$this->access_token && !$this->checkAuth()) return false;
  1015. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  1016. if ($result)
  1017. {
  1018. $json = json_decode($result,true);
  1019. if (!$json || isset($json['errcode'])) {
  1020. $this->errCode = $json['errcode'];
  1021. $this->errMsg = $json['errmsg'];
  1022. return false;
  1023. }
  1024. return $json;
  1025. }
  1026. return false;
  1027. }
  1028. /**
  1029. * 删除菜单
  1030. * @return boolean
  1031. */
  1032. public function deleteMenu(){
  1033. if (!$this->access_token && !$this->checkAuth()) return false;
  1034. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  1035. if ($result)
  1036. {
  1037. $json = json_decode($result,true);
  1038. if (!$json || !empty($json['errcode'])) {
  1039. $this->errCode = $json['errcode'];
  1040. $this->errMsg = $json['errmsg'];
  1041. return false;
  1042. }
  1043. return true;
  1044. }
  1045. return false;
  1046. }
  1047. /**
  1048. * 上传多媒体文件
  1049. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1050. * @param array $data {"media":'@Path\filename.jpg'}
  1051. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1052. * @return boolean|array
  1053. */
  1054. public function uploadMedia($data, $type){
  1055. if (!$this->access_token && !$this->checkAuth()) return false;
  1056. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1057. if ($result)
  1058. {
  1059. $json = json_decode($result,true);
  1060. if (!$json || !empty($json['errcode'])) {
  1061. $this->errCode = $json['errcode'];
  1062. $this->errMsg = $json['errmsg'];
  1063. return false;
  1064. }
  1065. return $json;
  1066. }
  1067. return false;
  1068. }
  1069. /**
  1070. * 根据媒体文件ID获取媒体文件
  1071. * @param string $media_id 媒体文件id
  1072. * @return raw data
  1073. */
  1074. public function getMedia($media_id){
  1075. if (!$this->access_token && !$this->checkAuth()) return false;
  1076. $result = $this->http_get(self::UPLOAD_MEDIA_URL.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1077. if ($result)
  1078. {
  1079. $json = json_decode($result,true);
  1080. if (isset($json['errcode'])) {
  1081. $this->errCode = $json['errcode'];
  1082. $this->errMsg = $json['errmsg'];
  1083. return false;
  1084. }
  1085. return $result;
  1086. }
  1087. return false;
  1088. }
  1089. /**
  1090. * 上传图文消息素材
  1091. * @param array $data 消息结构{"articles":[{...}]}
  1092. * @return boolean|array
  1093. */
  1094. public function uploadArticles($data){
  1095. if (!$this->access_token && !$this->checkAuth()) return false;
  1096. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1097. if ($result)
  1098. {
  1099. $json = json_decode($result,true);
  1100. if (!$json || !empty($json['errcode'])) {
  1101. $this->errCode = $json['errcode'];
  1102. $this->errMsg = $json['errmsg'];
  1103. return false;
  1104. }
  1105. return $json;
  1106. }
  1107. return false;
  1108. }
  1109. /**
  1110. * 高级群发消息, 根据OpenID列表群发图文消息
  1111. * @param array $data 消息结构{ "touser":[ "OPENID1", "OPENID2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  1112. * @return boolean|array
  1113. */
  1114. public function sendMassMessage($data){
  1115. if (!$this->access_token && !$this->checkAuth()) return false;
  1116. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1117. if ($result)
  1118. {
  1119. $json = json_decode($result,true);
  1120. if (!$json || !empty($json['errcode'])) {
  1121. $this->errCode = $json['errcode'];
  1122. $this->errMsg = $json['errmsg'];
  1123. return false;
  1124. }
  1125. return $json;
  1126. }
  1127. return false;
  1128. }
  1129. /**
  1130. * 高级群发消息, 根据群组id群发图文消息
  1131. * @param array $data 消息结构{ "filter":[ "group_id": "2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  1132. * @return boolean|array
  1133. */
  1134. public function sendGroupMassMessage($data){
  1135. if (!$this->access_token && !$this->checkAuth()) return false;
  1136. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1137. if ($result)
  1138. {
  1139. $json = json_decode($result,true);
  1140. if (!$json || !empty($json['errcode'])) {
  1141. $this->errCode = $json['errcode'];
  1142. $this->errMsg = $json['errmsg'];
  1143. return false;
  1144. }
  1145. return $json;
  1146. }
  1147. return false;
  1148. }
  1149. /**
  1150. * 高级群发消息, 删除群发图文消息
  1151. * @param int $msg_id 消息id
  1152. * @return boolean|array
  1153. */
  1154. public function deleteMassMessage($msg_id){
  1155. if (!$this->access_token && !$this->checkAuth()) return false;
  1156. $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)));
  1157. if ($result)
  1158. {
  1159. $json = json_decode($result,true);
  1160. if (!$json || !empty($json['errcode'])) {
  1161. $this->errCode = $json['errcode'];
  1162. $this->errMsg = $json['errmsg'];
  1163. return false;
  1164. }
  1165. return true;
  1166. }
  1167. return false;
  1168. }
  1169. /**
  1170. * 创建二维码ticket
  1171. * @param int $scene_id 自定义追踪id
  1172. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
  1173. * @param int $expire 临时二维码有效期,最大为1800秒
  1174. * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800,'url'=>'二维码图片解析后的地址')
  1175. */
  1176. public function getQRCode($scene_id,$type=0,$expire=1800){
  1177. if (!$this->access_token && !$this->checkAuth()) return false;
  1178. $data = array(
  1179. 'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
  1180. 'expire_seconds'=>$expire,
  1181. 'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
  1182. );
  1183. if ($type == 1) {
  1184. unset($data['expire_seconds']);
  1185. }
  1186. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1187. if ($result)
  1188. {
  1189. $json = json_decode($result,true);
  1190. if (!$json || !empty($json['errcode'])) {
  1191. $this->errCode = $json['errcode'];
  1192. $this->errMsg = $json['errmsg'];
  1193. return false;
  1194. }
  1195. return $json;
  1196. }
  1197. return false;
  1198. }
  1199. /**
  1200. * 获取二维码图片
  1201. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  1202. * @return string url 返回http地址
  1203. */
  1204. public function getQRUrl($ticket) {
  1205. return self::QRCODE_IMG_URL.$ticket;
  1206. }
  1207. /**
  1208. * 长链接转短链接接口
  1209. * @param string $long_url 传入要转换的长url
  1210. * @return boolean|string url 成功则返回转换后的短url
  1211. */
  1212. public function getShortUrl($long_url){
  1213. if (!$this->access_token && !$this->checkAuth()) return false;
  1214. $data = array(
  1215. 'action'=>'long2short',
  1216. 'long_url'=>$long_url
  1217. );
  1218. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  1219. if ($result)
  1220. {
  1221. $json = json_decode($result,true);
  1222. if (!$json || !empty($json['errcode'])) {
  1223. $this->errCode = $json['errcode'];
  1224. $this->errMsg = $json['errmsg'];
  1225. return false;
  1226. }
  1227. return $json['short_url'];
  1228. }
  1229. return false;
  1230. }
  1231. /**
  1232. * 批量获取关注用户列表
  1233. * @param unknown $next_openid
  1234. */
  1235. public function getUserList($next_openid=''){
  1236. if (!$this->access_token && !$this->checkAuth()) return false;
  1237. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  1238. if ($result)
  1239. {
  1240. $json = json_decode($result,true);
  1241. if (isset($json['errcode'])) {
  1242. $this->errCode = $json['errcode'];
  1243. $this->errMsg = $json['errmsg'];
  1244. return false;
  1245. }
  1246. return $json;
  1247. }
  1248. return false;
  1249. }
  1250. /**
  1251. * 获取关注者详细信息
  1252. * @param string $openid
  1253. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  1254. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1255. */
  1256. public function getUserInfo($openid){
  1257. if (!$this->access_token && !$this->checkAuth()) return false;
  1258. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  1259. if ($result)
  1260. {
  1261. $json = json_decode($result,true);
  1262. if (isset($json['errcode'])) {
  1263. $this->errCode = $json['errcode'];
  1264. $this->errMsg = $json['errmsg'];
  1265. return false;
  1266. }
  1267. return $json;
  1268. }
  1269. return false;
  1270. }
  1271. /**
  1272. * 设置用户备注名
  1273. * @param string $openid
  1274. * @param string $remark 备注名
  1275. * @return boolean|array
  1276. */
  1277. public function updateUserRemark($openid,$remark){
  1278. if (!$this->access_token && !$this->checkAuth()) return false;
  1279. $data = array(
  1280. 'openid'=>$openid,
  1281. 'remark'=>$remark
  1282. );
  1283. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
  1284. if ($result)
  1285. {
  1286. $json = json_decode($result,true);
  1287. if (!$json || !empty($json['errcode'])) {
  1288. $this->errCode = $json['errcode'];
  1289. $this->errMsg = $json['errmsg'];
  1290. return false;
  1291. }
  1292. return $json;
  1293. }
  1294. return false;
  1295. }
  1296. /**
  1297. * 获取用户分组列表
  1298. * @return boolean|array
  1299. */
  1300. public function getGroup(){
  1301. if (!$this->access_token && !$this->checkAuth()) return false;
  1302. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  1303. if ($result)
  1304. {
  1305. $json = json_decode($result,true);
  1306. if (isset($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 $openid
  1318. * @return boolean|int 成功则返回用户分组id
  1319. */
  1320. public function getUserGroup($openid){
  1321. if (!$this->access_token && !$this->checkAuth()) return false;
  1322. $data = array(
  1323. 'openid'=>$openid
  1324. );
  1325. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1326. if ($result)
  1327. {
  1328. $json = json_decode($result,true);
  1329. if (!$json || !empty($json['errcode'])) {
  1330. $this->errCode = $json['errcode'];
  1331. $this->errMsg = $json['errmsg'];
  1332. return false;
  1333. } else
  1334. if (isset($json['groupid'])) return $json['groupid'];
  1335. }
  1336. return false;
  1337. }
  1338. /**
  1339. * 新增自定分组
  1340. * @param string $name 分组名称
  1341. * @return boolean|array
  1342. */
  1343. public function createGroup($name){
  1344. if (!$this->access_token && !$this->checkAuth()) return false;
  1345. $data = array(
  1346. 'group'=>array('name'=>$name)
  1347. );
  1348. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1349. if ($result)
  1350. {
  1351. $json = json_decode($result,true);
  1352. if (!$json || !empty($json['errcode'])) {
  1353. $this->errCode = $json['errcode'];
  1354. $this->errMsg = $json['errmsg'];
  1355. return false;
  1356. }
  1357. return $json;
  1358. }
  1359. return false;
  1360. }
  1361. /**
  1362. * 更改分组名称
  1363. * @param int $groupid 分组id
  1364. * @param string $name 分组名称
  1365. * @return boolean|array
  1366. */
  1367. public function updateGroup($groupid,$name){
  1368. if (!$this->access_token && !$this->checkAuth()) return false;
  1369. $data = array(
  1370. 'group'=>array('id'=>$groupid,'name'=>$name)
  1371. );
  1372. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1373. if ($result)
  1374. {
  1375. $json = json_decode($result,true);
  1376. if (!$json || !empty($json['errcode'])) {
  1377. $this->errCode = $json['errcode'];
  1378. $this->errMsg = $json['errmsg'];
  1379. return false;
  1380. }
  1381. return $json;
  1382. }
  1383. return false;
  1384. }
  1385. /**
  1386. * 移动用户分组
  1387. * @param int $groupid 分组id
  1388. * @param string $openid 用户openid
  1389. * @return boolean|array
  1390. */
  1391. public function updateGroupMembers($groupid,$openid){
  1392. if (!$this->access_token && !$this->checkAuth()) return false;
  1393. $data = array(
  1394. 'openid'=>$openid,
  1395. 'to_groupid'=>$groupid
  1396. );
  1397. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1398. if ($result)
  1399. {
  1400. $json = json_decode($result,true);
  1401. if (!$json || !empty($json['errcode'])) {
  1402. $this->errCode = $json['errcode'];
  1403. $this->errMsg = $json['errmsg'];
  1404. return false;
  1405. }
  1406. return $json;
  1407. }
  1408. return false;
  1409. }
  1410. /**
  1411. * 发送客服消息
  1412. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  1413. * @return boolean|array
  1414. */
  1415. public function sendCustomMessage($data){
  1416. if (!$this->access_token && !$this->checkAuth()) return false;
  1417. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1418. if ($result)
  1419. {
  1420. $json = json_decode($result,true);
  1421. if (!$json || !empty($json['errcode'])) {
  1422. $this->errCode = $json['errcode'];
  1423. $this->errMsg = $json['errmsg'];
  1424. return false;
  1425. }
  1426. return $json;
  1427. }
  1428. return false;
  1429. }
  1430. /**
  1431. * oauth 授权跳转接口
  1432. * @param string $callback 回调URI
  1433. * @return string
  1434. */
  1435. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  1436. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1437. }
  1438. /**
  1439. * 通过code获取Access Token
  1440. * @return array {access_token,expires_in,refresh_token,openid,scope}
  1441. */
  1442. public function getOauthAccessToken(){
  1443. $code = isset($_GET['code'])?$_GET['code']:'';
  1444. if (!$code) return false;
  1445. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  1446. if ($result)
  1447. {
  1448. $json = json_decode($result,true);
  1449. if (!$json || !empty($json['errcode'])) {
  1450. $this->errCode = $json['errcode'];
  1451. $this->errMsg = $json['errmsg'];
  1452. return false;
  1453. }
  1454. $this->user_token = $json['access_token'];
  1455. return $json;
  1456. }
  1457. return false;
  1458. }
  1459. /**
  1460. * 刷新access token并续期
  1461. * @param string $refresh_token
  1462. * @return boolean|mixed
  1463. */
  1464. public function getOauthRefreshToken($refresh_token){
  1465. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  1466. if ($result)
  1467. {
  1468. $json = json_decode($result,true);
  1469. if (!$json || !empty($json['errcode'])) {
  1470. $this->errCode = $json['errcode'];
  1471. $this->errMsg = $json['errmsg'];
  1472. return false;
  1473. }
  1474. $this->user_token = $json['access_token'];
  1475. return $json;
  1476. }
  1477. return false;
  1478. }
  1479. /**
  1480. * 获取授权后的用户资料
  1481. * @param string $access_token
  1482. * @param string $openid
  1483. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  1484. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1485. */
  1486. public function getOauthUserinfo($access_token,$openid){
  1487. $result = $this->http_get(self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  1488. if ($result)
  1489. {
  1490. $json = json_decode($result,true);
  1491. if (!$json || !empty($json['errcode'])) {
  1492. $this->errCode = $json['errcode'];
  1493. $this->errMsg = $json['errmsg'];
  1494. return false;
  1495. }
  1496. return $json;
  1497. }
  1498. return false;
  1499. }
  1500. /**
  1501. * 检验授权凭证是否有效
  1502. * @param string $access_token
  1503. * @param string $openid
  1504. * @return boolean 是否有效
  1505. */
  1506. public function getOauthAuth($access_token,$openid){
  1507. $result = $this->http_get(self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  1508. if ($result)
  1509. {
  1510. $json = json_decode($result,true);
  1511. if (!$json || !empty($json['errcode'])) {
  1512. $this->errCode = $json['errcode'];
  1513. $this->errMsg = $json['errmsg'];
  1514. return false;
  1515. } else
  1516. if ($json['errcode']==0) return true;
  1517. }
  1518. return false;
  1519. }
  1520. /**
  1521. * 获取签名
  1522. * @param array $arrdata 签名数组
  1523. * @param string $method 签名方法
  1524. * @return boolean|string 签名值
  1525. */
  1526. public function getSignature($arrdata,$method="sha1") {
  1527. if (!function_exists($method)) return false;
  1528. ksort($arrdata);
  1529. $paramstring = "";
  1530. foreach($arrdata as $key => $value)
  1531. {
  1532. if(strlen($paramstring) == 0)
  1533. $paramstring .= $key . "=" . $value;
  1534. else
  1535. $paramstring .= "&" . $key . "=" . $value;
  1536. }
  1537. $paySign = $method($paramstring);
  1538. return $paySign;
  1539. }
  1540. /**
  1541. * 生成随机字串
  1542. * @param number $length 长度,默认为16,最长为32字节
  1543. * @return string
  1544. */
  1545. public function generateNonceStr($length=16){
  1546. // 密码字符集,可任意添加你需要的字符
  1547. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1548. $str = "";
  1549. for($i = 0; $i < $length; $i++)
  1550. {
  1551. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1552. }
  1553. return $str;
  1554. }
  1555. /**
  1556. * 生成原生支付url
  1557. * @param number $productid 商品编号,最长为32字节
  1558. * @return string
  1559. */
  1560. public function createNativeUrl($productid){
  1561. $nativeObj["appid"] = $this->appid;
  1562. $nativeObj["appkey"] = $this->paysignkey;
  1563. $nativeObj["productid"] = urlencode($productid);
  1564. $nativeObj["timestamp"] = time();
  1565. $nativeObj["noncestr"] = $this->generateNonceStr();
  1566. $nativeObj["sign"] = $this->getSignature($nativeObj);
  1567. unset($nativeObj["appkey"]);
  1568. $bizString = "";
  1569. foreach($nativeObj as $key => $value)
  1570. {
  1571. if(strlen($bizString) == 0)
  1572. $bizString .= $key . "=" . $value;
  1573. else
  1574. $bizString .= "&" . $key . "=" . $value;
  1575. }
  1576. return "weixin://wxpay/bizpayurl?".$bizString;
  1577. //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX
  1578. }
  1579. /**
  1580. * 生成订单package字符串
  1581. * @param string $out_trade_no 必填,商户系统内部的订单号,32个字符内,确保在商户系统唯一
  1582. * @param string $body 必填,商品描述,128 字节以下
  1583. * @param int $total_fee 必填,订单总金额,单位为分
  1584. * @param string $notify_url 必填,支付完成通知回调接口,255 字节以内
  1585. * @param string $spbill_create_ip 必填,用户终端IP,IPV4字串,15字节内
  1586. * @param int $fee_type 必填,现金支付币种,默认1:人民币
  1587. * @param string $bank_type 必填,银行通道类型,默认WX
  1588. * @param string $input_charset 必填,传入参数字符编码,默认UTF-8,取值有UTF-8和GBK
  1589. * @param string $time_start 交易起始时间,订单生成时间,格式yyyyMMddHHmmss
  1590. * @param string $time_expire 交易结束时间,也是订单失效时间
  1591. * @param int $transport_fee 物流费用,单位为分
  1592. * @param int $product_fee 商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee
  1593. * @param string $goods_tag 商品标记,优惠券时可能用到
  1594. * @param string $attach 附加数据,notify接口原样返回
  1595. * @return string
  1596. */
  1597. 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=""){
  1598. $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);
  1599. if ($time_start) $arrdata['time_start'] = $time_start;
  1600. if ($time_expire) $arrdata['time_expire'] = $time_expire;
  1601. if ($transport_fee) $arrdata['transport_fee'] = $transport_fee;
  1602. if ($product_fee) $arrdata['product_fee'] = $product_fee;
  1603. if ($goods_tag) $arrdata['goods_tag'] = $goods_tag;
  1604. if ($attach) $arrdata['attach'] = $attach;
  1605. ksort($arrdata);
  1606. $paramstring = "";
  1607. foreach($arrdata as $key => $value)
  1608. {
  1609. if(strlen($paramstring) == 0)
  1610. $paramstring .= $key . "=" . $value;
  1611. else
  1612. $paramstring .= "&" . $key . "=" . $value;
  1613. }
  1614. $stringSignTemp = $paramstring . "&key=" . $this->partnerkey;
  1615. $signValue = strtoupper(md5($stringSignTemp));
  1616. $package = http_build_query($arrdata) . "&sign=" . $signValue;
  1617. return $package;
  1618. }
  1619. /**
  1620. * 支付签名(paySign)生成方法
  1621. * @param string $package 订单详情字串
  1622. * @param string $timeStamp 当前时间戳(需与JS输出的一致)
  1623. * @param string $nonceStr 随机串(需与JS输出的一致)
  1624. * @return string 返回签名字串
  1625. */
  1626. public function getPaySign($package, $timeStamp, $nonceStr){
  1627. $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey);
  1628. $paySign = $this->getSignature($arrdata);
  1629. return $paySign;
  1630. }
  1631. /**
  1632. * 回调通知签名验证
  1633. * @param array $orderxml 返回的orderXml的数组表示,留空则自动从post数据获取
  1634. * @return boolean
  1635. */
  1636. public function checkOrderSignature($orderxml=''){
  1637. if (!$orderxml) {
  1638. $postStr = file_get_contents("php://input");
  1639. if (!empty($postStr)) {
  1640. $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  1641. } else return false;
  1642. }
  1643. $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']);
  1644. $paySign = $this->getSignature($arrdata);
  1645. if ($paySign!=$orderxml['AppSignature']) return false;
  1646. return true;
  1647. }
  1648. /**
  1649. * 发货通知
  1650. * @param string $openid 用户open_id
  1651. * @param string $transid 交易单号
  1652. * @param string $out_trade_no 第三方订单号
  1653. * @param int $status 0:发货失败;1:已发货
  1654. * @param string $msg 失败原因
  1655. * @return boolean|array
  1656. */
  1657. public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
  1658. if (!$this->access_token && !$this->checkAuth()) return false;
  1659. $postdata = array(
  1660. "appid"=>$this->appid,
  1661. "appkey"=>$this->paysignkey,
  1662. "openid"=>$openid,
  1663. "transid"=>strval($transid),
  1664. "out_trade_no"=>strval($out_trade_no),
  1665. "deliver_timestamp"=>strval(time()),
  1666. "deliver_status"=>strval($status),
  1667. "deliver_msg"=>$msg,
  1668. );
  1669. $postdata['app_signature'] = $this->getSignature($postdata);
  1670. $postdata['sign_method'] = 'sha1';
  1671. unset($postdata['appkey']);
  1672. $result = $this->http_post(self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
  1673. if ($result)
  1674. {
  1675. $json = json_decode($result,true);
  1676. if (!$json || !empty($json['errcode'])) {
  1677. $this->errCode = $json['errcode'];
  1678. $this->errMsg = $json['errmsg'];
  1679. return false;
  1680. }
  1681. return $json;
  1682. }
  1683. return false;
  1684. }
  1685. /**
  1686. * 查询订单信息
  1687. * @param string $out_trade_no 订单号
  1688. * @return boolean|array
  1689. */
  1690. public function getPayOrder($out_trade_no) {
  1691. if (!$this->access_token && !$this->checkAuth()) return false;
  1692. $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}"));
  1693. $postdata = array(
  1694. "appid"=>$this->appid,
  1695. "appkey"=>$this->paysignkey,
  1696. "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign",
  1697. "timestamp"=>strval(time()),
  1698. );
  1699. $postdata['app_signature'] = $this->getSignature($postdata);
  1700. $postdata['sign_method'] = 'sha1';
  1701. unset($postdata['appkey']);
  1702. $result = $this->http_post(self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata));
  1703. if ($result)
  1704. {
  1705. $json = json_decode($result,true);
  1706. if (!$json || !empty($json['errcode'])) {
  1707. $this->errCode = $json['errcode'];
  1708. $this->errMsg = $json['errmsg'].json_encode($postdata);
  1709. return false;
  1710. }
  1711. return $json["order_info"];
  1712. }
  1713. return false;
  1714. }
  1715. /**
  1716. * 获取收货地址JS的签名
  1717. * @tutorial 参考weixin.js脚本的WeixinJS.editAddress方法调用
  1718. * @param string $appId
  1719. * @param string $url
  1720. * @param int $timeStamp
  1721. * @param string $nonceStr
  1722. * @param string $user_token
  1723. * @return Ambigous <boolean, string>
  1724. */
  1725. public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){
  1726. if (!$user_token) $user_token = $this->user_token;
  1727. if (!$user_token) {
  1728. $this->errMsg = 'no user access token found!';
  1729. return false;
  1730. }
  1731. $url = htmlspecialchars_decode($url);
  1732. $arrdata = array(
  1733. 'appid'=>$this->appid,
  1734. 'url'=>$url,
  1735. 'timestamp'=>strval($timeStamp),
  1736. 'noncestr'=>$nonceStr,
  1737. 'accesstoken'=>$user_token
  1738. );
  1739. return $this->getSignature($arrdata);
  1740. }
  1741. /**
  1742. * 发送模板消息
  1743. * @param array $data 消息结构
  1744. * {
  1745. "touser":"OPENID",
  1746. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  1747. "url":"http://weixin.qq.com/download",
  1748. "topcolor":"#FF0000",
  1749. "data":{
  1750. "参数名1": {
  1751. "value":"参数",
  1752. "color":"#173177" //参数颜色
  1753. },
  1754. "Date":{
  1755. "value":"06月07日 19时24分",
  1756. "color":"#173177"
  1757. },
  1758. "CardNumber":{
  1759. "value":"0426",
  1760. "color":"#173177"
  1761. },
  1762. "Type":{
  1763. "value":"消费",
  1764. "color":"#173177"
  1765. }
  1766. }
  1767. }
  1768. * @return boolean|array
  1769. */
  1770. public function sendTemplateMessage($data){
  1771. if (!$this->access_token && !$this->checkAuth()) return false;
  1772. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1773. if($result){
  1774. $json = json_decode($result,true);
  1775. if (!$json || !empty($json['errcode'])) {
  1776. $this->errCode = $json['errcode'];
  1777. $this->errMsg = $json['errmsg'];
  1778. return false;
  1779. }
  1780. return $json;
  1781. }
  1782. return false;
  1783. }
  1784. /**
  1785. * 获取多客服会话记录
  1786. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  1787. * @return boolean|array
  1788. */
  1789. public function getCustomServiceMessage($data){
  1790. if (!$this->access_token && !$this->checkAuth()) return false;
  1791. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  1792. if ($result)
  1793. {
  1794. $json = json_decode($result,true);
  1795. if (!$json || !empty($json['errcode'])) {
  1796. $this->errCode = $json['errcode'];
  1797. $this->errMsg = $json['errmsg'];
  1798. return false;
  1799. }
  1800. return $json;
  1801. }
  1802. return false;
  1803. }
  1804. /**
  1805. * 转发多客服消息
  1806. * Examle: $obj->transfer_customer_service($customer_account)->reply();
  1807. * @param string $customer_account 转发到指定客服帐号:test1@test
  1808. */
  1809. public function transfer_customer_service($customer_account = '')
  1810. {
  1811. $msg = array(
  1812. 'ToUserName' => $this->getRevFrom(),
  1813. 'FromUserName'=>$this->getRevTo(),
  1814. 'CreateTime'=>time(),
  1815. 'MsgType'=>'transfer_customer_service',
  1816. );
  1817. if (!$customer_account) {
  1818. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  1819. }
  1820. $this->Message($msg);
  1821. return $this;
  1822. }
  1823. /**
  1824. * 获取多客服客服基本信息
  1825. *
  1826. * @return boolean|array
  1827. */
  1828. public function getCustomServiceKFlist(){
  1829. if (!$this->access_token && !$this->checkAuth()) return false;
  1830. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  1831. if ($result)
  1832. {
  1833. $json = json_decode($result,true);
  1834. if (!$json || !empty($json['errcode'])) {
  1835. $this->errCode = $json['errcode'];
  1836. $this->errMsg = $json['errmsg'];
  1837. return false;
  1838. }
  1839. return $json;
  1840. }
  1841. return false;
  1842. }
  1843. /**
  1844. * 获取多客服在线客服接待信息
  1845. *
  1846. * @return boolean|array {
  1847. "kf_online_list": [
  1848. {
  1849. "kf_account": "test1@test", //客服账号@微信别名
  1850. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  1851. "kf_id": "1001", //客服工号
  1852. "auto_accept": 0, //客服设置的最大自动接入数
  1853. "accepted_case": 1 //客服当前正在接待的会话数
  1854. }
  1855. ]
  1856. }
  1857. */
  1858. public function getCustomServiceOnlineKFlist(){
  1859. if (!$this->access_token && !$this->checkAuth()) return false;
  1860. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  1861. if ($result)
  1862. {
  1863. $json = json_decode($result,true);
  1864. if (!$json || !empty($json['errcode'])) {
  1865. $this->errCode = $json['errcode'];
  1866. $this->errMsg = $json['errmsg'];
  1867. return false;
  1868. }
  1869. return $json;
  1870. }
  1871. return false;
  1872. }
  1873. /**
  1874. * 语义理解接口
  1875. * @param String $uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
  1876. * @param String $query 输入文本串
  1877. * @param String $category 需要使用的服务类型,多个用“,”隔开,不能为空
  1878. * @param Float $latitude 纬度坐标,与经度同时传入;与城市二选一传入
  1879. * @param Float $longitude 经度坐标,与纬度同时传入;与城市二选一传入
  1880. * @param String $city 城市名称,与经纬度二选一传入
  1881. * @param String $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入
  1882. * @return boolean|array
  1883. */
  1884. public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
  1885. if (!$this->access_token && !$this->checkAuth()) return false;
  1886. $data=array(
  1887. 'query' => $query,
  1888. 'category' => $category,
  1889. 'appid' => $this->appid,
  1890. 'uid' => ''
  1891. );
  1892. //地理坐标或城市名称二选一
  1893. if ($latitude) {
  1894. $data['latitude'] = $latitude;
  1895. $data['longitude'] = $longitude;
  1896. } elseif ($city) {
  1897. $data['city'] = $city;
  1898. } elseif ($region) {
  1899. $data['region'] = $region;
  1900. }
  1901. $result = $this->http_post(self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
  1902. if ($result)
  1903. {
  1904. $json = json_decode($result,true);
  1905. if (!$json || !empty($json['errcode'])) {
  1906. $this->errCode = $json['errcode'];
  1907. $this->errMsg = $json['errmsg'];
  1908. return false;
  1909. }
  1910. return $json;
  1911. }
  1912. return false;
  1913. }
  1914. }
  1915. /**
  1916. * PKCS7Encoder class
  1917. *
  1918. * 提供基于PKCS7算法的加解密接口.
  1919. */
  1920. class PKCS7Encoder
  1921. {
  1922. public static $block_size = 32;
  1923. /**
  1924. * 对需要加密的明文进行填充补位
  1925. * @param $text 需要进行填充补位操作的明文
  1926. * @return 补齐明文字符串
  1927. */
  1928. function encode($text)
  1929. {
  1930. $block_size = PKCS7Encoder::$block_size;
  1931. $text_length = strlen($text);
  1932. //计算需要填充的位数
  1933. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  1934. if ($amount_to_pad == 0) {
  1935. $amount_to_pad = PKCS7Encoder::block_size;
  1936. }
  1937. //获得补位所用的字符
  1938. $pad_chr = chr($amount_to_pad);
  1939. $tmp = "";
  1940. for ($index = 0; $index < $amount_to_pad; $index++) {
  1941. $tmp .= $pad_chr;
  1942. }
  1943. return $text . $tmp;
  1944. }
  1945. /**
  1946. * 对解密后的明文进行补位删除
  1947. * @param decrypted 解密后的明文
  1948. * @return 删除填充补位后的明文
  1949. */
  1950. function decode($text)
  1951. {
  1952. $pad = ord(substr($text, -1));
  1953. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  1954. $pad = 0;
  1955. }
  1956. return substr($text, 0, (strlen($text) - $pad));
  1957. }
  1958. }
  1959. /**
  1960. * Prpcrypt class
  1961. *
  1962. * 提供接收和推送给公众平台消息的加解密接口.
  1963. */
  1964. class Prpcrypt
  1965. {
  1966. public $key;
  1967. function Prpcrypt($k)
  1968. {
  1969. $this->key = base64_decode($k . "=");
  1970. }
  1971. /**
  1972. * 对明文进行加密
  1973. * @param string $text 需要加密的明文
  1974. * @return string 加密后的密文
  1975. */
  1976. public function encrypt($text, $appid)
  1977. {
  1978. try {
  1979. //获得16位随机字符串,填充到明文之前
  1980. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  1981. $text = $random . pack("N", strlen($text)) . $text . $appid;
  1982. // 网络字节序
  1983. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  1984. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  1985. $iv = substr($this->key, 0, 16);
  1986. //使用自定义的填充方式对明文进行补位填充
  1987. $pkc_encoder = new PKCS7Encoder;
  1988. $text = $pkc_encoder->encode($text);
  1989. mcrypt_generic_init($module, $this->key, $iv);
  1990. //加密
  1991. $encrypted = mcrypt_generic($module, $text);
  1992. mcrypt_generic_deinit($module);
  1993. mcrypt_module_close($module);
  1994. // print(base64_encode($encrypted));
  1995. //使用BASE64对加密后的字符串进行编码
  1996. return array(ErrorCode::$OK, base64_encode($encrypted));
  1997. } catch (Exception $e) {
  1998. //print $e;
  1999. return array(ErrorCode::$EncryptAESError, null);
  2000. }
  2001. }
  2002. /**
  2003. * 对密文进行解密
  2004. * @param string $encrypted 需要解密的密文
  2005. * @return string 解密得到的明文
  2006. */
  2007. public function decrypt($encrypted, $appid)
  2008. {
  2009. try {
  2010. //使用BASE64对需要解密的字符串进行解码
  2011. $ciphertext_dec = base64_decode($encrypted);
  2012. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2013. $iv = substr($this->key, 0, 16);
  2014. mcrypt_generic_init($module, $this->key, $iv);
  2015. //解密
  2016. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  2017. mcrypt_generic_deinit($module);
  2018. mcrypt_module_close($module);
  2019. } catch (Exception $e) {
  2020. return array(ErrorCode::$DecryptAESError, null);
  2021. }
  2022. try {
  2023. //去除补位字符
  2024. $pkc_encoder = new PKCS7Encoder;
  2025. $result = $pkc_encoder->decode($decrypted);
  2026. //去除16位随机字符串,网络字节序和AppId
  2027. if (strlen($result) < 16)
  2028. return "";
  2029. $content = substr($result, 16, strlen($result));
  2030. $len_list = unpack("N", substr($content, 0, 4));
  2031. $xml_len = $len_list[1];
  2032. $xml_content = substr($content, 4, $xml_len);
  2033. $from_appid = substr($content, $xml_len + 4);
  2034. if (!$appid)
  2035. $appid = $from_appid;
  2036. //如果传入的appid是空的,则认为是订阅号,使用数据中提取出来的appid
  2037. } catch (Exception $e) {
  2038. //print $e;
  2039. return array(ErrorCode::$IllegalBuffer, null);
  2040. }
  2041. if ($from_appid != $appid)
  2042. return array(ErrorCode::$ValidateAppidError, null);
  2043. //不注释上边两行,避免传入appid是错误的情况
  2044. return array(0, $xml_content, $from_appid); //增加appid,为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
  2045. }
  2046. /**
  2047. * 随机生成16位字符串
  2048. * @return string 生成的字符串
  2049. */
  2050. function getRandomStr()
  2051. {
  2052. $str = "";
  2053. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  2054. $max = strlen($str_pol) - 1;
  2055. for ($i = 0; $i < 16; $i++) {
  2056. $str .= $str_pol[mt_rand(0, $max)];
  2057. }
  2058. return $str;
  2059. }
  2060. }
  2061. /**
  2062. * error code
  2063. * 仅用作类内部使用,不用于官方API接口的errCode码
  2064. */
  2065. class ErrorCode
  2066. {
  2067. public static $OK = 0;
  2068. public static $ValidateSignatureError = 40001;
  2069. public static $ParseXmlError = 40002;
  2070. public static $ComputeSignatureError = 40003;
  2071. public static $IllegalAesKey = 40004;
  2072. public static $ValidateAppidError = 40005;
  2073. public static $EncryptAESError = 40006;
  2074. public static $DecryptAESError = 40007;
  2075. public static $IllegalBuffer = 40008;
  2076. public static $EncodeBase64Error = 40009;
  2077. public static $DecodeBase64Error = 40010;
  2078. public static $GenReturnXmlError = 40011;
  2079. public static $errCode=array(
  2080. '0' => '处理成功',
  2081. '40001' => '校验签名失败',
  2082. '40002' => '解析xml失败',
  2083. '40003' => '计算签名失败',
  2084. '40004' => '不合法的AESKey',
  2085. '40005' => '校验AppID失败',
  2086. '40006' => 'AES加密失败',
  2087. '40007' => 'AES解密失败',
  2088. '40008' => '公众平台发送的xml不合法',
  2089. '40009' => 'Base64编码失败',
  2090. '40010' => 'Base64解码失败',
  2091. '40011' => '公众帐号生成回包xml失败'
  2092. );
  2093. public static function getErrText($err) {
  2094. if (isset(self::$errCode[$err])) {
  2095. return self::$errCode[$err];
  2096. }else {
  2097. return false;
  2098. };
  2099. }
  2100. }