wechat.class.php 65 KB

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