/PigCms/Lib/ORG/Wechat.class.php
PHP | 323 lines | 247 code | 31 blank | 45 comment | 36 complexity | 93c831b2ed42a2c50eca9239902094b5 MD5 | raw file
- <?php
- class Wechat {
- public $token;
- public $wxuser;
- public $pigsecret;
- private $data = array();
- public function __construct($token, $wxuser = ''){
- $this->auth($token, $wxuser) || exit;
- $this->token = $token;
- $this->wxuser = $wxuser;
-
- if (!$this->wxuser['encoding_aes_key']) {
- $this->pigsecret = $this->token;
- }
- else{
- $this->pigsecret = $this->wxuser['encoding_aes_key'];
- }
- //https://wx.handday.com/appproxy/books/65804
- //658043CD96864573B8B1BAD1AC1ECC65
- //132009d373093fd544acdc00e2f260daf38fe41b000
-
- if (IS_GET) {
- $xml = file_get_contents("php://input");
- if ($this->wxuser['public_type'] == "企业号") {
- import("@.ORG.aes.WXBizMsgCrypt");
- $sReqMsgSig = $_GET['msg_signature'];
- $sReqTimeStamp = $_GET['timestamp'];
- $sReqNonce = $_GET['nonce'];
- $sReqData = $msg;
- $sEchoStr = "";
- $pc = new WXBizMsgCrypt($this->wxuser['token'], $this->pigsecret, $this->wxuser['app_id']);
- $errCode = $pc->VerifyURL($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $_GET['echostr'], $sEchoStr);
-
- echo $sEchoStr;
- exit;
- }
- else if ($_GET['echostr']){
- echo $_GET['echostr'];
- exit;
- }
- else{
- \Log::write("@@@@@@@@@@@@@@@",'WARN');
- exit;
- }
-
- }else {
-
- $xml = file_get_contents("php://input");
- if ($this->wxuser['public_type'] == '企业号') {
- \Log::write("1111####",'WARN');
- $this->data = $this->decodeMsg($xml);
- }else {
-
-
- $xml = new SimpleXMLElement($xml);
- $xml || exit;
- foreach ($xml as $key => $value) {
- $this->data[$key] = strval($value);
- }
- }
- }
- }
- public function encodeMsg($sRespData) {
- $sReqTimeStamp = time();
- $sReqNonce = $_GET['nonce'];
- $encryptMsg = "";
- import("@.ORG.aes.WXBizMsgCrypt");
- $pc = new WXBizMsgCrypt($this->wxuser['token'], $this->pigsecret, $this->wxuser['app_id']);
-
- $sRespData = str_replace('<?xml version="1.0"?>', '', $sRespData);
- $errCode = $pc->encryptMsg($sRespData, $sReqTimeStamp, $sReqNonce, $encryptMsg);
- //\Log::write($errCode,'WARN');
- if ($errCode == 0) {
- return $encryptMsg;
- }else {
- return $errCode;
- }
- }
- public function decodeMsg($msg) {
- import("@.ORG.aes.WXBizMsgCrypt");
- $sReqMsgSig = $_GET['msg_signature'];
- $sReqTimeStamp = $_GET['timestamp'];
- $sReqNonce = $_GET['nonce'];
- $sReqData = $msg;
- $sMsg = "";
- \Log::write("decodeMsg:token=".$this->wxuser['token']
- ."secret=".$this->pigsecret."app_id=".$this->wxuser['app_id'],'WARN');
- $pc = new WXBizMsgCrypt($this->wxuser['token'], $this->pigsecret, $this->wxuser['app_id']);
- $errCode = $pc->decryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
- if ($errCode == 0) {
- $data = array();
- $xml = new SimpleXMLElement($sMsg);
- $xml || exit;
- foreach ($xml as $key => $value) {
- $data[$key] = strval($value);
- }
- return $data;
- }else {
- return $errCode;
- }
- }
- /**
- * 获取微信推送的数据
- * @return array 转换为数组后的数据
- */
- public function request(){
- return $this->data;
- }
-
- /**
- * * 响应微信发送的信息(自动回复)
- * @param string $to 接收用户名
- * @param string $from 发送者用户名
- * @param array $content 回复信息,文本信息为string类型
- * @param string $type 消息类型
- * @param string $flag 是否新标刚接受到的信息
- * @return string XML字符串
- */
- public function response($content, $type = 'text', $flag = 0){
- /* 基础数据 */
- $this->data = array(
- 'ToUserName' => $this->data['FromUserName'],
- 'FromUserName' => $this->data['ToUserName'],
- 'CreateTime' => NOW_TIME,
- 'MsgType' => $type,
- );
-
- /* 添加类型数据 */
- $this->$type($content);
-
-
-
- /* 转换数据为XML */
- $xml = new SimpleXMLElement('<xml></xml>');
-
- if ($this->wxuser['public_type'] == '企业号') {
- $this->data2xml($xml, $this->data);
- //\Log::write($xml->asXML(),'WARN');
- exit($this->encodeMsg($xml->asXML()));
- }else {
- /* 添加状态 */
- $this->data['FuncFlag'] = $flag;
- $this->data2xml($xml, $this->data);
- //\Log::write($xml->asXML(),'WARN');
- exit($xml->asXML());
- }
- }
- /**
- * 回复文本信息
- * @param string $content 要回复的信息
- */
- private function text($content){
- $this -> data['Content'] = $content;
- }
-
- /**
- * 回复音乐信息
- * @param string $content 要回复的音乐
- */
- private function music($music){
- list(
- $music['Title'],
- $music['Description'],
- $music['MusicUrl'],
- $music['HQMusicUrl']
- ) = $music;
- $this->data['Music'] = $music;
- }
-
- /**
- * 回复图文信息
- * @param string $news 要回复的图文内容
- */
- private function news($news){
- $articles = array();
- foreach ($news as $key => $value) {
- list(
- $articles[$key]['Title'],
- $articles[$key]['Description'],
- $articles[$key]['PicUrl'],
- $articles[$key]['Url']
- ) = $value;
- if($key >= 9) { break; } //最多只允许10调新闻
- }
- $this->data['ArticleCount'] = count($articles);
- $this->data['Articles'] = $articles;
- }
- private function transfer_customer_service($content){
- $this->data['Content'] = '';
- }
-
- private function data2xml($xml, $data, $item = 'item') {
- foreach ($data as $key => $value) {
- /* 指定默认的数字key */
- is_numeric($key) && $key = $item;
-
- /* 添加子元素 */
- if(is_array($value) || is_object($value)){
- $child = $xml->addChild($key);
- $this->data2xml($child, $value, $item);
- } else {
- if(is_numeric($value)){
- $child = $xml->addChild($key, $value);
- } else {
- $child = $xml->addChild($key);
- $node = dom_import_simplexml($child);
- $node->appendChild($node->ownerDocument->createCDATASection($value));
- }
- }
- }
- }
- private function auth($token, $wxuser = ''){
- $signature = $_GET["signature"];
- $timestamp = $_GET["timestamp"];
- $nonce = $_GET["nonce"];
- $tmpArr = array($token, $timestamp, $nonce);
- sort($tmpArr, SORT_STRING);
- $tmpStr = implode($tmpArr);
- $tmpStr = sha1($tmpStr);
- if(trim($tmpStr) == trim($signature)){
- return true;
- }else{
- return true;
- }
- return true;
- }
-
- public function getSignPackage() {
- $jsapiTicket = $this->getJsApiTicket();
-
- // 注意 URL 一定要动态获取,不能 hardcode.
- $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
- $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
-
- $timestamp = time();
- $nonceStr = $this->createNonceStr();
-
- // 这里参数的顺序要按照 key 值 ASCII 码升序排序
- $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
-
- $signature = sha1($string);
-
- $signPackage = array(
- "appId" => $this->appId,
- "nonceStr" => $nonceStr,
- "timestamp" => $timestamp,
- "url" => $url,
- "signature" => $signature,
- "rawString" => $string
- );
- return $signPackage;
- }
-
- private 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;
- }
-
- private function getJsApiTicket() {
- // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
- $data = json_decode(file_get_contents("jsapi_ticket.json"));
- if ($data->expire_time < time()) {
- $accessToken = $this->getAccessToken();
- // 如果是企业号用以下 URL 获取 ticket
- // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
- $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
- $res = json_decode($this->httpGet($url));
- $ticket = $res->ticket;
- if ($ticket) {
- $data->expire_time = time() + 7000;
- $data->jsapi_ticket = $ticket;
- $fp = fopen("jsapi_ticket.json", "w");
- fwrite($fp, json_encode($data));
- fclose($fp);
- }
- } else {
- $ticket = $data->jsapi_ticket;
- }
-
- return $ticket;
- }
-
- private function getAccessToken() {
- // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
- $data = json_decode(file_get_contents("access_token.json"));
- if ($data->expire_time < time()) {
- // 如果是企业号用以下URL获取access_token
- // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
- $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
- $res = json_decode($this->httpGet($url));
- $access_token = $res->access_token;
- if ($access_token) {
- $data->expire_time = time() + 7000;
- $data->access_token = $access_token;
- $fp = fopen("access_token.json", "w");
- fwrite($fp, json_encode($data));
- fclose($fp);
- }
- } else {
- $access_token = $data->access_token;
- }
- return $access_token;
- }
-
- private function httpGet($url) {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_TIMEOUT, 500);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($curl, CURLOPT_URL, $url);
-
- $res = curl_exec($curl);
- curl_close($curl);
-
- return $res;
- }
- }
- ?>