service == null) { $this->service = new WeChatService(); } return $this->service; } /** * Des:开放给微信调用的接口 * Name: indexAction * @return bool|string * @author 倪宗锋 */ public function actionIndex() { if (isset($_GET['echostr'])) {//首次校验 $check = $this->getService()->valid(); return $check; } return $this->getService()->exec(); } /** * Des:设置菜单 * Name: setMenuAction * @author 倪宗锋 */ public function actionSetMenu() { $access_token = $this->getService()->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token; $wechatConfig = Util::getWeChatConfig(); $data = require ROOT_PATH . '/common/config/wechatConfig/wxInterface/'.$wechatConfig['mch_id'].'/wxMenu.config.php'; $result = $this->getService()->_requestPost($url, $data); print_r($result); } /** * Des:获取素材ID * Name: getMediaAction * @author 倪宗锋 */ public function actionGetMedia() { $type = $this->_get('type', 'news');//素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news) $list = $this->getMediaList($type); include ROOT_PATH.'/common/config/wechatConfig/getMedia.phtml'; return ''; } /** * @param $type * @return array */ public function getMediaList($type) { $clear = $this->_get('clear', ''); $cache = \Yii::$app->getCache(); $wxConfig = Util::getWeChatConfig(); $keys = $wxConfig['appid'] . 'wxMediaList'; if ($clear == 'clear') { $cache->delete($keys); } $wxMediaList = $cache->get($keys); $access_token = $this->getService()->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" . $access_token; $data = '{"type":"' . $type . '","offset":0,"count":20}'; $result = $this->getService()->httpRequest($url, $data); $return = json_decode($result, true); $list = array(); if (isset($return['item'])) { $list = $return['item']; } foreach ($list as $key => $val) { if ($type == 'news') { $list[$key] = $this->setNewsShow($val); } } $wxMediaList[$type] = $list; $cache->set($keys, $wxMediaList, 60 * 10);//缓存10分钟 return $list; } public function actionClear() { $cache = \Yii::$app->getCache(); $wxConfig = Util::getWeChatConfig(); $keys = $wxConfig['appid'] . 'wxMediaList'; $cache->set($keys, array(), 60 * 10); } /** * Des: 设置图文展示 * Name: setNewsShow * @param $list * @return array * @author 倪宗锋 */ public function setNewsShow($list) { $listArr = $list['content']['news_item']; $title = ''; foreach ($listArr as $val) { if ($val['title']) { $title .= $val['title'] . '
'; } } $return = array( 'media_id' => $list['media_id'], 'name' => $title ); return $return; } }