wechat.class.php 65 KB

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