Wechat.class.php 65 KB

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