appConfigs = $this->loadConfig(); $this->corpId = $this->appConfigs->CorpId; $this->agentId = $agentId; //由于通讯录是特殊的应用,需要单独处理 if ($agentId == "txl") { $this->secret = 'JV0C-B1T6e19y66EhAt_aU7t8iWTVtUUsfxbiQSRU-g'; $this->corpId = 'wwb1c5a9f70b4faecb'; } else { //其他应用 $config = $this->getConfigByAgentId($agentId); if ($config) { $this->secret = $config->Secret; } } } /** * User:Steven * Desc:给URL地址追加参数 * @param $url * @param $key * @param $value * @return string */ public function appendParamter($url, $key, $value) { return strrpos($url, "?", 0) > -1 ? "$url&$key=$value" : "$url?$key=$value"; } /** * User:Steven * Desc:生成指定长度的随机字符串 * @param int $length * @return string */ function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } /** * User:Steven * Desc:读取本地文件 * @param $filename * @return string */ function get_php_file($filename) { if (file_exists($filename)) { return trim(substr(file_get_contents($filename), 15)); } else { return '{"expire_time":0}'; } } /** * User:Steven * Desc:写入本地文件 * @param $filename * @param $content */ function set_php_file($filename, $content) { $fp = fopen($filename, "w"); fwrite($fp, "" . $content); fclose($fp); } /** * User:Steven * Desc:加载本地的应用配置文件 * @return mixed */ function loadConfig() { return json_decode($this->get_php_file(\Yii::getAlias('@backend') . "/config/wechat/config.php")); } /** * User:Steven * Desc:根据应用ID获取应用配置 * @param $id * @return mixed */ public function getConfigByAgentId($id) { $configs = $this->loadConfig(); foreach ($configs->AppsConfig as $key => $value) { if ($value->AgentId == $id) { $config = $value; break; } } return $config; } /** * User:Steven * Desc:获取access_token * @return mixed */ public function getAccessToken() { //由于实际使用过程中不同的应用会产生不同的token,所以示例按照agentId做为文件名进行存储 $path = \Yii::getAlias('@backend') . "/config/wechat/$this->agentId.php"; $data = json_decode($this->get_php_file($path)); if ($data->expire_time < time()) { $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->corpId&corpsecret=$this->secret"; $res = json_decode(Utils::http_get($url)["content"]); $access_token = $res->access_token; $data = (object)$data; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; $this->set_php_file($path, json_encode($data)); } } else { $access_token = $data->access_token; } return $access_token; } }