From 7f138ef2551b97ebd2f69d54435681a53bdc612d Mon Sep 17 00:00:00 2001 From: "as2252258@163.com" Date: Mon, 11 Nov 2019 18:14:47 +0800 Subject: [PATCH] add clear --- Container.php | 96 ++++++ README.md | 2 +- {wx => common}/Config.php | 39 ++- common/Decode.php | 99 +++++++ {wx => common}/Help.php | 2 +- wx/WxClient.php => common/HttpClient.php | 290 ++++++++++++------ {wx => common}/Miniprogarampage.php | 67 ++++- common/Progaram.php | 10 + {wx => common}/Result.php | 12 +- composer.json | 9 +- officialaccount/AccessToken.php | 12 + officialaccount/AfficialAccount.php | 36 +++ officialaccount/Authorization.php | 104 +++++++ officialaccount/NewsManager.php | 178 +++++++++++ officialaccount/QrCode.php | 75 +++++ officialaccount/SourceMaterial.php | 100 +++++++ officialaccount/Subscribe.php | 118 ++++++++ officialaccount/Tag.php | 30 ++ officialaccount/WxSDK.php | 41 +++ officialaccount/dcaler/Authorization.php | 360 +++++++++++++++++++++++ officialaccount/dcaler/PKCS7Encoder.php | 46 +++ officialaccount/dcaler/Prpcrypt.php | 119 ++++++++ officialaccount/dcaler/SnsInfo.php | 204 +++++++++++++ officialaccount/dcaler/XMLParse.php | 49 +++ qq/Account.php | 174 +---------- qq/GamePrePay.php | 13 + qq/Message.php | 314 -------------------- qq/Notify.php | 5 +- qq/PublicTemplate.php | 157 ---------- qq/QqSDK.php | 116 -------- qq/QrCode.php | 117 ++++++++ qq/Recharge.php | 11 +- qq/SmallProgram.php | 36 +++ qq/Subject.php | 136 +++++++++ qq/Template.php | 7 +- qq/Token.php | 21 +- test.php | 72 +++-- wx/Account.php | 53 ++-- wx/Message.php | 9 +- wx/Notify.php | 2 +- wx/PublicTemplate.php | 4 +- wx/Recharge.php | 5 +- wx/SmallProgram.php | 38 +++ wx/Subject.php | 4 +- wx/Template.php | 4 +- wx/Token.php | 21 +- wx/Wx.php | 123 -------- 47 files changed, 2440 insertions(+), 1100 deletions(-) create mode 100644 Container.php rename {wx => common}/Config.php (91%) create mode 100644 common/Decode.php rename {wx => common}/Help.php (98%) rename wx/WxClient.php => common/HttpClient.php (61%) rename {wx => common}/Miniprogarampage.php (73%) create mode 100644 common/Progaram.php rename {wx => common}/Result.php (93%) create mode 100644 officialaccount/AccessToken.php create mode 100644 officialaccount/AfficialAccount.php create mode 100644 officialaccount/Authorization.php create mode 100644 officialaccount/NewsManager.php create mode 100644 officialaccount/QrCode.php create mode 100644 officialaccount/SourceMaterial.php create mode 100644 officialaccount/Subscribe.php create mode 100644 officialaccount/Tag.php create mode 100644 officialaccount/WxSDK.php create mode 100644 officialaccount/dcaler/Authorization.php create mode 100644 officialaccount/dcaler/PKCS7Encoder.php create mode 100644 officialaccount/dcaler/Prpcrypt.php create mode 100644 officialaccount/dcaler/SnsInfo.php create mode 100644 officialaccount/dcaler/XMLParse.php create mode 100644 qq/GamePrePay.php delete mode 100644 qq/Message.php delete mode 100644 qq/PublicTemplate.php delete mode 100644 qq/QqSDK.php create mode 100644 qq/QrCode.php create mode 100644 qq/SmallProgram.php create mode 100644 qq/Subject.php create mode 100644 wx/SmallProgram.php delete mode 100644 wx/Wx.php diff --git a/Container.php b/Container.php new file mode 100644 index 0000000..7260f62 --- /dev/null +++ b/Container.php @@ -0,0 +1,96 @@ +generate($config); + + if (static::$_instance->exists($class)) { + return static::$_instance->get($class); + } else { + return static::$_instance->generate($config); + } + } + + /** + * @param \common\Config $config + * @return $this + */ + public function generate(Config $config) + { + $this->config = $config; + return $this; + } + + + /** + * @param $class + * @return object|ReflectionClass + * @throws ReflectionException + * @throws Exception + */ + private function createObject($class) + { + $newInstance = new \ReflectionClass($class); + if (!$newInstance->isInstantiable()) { + throw new Exception('Class Con\'t instance.'); + } + $newInstance = $newInstance->newInstance(); + if (method_exists($newInstance, 'initConfig')) { + $newInstance->initConfig($this->config); + } + + $this->container[$class] = $newInstance; + return $newInstance; + } + + + /** + * @param $name + * @return mixed + */ + public function get($name) + { + return $this->container[$name]; + } + + /** + * @param $name + * @return bool + */ + public function exists($name) + { + return array_key_exists($name, $this->container) && $this->container[$name] instanceof Progaram; + } + +} diff --git a/README.md b/README.md index 0da3ecb..f56dfd9 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ ```php -$config = new \wchat\Config(); +$config = new \common\Config(); $config->setAppid(''); $config->setAppsecret(''); $config->setMchId(''); diff --git a/wx/Config.php b/common/Config.php similarity index 91% rename from wx/Config.php rename to common/Config.php index 483eb8f..1f80786 100644 --- a/wx/Config.php +++ b/common/Config.php @@ -1,7 +1,7 @@ token; + } + /** + * @param mixed $token + * @return Config + */ + public function setToken($token) + { + $this->token = $token; + return $this; + } + + /** + * @return mixed + */ + public function getEncodingAesKey() + { + return $this->encodingAesKey; + } + + /** + * @param mixed $encodingAesKey + * @return Config + */ + public function setEncodingAesKey($encodingAesKey) + { + $this->encodingAesKey = $encodingAesKey; + return $this; + } /** * @return string diff --git a/common/Decode.php b/common/Decode.php new file mode 100644 index 0000000..9018b4f --- /dev/null +++ b/common/Decode.php @@ -0,0 +1,99 @@ +sessionKey = $sessionKey; + return $this; + } + + /** + * @param mixed $iv + * @return Decode + */ + public function setIv($iv) + { + $this->iv = $iv; + return $this; + } + + /** + * @param mixed $encryptedData + * @return Decode + */ + public function setEncryptedData($encryptedData) + { + $this->encryptedData = $encryptedData; + return $this; + } + + /** + * @param mixed $appId + * @return Decode + */ + public function setAppId($appId) + { + $this->appId = $appId; + return $this; + } + + + /** + * @param $asArray + * @return array|mixed + * @throws \Exception + */ + public function decode($asArray) + { + if (strlen($this->sessionKey) != 24) { + throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey); + } + + $aesKey = base64_decode($this->sessionKey); + if (strlen($this->iv) != 24) { + throw new \Exception('base64解密失败', $this->IllegalIv); + } + + $aesIV = base64_decode($this->iv); + $aesCipher = base64_decode($this->encryptedData); + $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV); + if ($result === false) { + throw new \Exception('aes 解密失败', $this->IllegalBuffer); + } + + $dataObj = json_decode($result); + if ($dataObj->watermark->appid != $this->appId) { + throw new \Exception('aes 解密失败', $this->IllegalBuffer); + } + + if ($asArray) { + return get_object_vars($dataObj); + } + + return $dataObj; + + } + +} diff --git a/wx/Help.php b/common/Help.php similarity index 98% rename from wx/Help.php rename to common/Help.php index a4aa54e..4ddb35e 100644 --- a/wx/Help.php +++ b/common/Help.php @@ -1,7 +1,7 @@ errorCodeField = $name; + return $this; + } + + /** + * @param string $name + * @return $this + */ + public function setErrorMsgField(string $name) + { + $this->errorMsgField = $name; + return $this; + } + /** * @param string $host */ @@ -102,11 +128,22 @@ class WxClient $this->isSSL = $isSSL; } + /** + * @return bool + */ public function getIsSSL() { return $this->isSSL; } + /** + * @param bool $isFIle + * 设置返回类型 + */ + public function asFileStream($isFIle = true) + { + $this->isFileStream = $isFIle; + } /** * @param $url @@ -116,23 +153,13 @@ class WxClient */ private function request($url, $data = []) { + $data = $this->paramEncode($data); if (function_exists('getIsCli') && getIsCli()) { - if (strpos($url, 'http://') !== FALSE) { - $url = str_replace('http://', '', $url); - } else if (strpos($url, 'https://') !== FALSE) { - $url = str_replace('https://', '', $url); - } - $explode = explode('/', $url); - $ip = System::gethostbyname(array_shift($explode)); - return $this->coroutine($ip, $url, $data); + return $this->coroutine($this->parseUrlHost($url), $url, $data); } - if ( - strpos($url, 'http://') === 0 || - strpos($url, 'https://') === 0 - ) { + if ($this->isHttp($url) || $this->isHttps($url)) { return $this->curl($url, $data); } - if ($this->isSSL) { return $this->curl('https://' . $this->host . '/' . $url, $data); } else { @@ -140,6 +167,40 @@ class WxClient } } + /** + * @param $url + * @return string + */ + private function parseUrlHost(&$url) + { + if ($this->isHttp($url)) { + $url = str_replace('http://', '', $url); + } else if ($this->isHttps($url)) { + $url = str_replace('https://', '', $url); + } + $explode = explode('/', $url); + return System::gethostbyname(array_shift($explode)); + } + + /** + * @param $url + * @return bool + */ + private function isHttp($url) + { + return strpos($url, 'http://') === 0; + } + + /** + * @param $url + * @return bool + */ + private function isHttps($url) + { + return strpos($url, 'https://') === 0; + } + + /** * @param $ip * @param $url @@ -150,18 +211,15 @@ class WxClient */ private function coroutine($ip, $url, $data = []) { - $_data = $this->paramEncode($data); - if ($this->method == 'get' && is_array($_data)) { - $url .= '?' . http_build_query($_data); - } - $client = $this->getClient($ip, $this->getHostPort(), $url, $data); + $client = $this->generate_client($ip, $url, $data); if ($client->statusCode < 0) { throw new \Exception($client->errMsg); } + $body = $client->body; $client->close(); - return $this->structure($body, $_data); + return $this->structure($body, $data); } /** @@ -190,21 +248,19 @@ class WxClient * @param $data * @return Client */ - private function getClient($host, $port, $url, $data) + private function generate_client($host, $url, $data) { - $client = new Client($host, $port, $this->isSSL); + $client = new Client($host, $this->getHostPort(), $this->isSSL); if (!empty($this->agent)) { $this->header['User-Agent'] = $this->agent; } if (!empty($this->header)) { $client->setHeaders($this->header); } - switch (strtolower($this->method)) { - case self::GET: - $client->get($url); - break; - default: - $client->post($url, $data); + if (strtolower($this->method) == self::GET) { + $client->get($url . '?' . $data); + } else { + $client->post($url, $data); } return $client; } @@ -215,43 +271,11 @@ class WxClient * @return array|mixed|Result */ private function curl($url, $data = []) - { - $data = $this->paramEncode($data, self::POST); - $ch = $this->structureCurlRequest($url, $data); - - if ($this->method != self::GET) { - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - } else if ($this->method == self::POST) { - curl_setopt($ch, CURLOPT_POST, 1); - } - - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method)); - $output = curl_exec($ch); - if ($output === FALSE) { - return new Result(['code' => 500, 'message' => curl_error($ch)]); - } - curl_close($ch); - - return $this->structure($output, $data); - } - - /** - * @param $url - * @param $_data - * @return resource - */ - private function structureCurlRequest($url, $_data) { $ch = curl_init(); - if ($this->method == self::GET) { - if (is_array($_data)) { - $_data = http_build_query($_data); - } - $url = $url . '?' . $_data; - } - curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_URL, $this->createRequestUrl($url, $data)); curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 超时设置 - curl_setopt($ch, CURLOPT_HEADER, FALSE); + curl_setopt($ch, CURLOPT_HEADER, true); if (!empty($this->header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header); } @@ -267,66 +291,134 @@ class WxClient curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//返回内容 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向 curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); - return $ch; + + if ($this->method != self::GET) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + } else if ($this->method == self::POST) { + curl_setopt($ch, CURLOPT_POST, 1); + } + + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method)); + $output = curl_exec($ch); + curl_close($ch); + + if ($output === FALSE) { + return new Result(['code' => 500, 'message' => curl_error($ch)]); + } + list($header, $body) = explode("\r\n\r\n", $output, 2); + $header = explode(PHP_EOL, $header); + $status = (int)explode(' ', trim($header[0]))[1]; + $header = $this->headerFormat($header); + + if ($status != 200) { + return new Result(['code' => 500, 'message' => $body, 'header' => $header]); + } + + return $this->structure($this->resolve($header, $body), $data, $header); + } + + /** + * @param $url + * @param $data + * @return string + */ + private function createRequestUrl($url, $data) + { + if ($this->isGet()) { + return $url . '?' . $data; + } + return $url; + } + + /** + * @param $data + * @param $body + * @return mixed + */ + private function resolve($data, $body) + { + if (strpos('json', $data['Content-Type']) !== false) { + return json_decode($body, true); + } else if (strpos('xml', $data['Content-Type']) !== false) { + $data = simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA); + return json_decode(json_encode($data), TRUE); + } else if (strpos('plain', $data['Content-Type']) !== false) { + return json_decode($data, TRUE); + } else { + return $body; + } + } + + /** + * @param $headers + * @return array + */ + private function headerFormat($headers) + { + $_tmp = []; + foreach ($headers as $key => $val) { + $trim = explode(': ', trim($val)); + + $_tmp[$trim[0]] = $trim[1] ?? ''; + } + return $_tmp; } /** * @param $body * @param $_data + * @param $header * @return array|mixed|Result * 构建返回体 */ - private function structure($body, $_data) + private function structure($body, $_data, $header = []) { $this->setIsSSL(false); $this->setHeaders([]); if ($this->callback !== NULL) { - $result = call_user_func($this->callback, $body, $_data); - } else { - $result = $this->formatResponseBody($body); - } + $result = call_user_func($this->callback, $body, $_data, $header); + $this->setCallback(null); - $this->setCallback(null); - if (!is_array($result)) { return $result; } + if (!is_array($body)) { + return $body; + } + $result['code'] = $body[$this->errorCodeField] ?? 0; + $result['message'] = $body[$this->errorMsgField] ?? 'system success.'; + $result['data'] = $body; + $result['header'] = $header; return new Result($result); } /** - * @param $body - * @return array|Result + * @return bool + * check isPost Request */ - private function formatResponseBody($body) + public function isPost() { - $result = []; - if (is_null($results = json_decode($body, TRUE))) { - $data = simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA); - $results = json_decode(json_encode($data), TRUE); - } - if (!is_array($results)) { - $result = new Result(['code' => 505, 'message' => '服务器返回体错误!']); - } else if (isset($results['errcode'])) { - $result['code'] = $results['errcode']; - $result['message'] = $results['errmsg']; - } else { - $result['code'] = 0; - $result['message'] = 'system success.'; - $result['data'] = $results; - } - return $result; + return strtolower($this->method) === self::POST; + } + + /** + * @return bool + * + * check isGet Request + */ + public function isGet() + { + return strtolower($this->method) === self::GET; } /** * @param $arr - * @param string $pushType * * @return array|string * 将请求参数进行编码 */ - private function paramEncode($arr, $pushType = 'post') + private function paramEncode($arr) { if (!is_array($arr)) { return $arr; @@ -335,8 +427,10 @@ class WxClient foreach ($arr as $Key => $val) { $_tmp[$Key] = $val; } - - return ($pushType == 'post' ? $_tmp : http_build_query($_tmp)); + if ($this->isGet()) { + return http_build_query($_tmp); + } + return $_tmp; } /** diff --git a/wx/Miniprogarampage.php b/common/Miniprogarampage.php similarity index 73% rename from wx/Miniprogarampage.php rename to common/Miniprogarampage.php index e882e24..a781922 100644 --- a/wx/Miniprogarampage.php +++ b/common/Miniprogarampage.php @@ -6,9 +6,11 @@ * Time: 10:23 */ -namespace wchat; +namespace common; -abstract class Miniprogarampage +use common\Config; + +abstract class Miniprogarampage implements Progaram { /** @var Config */ @@ -17,15 +19,61 @@ abstract class Miniprogarampage /** @var Miniprogarampage $instance */ protected static $instance = null; - /** @var WxClient */ + /** @var HttpClient */ protected $request = null; + protected $errorCode = 0; + protected $errorMsg = ''; + + + /** + * @param $message + * @param int $code + * @return Result + */ + protected function sendError($message, $code = 500) + { + return new Result(['code' => $code, 'message' => $message]); + } + + /** + * @param $code + */ + public function setErrorCode($code) + { + $this->errorCode = $code; + } + + /** + * @param $message + */ + public function setErrorMessage($message) + { + $this->errorMsg = $message; + } + + /** + * @return int + */ + public function getErrorCode() + { + return $this->errorCode; + } + + /** + * @return string + */ + public function getErrorMessage() + { + return $this->errorMsg; + } + /** * Miniprogarampage constructor. */ private function __construct() { - $this->request = WxClient::getInstance(); + $this->request = HttpClient::NewRequest(); $this->request->setIsSSL(true); } @@ -49,6 +97,15 @@ abstract class Miniprogarampage return static::$instance; } + /** + * @param Config $config + * @return $this + */ + public function initConfig($config) + { + $this->config = $config; + return $this; + } /** * @return bool|mixed|string @@ -60,7 +117,7 @@ abstract class Miniprogarampage if (!empty($access)) { return $access; } - $this->request->setMethod(WxClient::GET); + $this->request->setMethod(HttpClient::GET); $data = $this->request->get('/cgi-bin/token', [ 'grant_type' => 'client_credential', 'appid' => $this->config->getAppid(), diff --git a/common/Progaram.php b/common/Progaram.php new file mode 100644 index 0000000..44cdca7 --- /dev/null +++ b/common/Progaram.php @@ -0,0 +1,10 @@ + $this->startTime, + 'startTime' => $this->startTime, 'requestTime' => $this->requestTime, - 'runTime' => $this->runTime, + 'runTime' => $this->runTime, ]; } @@ -144,11 +144,17 @@ class Result return $this; } + /** + * @return mixed + */ public function getMessage() { return $this->message; } + /** + * @return mixed + */ public function getCode() { return $this->code; diff --git a/composer.json b/composer.json index 6031c25..ea1f56c 100644 --- a/composer.json +++ b/composer.json @@ -14,8 +14,13 @@ "autoload": { "psr-4": { "wchat\\": "wx", - "qq\\": "qq" - } + "qq\\": "qq", + "common\\": "common", + "officialaccount\\": "officialaccount" + }, + "files": [ + "Container.php" + ] }, "require": { "php": ">= 7.0" diff --git a/officialaccount/AccessToken.php b/officialaccount/AccessToken.php new file mode 100644 index 0000000..a37040a --- /dev/null +++ b/officialaccount/AccessToken.php @@ -0,0 +1,12 @@ +config->getToken())) { + return $this->config->getToken(); + } + $requestParam['grant_type'] = 'client_credential'; + $requestParam['appid'] = $this->config->getAppid(); + $requestParam['secret'] = $this->config->getAppsecret(); + + $result = HttpClient::NewRequest()->get($this->url, $requestParam); + if (!$result->isResultsOK()) { + throw new \Exception($result->getMessage(), $result->getCode()); + } + return $result->getData(); + } + +} diff --git a/officialaccount/Authorization.php b/officialaccount/Authorization.php new file mode 100644 index 0000000..7211933 --- /dev/null +++ b/officialaccount/Authorization.php @@ -0,0 +1,104 @@ +GetAccessTokenByCode($code); + if (!$param->isResultsOK()) { + throw new \Exception($param->getMessage()); + } + + $requestParam['access_token'] = $param->getData('access_token'); + $requestParam['openid'] = $param->getData('openid'); + $requestParam['lang'] = 'zh_CN'; + + $client = HttpClient::NewRequest(); + $result = $client->get($this->snsUserInfo, $requestParam); + if ($result->isResultsOK()) { + return $result; + } + + $userInfo = SnsInfo::instance($result->getData()); + $result->append('instance', $userInfo); + + return $result; + } + + /** + * @param $code + * @return array|mixed|\wchat\Result + */ + private function GetAccessTokenByCode($code) + { + $requestParam['appid'] = $this->config->getAppid(); + $requestParam['secret'] = $this->config->getAppsecret(); + $requestParam['code'] = $code; + $requestParam['grant_type'] = 'authorization_code'; + + $client = HttpClient::NewRequest(); + return $client->get($this->oauth2, $requestParam); + } + + /** + * @param $openid + * @return DAuth + * @throws \Exception + * 获取用户信息 + */ + public function To_grant_authorization($openid) + { + $requestParam['access_token'] = $this->config->getAccessToken(); + $requestParam['openid'] = $openid; + $requestParam['lang'] = 'zh_CN'; + + $authorization = $this->request->get($this->url, $requestParam); + if (!$authorization) { + throw new \Exception($authorization->getMessage()); + } + + return DAuth::instance($authorization->getData()); + } + + + /** + * @param $long_url + * @return string + * @throws \Exception + */ + public function Turn_to_short_chain($long_url) + { + $token = $this->config->getAccessToken(); + $requestParam['action'] = 'long2short'; + $requestParam['long_url'] = $long_url; + + $result = $this->request->post($this->turn . $token, $requestParam); + if (!$result->isResultsOK()) { + throw new \Exception($result->getMessage()); + } + return $result->getData('short_url'); + } + +} diff --git a/officialaccount/NewsManager.php b/officialaccount/NewsManager.php new file mode 100644 index 0000000..d5ed781 --- /dev/null +++ b/officialaccount/NewsManager.php @@ -0,0 +1,178 @@ + '签名验证错误', + self::ParseXmlError => 'xml解析失败', + self::ComputeSignatureError => 'sha加密生成签名失败', + self::IllegalAesKey => 'encodingAesKey 非法', + self::ValidateAppidError => 'appid 校验错误', + self::EncryptAESError => 'aes 加密失败', + self::DecryptAESError => 'aes 解密失败', + self::IllegalBuffer => '解密后得到的buffer非法', + self::EncodeBase64Error => 'base64加密失败', + self::DecodeBase64Error => 'base64解密失败', + self::GenReturnXmlError => '生成xml失败', + ]; + return $messages[$code] ?? 'OK'; + } + + /** + * 将公众平台回复用户的消息加密打包. + *
    + *
  1. 对要发送的消息进行AES-CBC加密
  2. + *
  3. 生成安全签名
  4. + *
  5. 将消息密文和安全签名打包成xml格式
  6. + *
+ * + * @param $replyMsg string 公众平台待回复用户的消息,xml格式的字符串 + * @param $timeStamp string 时间戳,可以自己生成,也可以用URL参数的timestamp + * @param $nonce string 随机串,可以自己生成,也可以用URL参数的nonce + * @param &$encryptMsg string 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串, + * 当return返回0时有效 + * + * @return int 成功0,失败返回对应的错误码 + */ + public function encryptMsg($replyMsg, $timeStamp, $nonce, &$encryptMsg) + { + $pc = new Prpcrypt($this->config->getEncodingAesKey()); + + //加密 + $array = $pc->encrypt($replyMsg, $this->config->getAppid()); + $ret = $array[0]; + if ($ret != 0) { + return $ret; + } + + if ($timeStamp == null) { + $timeStamp = time(); + } + $encrypt = $array[1]; + + //生成安全签名 + $array = $this->getSHA1($this->config->getToken(), $timeStamp, $nonce, $encrypt); + $ret = $array[0]; + if ($ret != 0) { + return $ret; + } + $signature = $array[1]; + + //生成发送的xml + $xmlparse = new XMLParse; + $encryptMsg = $xmlparse->generate($encrypt, $signature, $timeStamp, $nonce); + return self::OK; + } + + + /** + * 检验消息的真实性,并且获取解密后的明文. + *
    + *
  1. 利用收到的密文生成安全签名,进行签名验证
  2. + *
  3. 若验证通过,则提取xml中的加密消息
  4. + *
  5. 对消息进行解密
  6. + *
+ * + * @param $msgSignature string 签名串,对应URL参数的msg_signature + * @param $timestamp string 时间戳 对应URL参数的timestamp + * @param $nonce string 随机串,对应URL参数的nonce + * @param $postData string 密文,对应POST请求的数据 + * @param &$msg string 解密后的原文,当return返回0时有效 + * + * @return int 成功0,失败返回对应的错误码 + */ + public function decryptMsg($msgSignature, $timestamp, $nonce, $postData, &$msg) + { + if (strlen($this->config->getEncodingAesKey()) != 43) { + return self::IllegalAesKey; + } + + $pc = new Prpcrypt($this->config->getEncodingAesKey()); + + //提取密文 + $xmlparse = new XMLParse(); + $array = $xmlparse->extract($postData); + $ret = $array[0]; + + if ($ret != 0) { + return $ret; + } + + if ($timestamp == null) { + $timestamp = time(); + } + + $encrypt = $array[1]; + $touser_name = $array[2]; + + //验证安全签名 + $array = $this->getSHA1($this->config->getToken(), $timestamp, $nonce, $encrypt); + $ret = $array[0]; + + if ($ret != 0) { + return $ret; + } + + $signature = $array[1]; + if ($signature != $msgSignature) { + return self::ValidateSignatureError; + } + + $result = $pc->decrypt($encrypt, $this->config->getAppid()); + if ($result[0] != 0) { + return $result[0]; + } + $msg = $result[1]; + + return self::OK; + } + + /** + * @param $token + * @param $timestamp + * @param $nonce + * @param $encrypt_msg + * @return array + */ + private function getSHA1($token, $timestamp, $nonce, $encrypt_msg) + { + //排序 + try { + $array = array($encrypt_msg, $token, $timestamp, $nonce); + sort($array, SORT_STRING); + $str = implode($array); + return array(self::OK, sha1($str)); + } catch (\Exception $e) { + //print $e . "\n"; + return array(self::ComputeSignatureError, null); + } + } + +} diff --git a/officialaccount/QrCode.php b/officialaccount/QrCode.php new file mode 100644 index 0000000..38315a0 --- /dev/null +++ b/officialaccount/QrCode.php @@ -0,0 +1,75 @@ +get_tick($requestParam); + + $client = HttpClient::NewRequest(); + return $client->get($this->temporary_url, ['ticket' => $tick]); + } + + + /** + * @param $scene_id + * @return array|mixed|\common\Result + * @throws \Exception + */ + public function permanent_qr_code($scene_id) + { + $requestParam['action_name'] = 'QR_LIMIT_SCENE'; + $requestParam['action_info[scene][scene_id]'] = $scene_id; + + $tick = $this->get_tick($requestParam); + + $client = HttpClient::NewRequest(); + return $client->get($this->permanent_qr_code_url, ['ticket' => $tick]); + } + + + /** + * @param $requestParam + * @return mixed + * @throws \Exception + * tick + */ + private function get_tick($requestParam) + { + $request = HttpClient::NewRequest(); + $request->setCallback(function ($body) { + if (is_array($body)) { + $param = ['code' => $body['errcode'], 'message' => $body['errmsg'], 'data' => $body]; + } else { + $param = ['code' => 0, 'data' => json_decode($body, true)]; + } + return new Result($param); + }); + $data = $request->post($this->tick_url . $this->config->getAccessToken(), json_encode($requestParam)); + if (!$data->isResultsOK()) { + throw new \Exception($data->getMessage()); + } + return $data->getData('ticket'); + } + +} diff --git a/officialaccount/SourceMaterial.php b/officialaccount/SourceMaterial.php new file mode 100644 index 0000000..b731bc5 --- /dev/null +++ b/officialaccount/SourceMaterial.php @@ -0,0 +1,100 @@ +sendError('文件不存在.', 404); + } + return $this->upload($file, 'image'); + } + + /** + * @param $file + * @return bool|mixed|Result + */ + public function VoiceUpload($file) + { + if (!file_exists($file)) { + return $this->sendError('文件不存在.', 404); + } + return $this->upload($file, 'voice'); + } + + /** + * @param $file + * @return bool|mixed|Result + */ + public function VideoUpload($file) + { + if (!file_exists($file)) { + return $this->sendError('文件不存在.', 404); + } + return $this->upload($file, 'video'); + } + + /** + * @param $file + * @return bool|mixed|Result + */ + public function ThumbUpload($file) + { + if (!file_exists($file)) { + return $this->sendError('文件不存在.', 404); + } + return $this->upload($file, 'thumb'); + } + + + /** + * @param $media_id + * @return array|mixed|Result + */ + public function MediaGet($media_id) + { + $client = HttpClient::NewRequest(); + + $accessToken = $this->config->getAccessToken(); + + return $client->get($this->getUploadUrl, ['access_token' => $accessToken, 'media_id' => $media_id]); + } + + /** + * @param $file + * @param $type + * @return bool|mixed + */ + private function upload($file, $type) + { + $uploadInfo['media'] = new \CURLFile($file); + $uploadInfo['form-data[filename]'] = $uploadInfo['media']->getFilename(); + $uploadInfo['form-data[content-type]'] = $uploadInfo['media']->getMimeType(); + + $accessToken = $this->config->getAccessToken(); + + $url = $this->uploadUrl . 'access_token=' . $accessToken . '&type=' . $type; + $result = $this->request->post($url, $uploadInfo); + if (!$result->isResultsOK()) { + return false; + } + return $result->getData(); + } + +} diff --git a/officialaccount/Subscribe.php b/officialaccount/Subscribe.php new file mode 100644 index 0000000..c7a2fae --- /dev/null +++ b/officialaccount/Subscribe.php @@ -0,0 +1,118 @@ +openid = $openid; + return $this; + } + + /** + * @param string $template_id + * @return Subscribe + */ + public function setTemplateId(string $template_id): Subscribe + { + $this->template_id = $template_id; + return $this; + } + + /** + * @param string $url + * @return Subscribe + */ + public function setUrl(string $url): Subscribe + { + $this->url = $url; + return $this; + } + + /** + * @param string $appid + * @param string $path + * @return Subscribe + */ + public function setMiniprogram(string $appid, string $path): Subscribe + { + $this->miniprogram['appid'] = $appid; + $this->miniprogram['pagepath'] = $path; + return $this; + } + + /** + * @param string $scene + * @return Subscribe + */ + public function setScene(string $scene): Subscribe + { + $this->scene = $scene; + return $this; + } + + /** + * @param string $title + * @return Subscribe + */ + public function setTitle(string $title): Subscribe + { + $this->title = $title; + return $this; + } + + + /** + * @param $keyword + * @param $content + * @param null $color + */ + public function addContent($keyword, $content, $color = null) + { + $param['value'] = $content; + if (!empty($color)) { + $param['color'] = $color; + } + $this->keywords[$keyword] = $param; + } + + /** + * @return array|mixed|\common\Result + */ + public function sendSubscribeMessage() + { + $requestParam['touser'] = $this->openid; + $requestParam['template_id'] = $this->template_id; + $requestParam['url'] = $this->url; + $requestParam['miniprogram'] = $this->miniprogram; + $requestParam['scene'] = $this->scene; + $requestParam['title'] = $this->title; + $requestParam['data'] = $this->keywords; + + $requestUrl = $this->pushUrl . $this->config->getAccessToken(); + + $client = HttpClient::NewRequest(); + return $client->post($requestUrl, $requestParam); + } + +} diff --git a/officialaccount/Tag.php b/officialaccount/Tag.php new file mode 100644 index 0000000..3e57943 --- /dev/null +++ b/officialaccount/Tag.php @@ -0,0 +1,30 @@ +config->getAccessToken(); + + $result = $this->request->post($this->generate_url . $config, $url); + if (!$result->isResultsOK()) { + throw new \Exception($result->getMessage()); + } + return $result->getData(); + } + +} diff --git a/officialaccount/WxSDK.php b/officialaccount/WxSDK.php new file mode 100644 index 0000000..b0b582a --- /dev/null +++ b/officialaccount/WxSDK.php @@ -0,0 +1,41 @@ +setSubscribe($object['subscribe']); + $class->setOpenid($object['openid']); + $class->setNickname($object['nickname']); + $class->setSex($object['sex']); + $class->setLanguage($object['language']); + $class->setCity($object['city']); + $class->setProvince($object['province']); + $class->setCountry($object['country']); + $class->setHeadimgurl($object['headimgurl']); + $class->setSubscribeTime($object['subscribe_time']); + $class->setUnionid($object['unionid']); + $class->setRemark($object['remark']); + $class->setGroupid($object['groupid']); + $class->setTagidList($object['tagid_list']); + $class->setSubscribeScene($object['subscribe_scene']); + $class->setQrScene($object['qr_scene']); + $class->setQrSceneStr($object['qr_scene_str']); + return $class; + } + + /** + * @return mixed + */ + public function getSubscribe() + { + return $this->subscribe; + } + + /** + * @param mixed $subscribe + * @return Authorization + */ + public function setSubscribe($subscribe) + { + $this->subscribe = $subscribe; + return $this; + } + + /** + * @return mixed + */ + public function getOpenid() + { + return $this->openid; + } + + /** + * @param mixed $openid + * @return Authorization + */ + public function setOpenid($openid) + { + $this->openid = $openid; + return $this; + } + + /** + * @return mixed + */ + public function getNickname() + { + return $this->nickname; + } + + /** + * @param mixed $nickname + * @return Authorization + */ + public function setNickname($nickname) + { + $this->nickname = $nickname; + return $this; + } + + /** + * @return mixed + */ + public function getSex() + { + return $this->sex; + } + + /** + * @param mixed $sex + * @return Authorization + */ + public function setSex($sex) + { + $this->sex = $sex; + return $this; + } + + /** + * @return mixed + */ + public function getLanguage() + { + return $this->language; + } + + /** + * @param mixed $language + * @return Authorization + */ + public function setLanguage($language) + { + $this->language = $language; + return $this; + } + + /** + * @return mixed + */ + public function getCity() + { + return $this->city; + } + + /** + * @param mixed $city + * @return Authorization + */ + public function setCity($city) + { + $this->city = $city; + return $this; + } + + /** + * @return mixed + */ + public function getProvince() + { + return $this->province; + } + + /** + * @param mixed $province + * @return Authorization + */ + public function setProvince($province) + { + $this->province = $province; + return $this; + } + + /** + * @return mixed + */ + public function getCountry() + { + return $this->country; + } + + /** + * @param mixed $country + * @return Authorization + */ + public function setCountry($country) + { + $this->country = $country; + return $this; + } + + /** + * @return mixed + */ + public function getHeadimgurl() + { + return $this->headimgurl; + } + + /** + * @param mixed $headimgurl + * @return Authorization + */ + public function setHeadimgurl($headimgurl) + { + $this->headimgurl = $headimgurl; + return $this; + } + + /** + * @return mixed + */ + public function getSubscribeTime() + { + return $this->subscribe_time; + } + + /** + * @param mixed $subscribe_time + * @return Authorization + */ + public function setSubscribeTime($subscribe_time) + { + $this->subscribe_time = $subscribe_time; + return $this; + } + + /** + * @return mixed + */ + public function getUnionid() + { + return $this->unionid; + } + + /** + * @param mixed $unionid + * @return Authorization + */ + public function setUnionid($unionid) + { + $this->unionid = $unionid; + return $this; + } + + /** + * @return mixed + */ + public function getRemark() + { + return $this->remark; + } + + /** + * @param mixed $remark + * @return Authorization + */ + public function setRemark($remark) + { + $this->remark = $remark; + return $this; + } + + /** + * @return mixed + */ + public function getGroupid() + { + return $this->groupid; + } + + /** + * @param mixed $groupid + * @return Authorization + */ + public function setGroupid($groupid) + { + $this->groupid = $groupid; + return $this; + } + + /** + * @return mixed + */ + public function getTagidList() + { + return $this->tagid_list; + } + + /** + * @param mixed $tagid_list + * @return Authorization + */ + public function setTagidList($tagid_list) + { + $this->tagid_list = $tagid_list; + return $this; + } + + /** + * @return mixed + */ + public function getSubscribeScene() + { + return $this->subscribe_scene; + } + + /** + * @param mixed $subscribe_scene + * @return Authorization + */ + public function setSubscribeScene($subscribe_scene) + { + $this->subscribe_scene = $subscribe_scene; + return $this; + } + + /** + * @return mixed + */ + public function getQrScene() + { + return $this->qr_scene; + } + + /** + * @param mixed $qr_scene + * @return Authorization + */ + public function setQrScene($qr_scene) + { + $this->qr_scene = $qr_scene; + return $this; + } + + /** + * @return mixed + */ + public function getQrSceneStr() + { + return $this->qr_scene_str; + } + + /** + * @param mixed $qr_scene_str + * @return Authorization + */ + public function setQrSceneStr($qr_scene_str) + { + $this->qr_scene_str = $qr_scene_str; + return $this; + } + + +} diff --git a/officialaccount/dcaler/PKCS7Encoder.php b/officialaccount/dcaler/PKCS7Encoder.php new file mode 100644 index 0000000..80e97b8 --- /dev/null +++ b/officialaccount/dcaler/PKCS7Encoder.php @@ -0,0 +1,46 @@ + 32) { + $pad = 0; + } + return substr($text, 0, (strlen($text) - $pad)); + } +} diff --git a/officialaccount/dcaler/Prpcrypt.php b/officialaccount/dcaler/Prpcrypt.php new file mode 100644 index 0000000..d121b06 --- /dev/null +++ b/officialaccount/dcaler/Prpcrypt.php @@ -0,0 +1,119 @@ +key = base64_decode($k . "="); + } + + /** + * @param $text + * @param $appid + * @return array + */ + public function encrypt($text, $appid) + { + + try { + //获得16位随机字符串,填充到明文之前 + $random = $this->getRandomStr(); + $text = $random . pack("N", strlen($text)) . $text . $appid; + // 网络字节序 + $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); + $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); + $iv = substr($this->key, 0, 16); + //使用自定义的填充方式对明文进行补位填充 + $pkc_encoder = new PKCS7Encoder; + $text = $pkc_encoder->encode($text); + mcrypt_generic_init($module, $this->key, $iv); + //加密 + $encrypted = mcrypt_generic($module, $text); + mcrypt_generic_deinit($module); + mcrypt_module_close($module); + + //print(base64_encode($encrypted)); + //使用BASE64对加密后的字符串进行编码 + return array(NewsManager::OK, base64_encode($encrypted)); + } catch (\Exception $e) { + //print $e; + return array(NewsManager::EncryptAESError, null); + } + } + + /** + * @param $encrypted + * @param $appid + * @return array|string + */ + public function decrypt($encrypted, $appid) + { + + try { + //使用BASE64对需要解密的字符串进行解码 + $ciphertext_dec = base64_decode($encrypted); + $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); + $iv = substr($this->key, 0, 16); + mcrypt_generic_init($module, $this->key, $iv); + + //解密 + $decrypted = mdecrypt_generic($module, $ciphertext_dec); + mcrypt_generic_deinit($module); + mcrypt_module_close($module); + } catch (\Exception $e) { + return array(NewsManager::DecryptAESError, null); + } + + + try { + //去除补位字符 + $pkc_encoder = new PKCS7Encoder; + $result = $pkc_encoder->decode($decrypted); + //去除16位随机字符串,网络字节序和AppId + if (strlen($result) < 16) + return ""; + $content = substr($result, 16, strlen($result)); + $len_list = unpack("N", substr($content, 0, 4)); + $xml_len = $len_list[1]; + $xml_content = substr($content, 4, $xml_len); + $from_appid = substr($content, $xml_len + 4); + } catch (\Exception $e) { + //print $e; + return array(NewsManager::IllegalBuffer, null); + } + if ($from_appid != $appid) + return array(NewsManager::ValidateAppidError, null); + return array(0, $xml_content); + + } + + + /** + * 随机生成16位字符串 + * @return string 生成的字符串 + */ + function getRandomStr() + { + + $str = ""; + $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; + $max = strlen($str_pol) - 1; + for ($i = 0; $i < 16; $i++) { + $str .= $str_pol[mt_rand(0, $max)]; + } + return $str; + } + +} diff --git a/officialaccount/dcaler/SnsInfo.php b/officialaccount/dcaler/SnsInfo.php new file mode 100644 index 0000000..c0aaa00 --- /dev/null +++ b/officialaccount/dcaler/SnsInfo.php @@ -0,0 +1,204 @@ +openid; + } + + /** + * @param mixed $openid + * @return SnsInfo + */ + public function setOpenid($openid) + { + $this->openid = $openid; + return $this; + } + + /** + * @return mixed + */ + public function getNickname() + { + return $this->nickname; + } + + /** + * @param mixed $nickname + * @return SnsInfo + */ + public function setNickname($nickname) + { + $this->nickname = $nickname; + return $this; + } + + /** + * @return mixed + */ + public function getSex() + { + return $this->sex; + } + + /** + * @param mixed $sex + * @return SnsInfo + */ + public function setSex($sex) + { + $this->sex = $sex; + return $this; + } + + /** + * @return mixed + */ + public function getProvince() + { + return $this->province; + } + + /** + * @param mixed $province + * @return SnsInfo + */ + public function setProvince($province) + { + $this->province = $province; + return $this; + } + + /** + * @return mixed + */ + public function getCity() + { + return $this->city; + } + + /** + * @param mixed $city + * @return SnsInfo + */ + public function setCity($city) + { + $this->city = $city; + return $this; + } + + /** + * @return mixed + */ + public function getCountry() + { + return $this->country; + } + + /** + * @param mixed $country + * @return SnsInfo + */ + public function setCountry($country) + { + $this->country = $country; + return $this; + } + + /** + * @return mixed + */ + public function getHeadimgurl() + { + return $this->headimgurl; + } + + /** + * @param mixed $headimgurl + * @return SnsInfo + */ + public function setHeadimgurl($headimgurl) + { + $this->headimgurl = $headimgurl; + return $this; + } + + /** + * @return mixed + */ + public function getPrivilege() + { + return $this->privilege; + } + + /** + * @param mixed $privilege + * @return SnsInfo + */ + public function setPrivilege($privilege) + { + $this->privilege = $privilege; + return $this; + } + + /** + * @return mixed + */ + public function getUnionid() + { + return $this->unionid; + } + + /** + * @param mixed $unionid + * @return SnsInfo + */ + public function setUnionid($unionid) + { + $this->unionid = $unionid; + return $this; + } + + + + /** + * @param $object + * @return SnsInfo + */ + public static function instance($object) + { + $class = new SnsInfo(); + $class->setOpenid($object['openid']); + $class->setNickname($object['nickname']); + $class->setSex($object['sex']); + $class->setCity($object['city']); + $class->setProvince($object['province']); + $class->setCountry($object['country']); + $class->setHeadimgurl($object['headimgurl']); + $class->setUnionid($object['unionid']); + $class->setPrivilege($object['privilege']); + return $class; + } + + +} diff --git a/officialaccount/dcaler/XMLParse.php b/officialaccount/dcaler/XMLParse.php new file mode 100644 index 0000000..4155fd2 --- /dev/null +++ b/officialaccount/dcaler/XMLParse.php @@ -0,0 +1,49 @@ +loadXML($xmltext); + $array_e = $xml->getElementsByTagName('Encrypt'); + $array_a = $xml->getElementsByTagName('ToUserName'); + $encrypt = $array_e->item(0)->nodeValue; + $tousername = $array_a->item(0)->nodeValue; + return [0, $encrypt, $tousername]; + } catch (\Exception $e) { + return [NewsManager::ParseXmlError, null, null]; + } + } + + /** + * @param $encrypt + * @param $signature + * @param $timestamp + * @param $nonce + * @return string + */ + public function generate($encrypt, $signature, $timestamp, $nonce) + { + $format = " + + +%s + +"; + return sprintf($format, $encrypt, $signature, $timestamp, $nonce); + } + +} diff --git a/qq/Account.php b/qq/Account.php index f40a24f..11fcc2b 100644 --- a/qq/Account.php +++ b/qq/Account.php @@ -8,35 +8,12 @@ namespace qq; -use wchat\Result; -use wchat\WxClient; -use wchat\Miniprogarampage; +use common\Decode; +use common\HttpClient; +use common\Result; -class Account extends Miniprogarampage +class Account extends SmallProgram { - - private $wxaqr = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='; - private $getwxacode = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='; - private $publicInfo = 'https://api.weixin.qq.com/cgi-bin/user/info?'; - private $getwxacodeunlimit = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='; - - private $savePath = __DIR__ . '/../../../'; - - - private $OK = 0; - private $IllegalAesKey = -41001; - private $IllegalIv = -41002; - private $IllegalBuffer = -41003; - private $DecodeBase64Error = -41004; - - /** - * @param $path - */ - public function setSavePath($path) - { - $this->savePath = $path; - } - /** * @param $code * @return Result @@ -53,31 +30,12 @@ class Account extends Miniprogarampage } $this->request->setHost('api.q.qq.com'); - $this->request->setMethod(WxClient::GET); + $this->request->setMethod(HttpClient::GET); $this->request->addHeader('Content-Type', 'text/xml'); return $this->request->get('sns/jscode2session', $param); } - /** - * @param $openid - * @return array|mixed|Result - * @throws \Exception - */ - public function getPublicUserInfo($openid) - { - $query = [ - 'access_token' => $this->getAccessToken(), - 'openid' => $openid, - 'lang' => 'zh_CN' - ]; - - $this->request->setMethod(WxClient::GET); - $this->request->setIsSSL(true); - return $this->request->get($this->publicInfo, $query); - } - - /** * @param $encryptedData * @param $iv @@ -94,122 +52,12 @@ class Account extends Miniprogarampage */ public function decode($encryptedData, $iv, $sessionKey, $asArray = false) { - $config = QqSDK::getMiniProGaRamPage()->getConfig(); - if (strlen($sessionKey) != 24) { - throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey); - } - - $aesKey = base64_decode($sessionKey); - if (strlen($iv) != 24) { - throw new \Exception('base64解密失败', $this->IllegalIv); - } - - $aesIV = base64_decode($iv); - $aesCipher = base64_decode($encryptedData); - $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV); - if ($result === false) { - throw new \Exception('aes 解密失败', $this->IllegalBuffer); - } - - $dataObj = json_decode($result); - if ($dataObj->watermark->appid != $config->getAppid()) { - throw new \Exception('aes 解密失败', $this->IllegalBuffer); - } - - if ($asArray) { - return get_object_vars($dataObj); - } - - return $dataObj; + $decode = new Decode(); + $decode->setAppId($this->config->getAppid()); + $decode->setIv($iv); + $decode->setEncryptedData($encryptedData); + $decode->setSessionKey($sessionKey); + return $decode->decode($asArray); } - - /** - * @param $path - * @param $width - * @return array|mixed|Result - * @throws \Exception - */ - public function createwxaqrcode($path, $width) - { - $url = $this->wxaqr . $this->getAccessToken(); - - $sendBody['path'] = $path; - $sendBody['width'] = $width; - - $this->request->setMethod(WxClient::POST); - $this->request->setCallback([$this, 'saveByPath']); - - return $this->request->post($url, $sendBody); - } - - - /** - * @param $path - * @param $width - * @param bool $is_hyaline - * @param bool $auto_color - * @param string $line_color - * @return array|mixed|Result - * @throws \Exception - */ - public function getwxacode($path, $width, $is_hyaline = false, $auto_color = false, $line_color = '') - { - $sendBody['path'] = $path; - $sendBody['width'] = $width; - $sendBody['auto_color'] = $auto_color; - $sendBody['is_hyaline'] = $is_hyaline; - if ($auto_color) { - $sendBody['line_color'] = $line_color; - } - - $url = $this->getwxacode . $this->getAccessToken(); - - $this->request->setMethod(WxClient::POST); - $this->request->setCallback([$this, 'saveByPath']); - return $this->request->post($url, $sendBody); - } - - - /** - * @param $path - * @param $width - * @param bool $is_hyaline - * @param bool $auto_color - * @param string $line_color - * @return array|mixed|Result - * @throws \Exception - */ - public function getwxacodeunlimit($path, $width, $is_hyaline = false, $auto_color = false, $line_color = '') - { - $sendBody['path'] = $path; - $sendBody['width'] = $width; - $sendBody['auto_color'] = $auto_color; - $sendBody['is_hyaline'] = $is_hyaline; - if ($auto_color) { - $sendBody['line_color'] = $line_color; - } - - $url = $this->getwxacodeunlimit . $this->getAccessToken(); - - $this->request->setMethod(WxClient::POST); - $this->request->setCallback([$this, 'saveByPath']); - return $this->request->post($url, $sendBody); - } - - /** - * @param mixed $body - * @return string - * @throws \Exception - */ - public function saveByPath($body) - { - if (!is_null($json = json_decode($body))) { - throw new \Exception($json['errmsg'], $json['errcode']); - } - - $push = md5_file($body) . '.png'; - file_put_contents($this->savePath . $push, $this->savePath); - return $this->savePath . $push; - } } diff --git a/qq/GamePrePay.php b/qq/GamePrePay.php new file mode 100644 index 0000000..09f127d --- /dev/null +++ b/qq/GamePrePay.php @@ -0,0 +1,13 @@ +openid = $openid; - $this->msgData['touser'] = $openid; - } - - /** - * @param string $content - * @return Result - * @throws \Exception - */ - public function sendTextNews(string $content) - { - $this->msgData['msgtype'] = 'text'; - $this->msgData['text[content]'] = $content; - - return $this->sendKefuMsg(); - } - - /** - * @param $media_id - * @return Result - * @throws \Exception - */ - public function sendImageNews(string $media_id) - { - $this->msgData['msgtype'] = 'image'; - $this->msgData['image[media_id]'] = $media_id; - - return $this->sendKefuMsg(); - } - - - /** - * @param $media_id - * @return Result - * @throws \Exception - */ - public function sendVoiceNews(string $media_id) - { - $this->msgData['msgtype'] = 'voice'; - $this->msgData['voice[media_id]'] = $media_id; - - return $this->sendKefuMsg(); - } - - /** - * @param $media_id - * @return Result - * @throws \Exception - */ - public function sendMpNewsNews(string $media_id) - { - $this->msgData['msgtype'] = 'mpnews'; - $this->msgData['mpnews[media_id]'] = $media_id; - - return $this->sendKefuMsg(); - } - - - /** - * @param string $title - * @param string $description - * @param string $url - * @param string $picurl - * @return Result - * @throws \Exception - */ - public function sendNewsNews(string $title, string $description, string $url, string $picurl) - { - $this->msgData['msgtype'] = 'news'; - $this->msgData['news[articles][0][title]'] = $title; - $this->msgData['news[articles][0][description]'] = $description; - $this->msgData['news[articles][0][url]'] = $url; - $this->msgData['news[articles][0][picurl]'] = $picurl; - - return $this->sendKefuMsg(); - } - - - /** - * @param string $title - * @return Result - * @throws \Exception - */ - public function sendCardNews(string $title) - { - $this->msgData['msgtype'] = 'wxcard'; - $this->msgData['wxcard[card_id]'] = $title; - - return $this->sendKefuMsg(); - } - - - /** - * @param string $media_id - * @param string $thumb_media_id - * @param string $title - * @param string $description - * @return Result - * @throws \Exception - */ - public function sendVideoNews(string $media_id, string $thumb_media_id, string $title, string $description) - { - $this->msgData['msgtype'] = 'video'; - $this->msgData['video[media_id]'] = $media_id; - $this->msgData['video[thumb_media_id]'] = $thumb_media_id; - $this->msgData['video[title]'] = $title; - $this->msgData['video[description]'] = $description; - - return $this->sendKefuMsg(); - } - - - /** - * @param string $musicurl - * @param string $hqmusicurl - * @param string $thumb_media_id - * @param string $title - * @param string $description - * @return Result - * @throws \Exception - */ - public function sendMusicNews(string $musicurl, string $hqmusicurl, string $thumb_media_id, string $title, string $description) - { - $this->msgData['msgtype'] = 'music'; - $this->msgData['music[title]'] = $title; - $this->msgData['music[description]'] = $description; - $this->msgData['music[musicurl]'] = $musicurl; - $this->msgData['music[hqmusicurl]'] = $hqmusicurl; - $this->msgData['music[thumb_media_id]'] = $thumb_media_id; - - return $this->sendKefuMsg(); - } - - - /** - * @param string $head_content - * @param string $tail_content - * @param array $menus - * @return Result - * @throws \Exception - */ - public function sendMenuNews(string $head_content, string $tail_content, array $menus = []) - { - $this->msgData['msgtype'] = 'msgmenu'; - $this->msgData['msgmenu[head_content]'] = $head_content; - $this->msgData['msgmenu[tail_content]'] = $tail_content; - - if (empty($menus) || !is_array($menus) || count($menus) < 2) { - throw new \Exception('菜单选项必须有2个'); - } - - foreach ($menus as $key => $val) { - $this->addNewsMenu($val['id'], $val['name']); - } - - return $this->sendKefuMsg(); - } - - private $index = 0; - - /** - * @param $id - * @param $menuName - * @return $this - */ - public function addNewsMenu($id, $menuName) - { - $this->msgData['msgmenu[list][' . $this->index . '][id]'] = $id; - $this->msgData['msgmenu[list][' . $this->index . '][content]'] = $menuName; - - ++$this->index; - - return $this; - } - - /** - * @param $title - * @param $appid - * @param $pagepath - * @param $thumb_media_id - * @return Result - * @throws \Exception - */ - public function sendMiniprogrampageNews(string $title, string $appid, string $pagepath, string $thumb_media_id) - { - $this->msgData['msgtype'] = 'msgmenu'; - $this->msgData['miniprogrampage[title]'] = $title; - $this->msgData['miniprogrampage[appid]'] = $appid; - $this->msgData['miniprogrampage[pagepath]'] = $pagepath; - $this->msgData['miniprogrampage[thumb_media_id]'] = $thumb_media_id; - - return $this->sendKefuMsg(); - } - - /** - * @param string $filePath - * @param string $type - * @param bool $isPermanent - * @param string $title - * @param string $introduction - * @return mixed - * @throws \Exception - */ - public function upload(string $filePath, string $type, $isPermanent = false, string $title = '', string $introduction = '') - { - if (!file_exists($filePath)) { - throw new \Exception('文件不存在'); - } - - if (!in_array($type, ['image', 'voice', 'video', 'thumb'])) { - throw new \Exception('暂不支持的文件类型'); - } - - $token = $this->getAccessToken(); - if ($isPermanent) { - $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$token}&type={$type}"; - } else { - $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$token}&type={$type}"; - } - - $mime = mime_content_type($filePath); - - $real_path = new \CURLFile(realpath($filePath)); - - $data = array("media" => $real_path, 'form-data[filename]' => $filePath, 'form-data[content-type]' => $mime); - if ($isPermanent && $mime == 'video/mp3') { - $data = ['media' => $real_path, 'description[title]' => $title, 'description[introduction]' => $introduction]; - } - - $this->request->setMethod(WxClient::POST); - - /** @var Result $body */ - $data = $this->request->post($url, $data); - if (!$data->isResultsOK()) { - throw new \Exception($data->getMessage()); - } - - return $data->getData(); - } - - /** - * @param $mime - * @throws \Exception - */ - private function checkExtinfo($mime) - { - switch (strtolower($mime)) { - case 'image/bmp': - case 'image/png': - case 'image/jpeg': - case 'image/jpg': - case 'image/gif': - break; - case 'mp3/wma/wav/amr': - break; - case 'mp4'; - break; - case 'jpg'; - break; - default: - throw new \Exception('不支持的文件格式'); - } - } - - /** - * @param $data - * @return Result - * @throws \Exception - */ - private function sendKefuMsg() - { - $data = json_encode($this->msgData, JSON_UNESCAPED_UNICODE); - - $url = '/cgi-bin/message/custom/send?access_token=' . $this->getAccessToken(); - $this->request->setMethod(WxClient::POST); - - /** @var Result $body */ - $body = $this->request->post($url, $data); - - if (!$body->isResultsOK()) { - throw new \Exception($body->getMessage()); - } - return $body; - } -} diff --git a/qq/Notify.php b/qq/Notify.php index 1e624e4..cc835e1 100644 --- a/qq/Notify.php +++ b/qq/Notify.php @@ -3,10 +3,9 @@ namespace qq; -use wchat\Miniprogarampage; -use wchat\Help; +use common\Help; -class Notify extends Miniprogarampage +class Notify extends SmallProgram { public $appid = ''; public $mch_id = ''; diff --git a/qq/PublicTemplate.php b/qq/PublicTemplate.php deleted file mode 100644 index 7044d30..0000000 --- a/qq/PublicTemplate.php +++ /dev/null @@ -1,157 +0,0 @@ -keywords = $keywords; - } - - /** - * @param string $templateId - */ - public function setTemplateId(string $templateId) - { - $this->templateId = $templateId; - } - - /** - * @param string $openId - */ - public function setOpenId(string $openId) - { - $this->openId = $openId; - } - - /** - * @param string $defaultUrl - */ - public function setDefaultUrl(string $defaultUrl) - { - $this->defaultUrl = $defaultUrl; - } - - /** - * @param $name - * @param $context - * @param string $color - */ - public function replaceKeyword($name, $context, $color = '') - { - $this->keywords[$name] = ['value' => $context, 'color' => $color]; - } - - - /** - * @param $name - * @param $context - * @param null $color - */ - public function addKeyword($name, $context, $color = null) - { - if (empty($color)) { - $color = '#000'; - } - $this->keywords[$name] = [ - 'value' => $context, - 'color' => $color - ]; - } - - /** - * @param $context - * @param string $color - */ - public function setFirst($context, $color = '#f00') - { - $this->first = [ - 'value' => $context, - 'color' => $color - ]; - } - - /** - * @param $context - * @param string $color - */ - public function setRemark($context, $color = '#000') - { - $this->remark = [ - 'value' => $context, - 'color' => $color - ]; - } - - /** - * @param $appid - * @param $pagepath - */ - public function setMiniprogram($appid, $pagepath) - { - $this->miniprogram = [ - 'appid' => $appid, - 'pagepath' => $pagepath - ]; - } - - /** - * @return Result - * @throws \Exception - * - * 奴隶交易通知 - */ - public function sendTemplate() - { - $url = $this->sendUrl . '?access_token=' . $this->getAccessToken(); - - $keywords = $this->keywords; - $keywords['first'] = $this->first; - $keywords['remark'] = $this->remark; - - $default = [ - "touser" => $this->openId, - "template_id" => $this->templateId, - "url" => $this->defaultUrl, - "data" => $keywords, - ]; - - if (!empty($this->miniprogram)) { - $default['miniprogram'] = $this->miniprogram; - } - - $params = json_encode($default, JSON_UNESCAPED_UNICODE); - - $this->request->setIsSSL(true); - $this->request->addHeader('content-type', 'application/json'); - - $result = $this->request->post($url, $params); - $result->append('postBody', $params); - - return $result; - } -} diff --git a/qq/QqSDK.php b/qq/QqSDK.php deleted file mode 100644 index 323e916..0000000 --- a/qq/QqSDK.php +++ /dev/null @@ -1,116 +0,0 @@ -config; - } - - - /** - * @param Config $config - * @return $this - */ - public function setConfig(Config $config) - { - $this->config = $config; - return $this; - } - - /** - * @return Template - */ - public function getTemplate() - { - return Template::getInstance($this->config); - } - - - /** - * @return PublicTemplate - */ - public function getPublicTemplate() - { - return PublicTemplate::getInstance($this->config); - } - - /** - * @return Account - */ - public function getAccount() - { - return Account::getInstance($this->config); - } - - /** - * @return Message - */ - public function getMessage() - { - return Message::getInstance($this->config); - } - - /** - * @return Recharge - */ - public function getRecharge() - { - return Recharge::getInstance($this->config); - } - - /** - * @return Notify - */ - public function getNotify() - { - return Notify::getInstance($this->config); - } - - /** - * @return WxClient - */ - public function getClient() - { - $client = WxClient::getInstance(); - $client->setAgent($this->config->getAgent()); - return $client; - } - - - /** - * @return Token - */ - public function getAccessToken() - { - return Token::getInstance($this->config); - } - -} diff --git a/qq/QrCode.php b/qq/QrCode.php new file mode 100644 index 0000000..9c201cf --- /dev/null +++ b/qq/QrCode.php @@ -0,0 +1,117 @@ +savePath = $path; + } + + + /** + * @param $path + * @param $width + * @return array|mixed|Result + * @throws \Exception + */ + public function createwxaqrcode($path, $width) + { + $url = $this->wxaqr . $this->getAccessToken(); + + $sendBody['path'] = $path; + $sendBody['width'] = $width; + + $this->request->setMethod(HttpClient::POST); + $this->request->setCallback([$this, 'saveByPath']); + + return $this->request->post($url, $sendBody); + } + + + /** + * @param $path + * @param $width + * @param bool $is_hyaline + * @param bool $auto_color + * @param string $line_color + * @return array|mixed|Result + * @throws \Exception + */ + public function getwxacode($path, $width, $is_hyaline = false, $auto_color = false, $line_color = '') + { + $sendBody['path'] = $path; + $sendBody['width'] = $width; + $sendBody['auto_color'] = $auto_color; + $sendBody['is_hyaline'] = $is_hyaline; + if ($auto_color) { + $sendBody['line_color'] = $line_color; + } + + $url = $this->getwxacode . $this->getAccessToken(); + + $this->request->setMethod(HttpClient::POST); + $this->request->setCallback([$this, 'saveByPath']); + return $this->request->post($url, $sendBody); + } + + + /** + * @param $path + * @param $width + * @param bool $is_hyaline + * @param bool $auto_color + * @param string $line_color + * @return array|mixed|Result + * @throws \Exception + */ + public function getwxacodeunlimit($path, $width, $is_hyaline = false, $auto_color = false, $line_color = '') + { + $sendBody['path'] = $path; + $sendBody['width'] = $width; + $sendBody['auto_color'] = $auto_color; + $sendBody['is_hyaline'] = $is_hyaline; + if ($auto_color) { + $sendBody['line_color'] = $line_color; + } + + $url = $this->getwxacodeunlimit . $this->getAccessToken(); + + $this->request->setMethod(HttpClient::POST); + $this->request->setCallback([$this, 'saveByPath']); + return $this->request->post($url, $sendBody); + } + + /** + * @param mixed $body + * @return string + * @throws \Exception + */ + public function saveByPath($body) + { + if (!is_null($json = json_decode($body))) { + throw new \Exception($json['errmsg'], $json['errcode']); + } + + $push = md5_file($body) . '.png'; + file_put_contents($this->savePath . $push, $this->savePath); + return $this->savePath . $push; + } +} diff --git a/qq/Recharge.php b/qq/Recharge.php index e83e723..627d9e2 100644 --- a/qq/Recharge.php +++ b/qq/Recharge.php @@ -8,12 +8,11 @@ namespace qq; -use wchat\Miniprogarampage; -use wchat\Result; -use wchat\Help; -use wchat\WxClient; +use common\HttpClient; +use common\Result; +use common\Help; -class Recharge extends Miniprogarampage +class Recharge extends SmallProgram { private $money = 0; @@ -175,7 +174,7 @@ class Recharge extends Miniprogarampage private function send($url, $data) { $this->request->setIsSSL(true); - $this->request->setMethod(WxClient::POST); + $this->request->setMethod(HttpClient::POST); $this->request->addHeader('Content-Type', 'text/xml'); return $this->request->send($url, $data); } diff --git a/qq/SmallProgram.php b/qq/SmallProgram.php new file mode 100644 index 0000000..037afc6 --- /dev/null +++ b/qq/SmallProgram.php @@ -0,0 +1,36 @@ +config->getToken())) { + return $this->config->getToken(); + } + $query = [ + 'grant_type' => 'client_credential', + 'appid' => $this->config->getAppid(), + 'secret' => $this->config->getAppsecret() + ]; + $param = $this->request->get($this->url, $query); + if (!$param->isResultsOK()) { + return null; + } + return $param->getData('access_token'); + } +} diff --git a/qq/Subject.php b/qq/Subject.php new file mode 100644 index 0000000..d846adf --- /dev/null +++ b/qq/Subject.php @@ -0,0 +1,136 @@ +keywords = $keywords; + } + + /** + * @param string $templateId + */ + public function setTemplateId(string $templateId) + { + $this->templateId = $templateId; + } + + /** + * @param string $openId + */ + public function setOpenId(string $openId) + { + $this->openId = $openId; + } + + /** + * @param string $defaultUrl + */ + public function setDefaultUrl(string $defaultUrl) + { + $this->defaultUrl = $defaultUrl; + } + + /** + * @param string $page + */ + public function setPage(string $page) + { + $this->page = $page; + } + + /** + * @param string $emphasis_keyword + */ + public function setEmphasisKeyword(string $emphasis_keyword) + { + $this->emphasis_keyword = $emphasis_keyword; + } + + /** + * @param $index + * @param $context + * @param $color + */ + public function replaceKeyword($index, $context, $color = '') + { + if (empty($color)) { + $color = '#000'; + } + $this->keywords['keyword' . $index] = [ + 'value' => $context, + 'color' => $color + ]; + } + + + /** + * @param $color + * @param $context + */ + public function addKeyword($context, $color = null) + { + if (empty($color)) { + $color = '#000'; + } + $this->keywords['keyword' . (count($this->keywords) + 1)] = [ + 'value' => $context, + 'color' => $color + ]; + } + + /** + * @return Result + * @throws \Exception + * + * 奴隶交易通知 + */ + public function sendTemplate() + { + $url = $this->sendUrl . '?access_token=' . $this->config->getAccessToken(); + $params = json_encode([ + "touser" => $this->openId, + "template_id" => $this->templateId, + "page" => $this->page, + "data" => $this->keywords, + ], JSON_UNESCAPED_UNICODE); + + if (!empty($this->emphasis_keyword)) { + $params['emphasis_keyword'] = $this->emphasis_keyword; + } + + $this->request->setIsSSL(true); + $this->request->addHeader('content-type', 'application/json'); + + $result = $this->request->post($url, $params); + $result->append('postBody', $params); + + $this->openId = ''; + $this->keywords = []; + $this->templateId = ''; + $this->page = ''; + + return $result; + } +} diff --git a/qq/Template.php b/qq/Template.php index ef58ece..334844c 100644 --- a/qq/Template.php +++ b/qq/Template.php @@ -9,12 +9,9 @@ namespace qq; -use wchat\Miniprogarampage; -use wchat\Result; -use wchat\Help; -use wchat\WxClient; +use common\Result; -class Template extends Miniprogarampage +class Template extends SmallProgram { private $keywords = []; diff --git a/qq/Token.php b/qq/Token.php index b7c3070..e1a31bc 100644 --- a/qq/Token.php +++ b/qq/Token.php @@ -4,29 +4,10 @@ namespace qq; -use wchat\Miniprogarampage; -class Token extends Miniprogarampage +class Token extends SmallProgram { - private $url = 'https://api.q.qq.com/api/getToken'; - /** - * @return mixed|null - */ - public function generateAccess_token() - { - $query = [ - 'grant_type' => 'client_credential', - 'appid' => $this->config->getAppid(), - 'secret' => $this->config->getAppsecret() - ]; - $param = $this->request->get($this->url, $query); - if (!$param->isResultsOK()) { - return null; - } - return $param->getData('access_token'); - } - } diff --git a/test.php b/test.php index 5fb5006..7983425 100644 --- a/test.php +++ b/test.php @@ -6,7 +6,10 @@ * Time: 18:38 */ -$config = new \wchat\Config(); +use officialaccount\AccessToken; +use wchat\Recharge; + +$config = new \common\Config(); $config->setAppid(''); $config->setAppsecret(''); $config->setMchId(''); @@ -16,28 +19,59 @@ $config->setDeviceInfo(''); $config->setAccessToken(''); -$instance = \wchat\Wx::getMiniProGaRamPage(); -$instance->setConfig($config); +/** @var AccessToken $container */ +$container = Container::newInstance(AccessToken::class, $config); +try { + $params = $container->generateAccess_token(); +} catch (Exception $e) { +} -$recharge = $instance->getRecharge(); -$recharge->cashWithdrawal(1, 'xxx', 'ooo'); -$recharge->recharge(1, '', ''); -$account = $instance->getAccount(); +/** @var Recharge $container */ +$container = Container::newInstance(\wchat\Recharge::class, $config); +$container->cashWithdrawal(1, 'xxx', 'xxx'); +$container->recharge(1, 'xxx', 'xxx'); + + +/** @var \wchat\Account $account */ +$account = Container::newInstance(\wchat\Account::class, $config); +$account->login(''); $account->setSavePath(''); $account->login(''); -$account->createwxaqrcode('pages/index/index',200); -$account->getwxacode('pages/index/index',150,true); -$account->getwxacodeunlimit('pages/index/index',150,true); +try { + $account->createwxaqrcode('pages/index/index', 200); + $account->getwxacode('pages/index/index', 150, true); + $account->getwxacodeunlimit('pages/index/index', 150, true); +} catch (Exception $exception) { - -$message = $instance->getMessage(); +} +/** @var \wchat\Message $message */ +$message = Container::newInstance(\wchat\Message::class, $config); $message->setOpenid(''); -$message->sendCardNews(''); +try { + $message->sendCardNews(''); + $message->sendTextNews(''); + $message->sendImageNews(''); + $message->sendVoiceNews(''); + $message->sendMpNewsNews(''); + $message->sendNewsNews('', '', '', ''); + $message->sendMusicNews('', '', '', '', ''); + $message->sendMenuNews('', ''); + $message->sendMiniprogrampageNews('', '', '', ''); + $message->sendVideoNews('', '', '', ''); +} catch (Exception $exception) { -$template = $instance->getTemplate(); -$template->setOpenId(''); -$template->setFormId(''); -$template->setTemplateId(''); -$template->setPage(''); -$template->sendTemplate(); +} + +try { + /** @var \wchat\Template $template */ + $template = Container::newInstance(\wchat\Template::class, $config); + $template->setOpenid(''); + $template->setOpenId(''); + $template->setFormId(''); + $template->setTemplateId(''); + $template->setPage(''); + $template->sendTemplate(); +} catch (Exception $exception) { + +} diff --git a/wx/Account.php b/wx/Account.php index 630d199..b2798f9 100644 --- a/wx/Account.php +++ b/wx/Account.php @@ -7,7 +7,12 @@ */ namespace wchat; -class Account extends Miniprogarampage + +use common\Decode; +use common\HttpClient; +use common\Result; + +class Account extends SmallProgram { private $wxaqr = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='; @@ -43,7 +48,7 @@ class Account extends Miniprogarampage $param['js_code'] = $code; $param['grant_type'] = 'authorization_code'; - $this->request->setMethod(WxClient::GET); + $this->request->setMethod(HttpClient::GET); $this->request->addHeader('Content-Type', 'text/xml'); return $this->request->get('sns/jscode2session', $param); @@ -58,11 +63,11 @@ class Account extends Miniprogarampage { $query = [ 'access_token' => $this->getAccessToken(), - 'openid' => $openid, - 'lang' => 'zh_CN' + 'openid' => $openid, + 'lang' => 'zh_CN' ]; - $this->request->setMethod(WxClient::GET); + $this->request->setMethod(HttpClient::GET); $this->request->setIsSSL(true); return $this->request->get($this->publicInfo, $query); } @@ -84,33 +89,13 @@ class Account extends Miniprogarampage */ public function decode($encryptedData, $iv, $sessionKey, $asArray = false) { - $config = Wx::getMiniProGaRamPage()->getConfig(); - if (strlen($sessionKey) != 24) { - throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey); - } + $decode = new Decode(); + $decode->setSessionKey($sessionKey); + $decode->setEncryptedData($encryptedData); + $decode->setAppId($this->config->getAppid()); + $decode->setIv($iv); - $aesKey = base64_decode($sessionKey); - if (strlen($iv) != 24) { - throw new \Exception('base64解密失败', $this->IllegalIv); - } - - $aesIV = base64_decode($iv); - $aesCipher = base64_decode($encryptedData); - $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV); - if ($result === false) { - throw new \Exception('aes 解密失败', $this->IllegalBuffer); - } - - $dataObj = json_decode($result); - if ($dataObj->watermark->appid != $config->getAppid()) { - throw new \Exception('aes 解密失败', $this->IllegalBuffer); - } - - if ($asArray) { - return get_object_vars($dataObj); - } - - return $dataObj; + return $decode->decode($asArray); } @@ -127,7 +112,7 @@ class Account extends Miniprogarampage $sendBody['path'] = $path; $sendBody['width'] = $width; - $this->request->setMethod(WxClient::POST); + $this->request->setMethod(HttpClient::POST); $this->request->setCallback([$this, 'saveByPath']); return $this->request->post($url, $sendBody); @@ -155,7 +140,7 @@ class Account extends Miniprogarampage $url = $this->getwxacode . $this->getAccessToken(); - $this->request->setMethod(WxClient::POST); + $this->request->setMethod(HttpClient::POST); $this->request->setCallback([$this, 'saveByPath']); return $this->request->post($url, $sendBody); } @@ -182,7 +167,7 @@ class Account extends Miniprogarampage $url = $this->getwxacodeunlimit . $this->getAccessToken(); - $this->request->setMethod(WxClient::POST); + $this->request->setMethod(HttpClient::POST); $this->request->setCallback([$this, 'saveByPath']); return $this->request->post($url, $sendBody); } diff --git a/wx/Message.php b/wx/Message.php index d89acb1..1ce6c6c 100644 --- a/wx/Message.php +++ b/wx/Message.php @@ -3,8 +3,9 @@ namespace wchat; - -class Message extends Miniprogarampage +use common\HttpClient; +use common\Result; +class Message extends SmallProgram { const TEXT = 0; const IMAGE = 1; @@ -253,7 +254,7 @@ class Message extends Miniprogarampage $data = ['media' => $real_path, 'description[title]' => $title, 'description[introduction]' => $introduction]; } - $this->request->setMethod(WxClient::POST); + $this->request->setMethod(HttpClient::POST); /** @var Result $body */ $data = $this->request->post($url, $data); @@ -298,7 +299,7 @@ class Message extends Miniprogarampage $data = json_encode($this->msgData, JSON_UNESCAPED_UNICODE); $url = '/cgi-bin/message/custom/send?access_token=' . $this->getAccessToken(); - $this->request->setMethod(WxClient::POST); + $this->request->setMethod(HttpClient::POST); /** @var Result $body */ $body = $this->request->post($url, $data); diff --git a/wx/Notify.php b/wx/Notify.php index 3aa2c98..de12600 100644 --- a/wx/Notify.php +++ b/wx/Notify.php @@ -4,7 +4,7 @@ namespace wchat; -class Notify extends Miniprogarampage +class Notify extends SmallProgram { public $appid = ''; public $mch_id = ''; diff --git a/wx/PublicTemplate.php b/wx/PublicTemplate.php index 8438e7e..a7f009a 100644 --- a/wx/PublicTemplate.php +++ b/wx/PublicTemplate.php @@ -8,7 +8,9 @@ namespace wchat; -class PublicTemplate extends Miniprogarampage +use common\Result; + +class PublicTemplate extends SmallProgram { private $keywords = []; diff --git a/wx/Recharge.php b/wx/Recharge.php index f129218..41088da 100644 --- a/wx/Recharge.php +++ b/wx/Recharge.php @@ -8,7 +8,10 @@ namespace wchat; -class Recharge extends Miniprogarampage +use common\Result; +use common\Help; + +class Recharge extends SmallProgram { private $money = 0; diff --git a/wx/SmallProgram.php b/wx/SmallProgram.php new file mode 100644 index 0000000..3819b33 --- /dev/null +++ b/wx/SmallProgram.php @@ -0,0 +1,38 @@ +config->getToken())) { + return $this->config->getToken(); + } + $query = [ + 'grant_type' => 'client_credential', + 'appid' => $this->config->getAppid(), + 'secret' => $this->config->getAppsecret() + ]; + $param = $this->request->get($this->url, $query); + if (!$param->isResultsOK()) { + throw new \Exception($param->getMessage()); + } + return $param->getData(); + } + +} diff --git a/wx/Subject.php b/wx/Subject.php index 0a8be8e..98e203d 100644 --- a/wx/Subject.php +++ b/wx/Subject.php @@ -4,7 +4,9 @@ namespace wchat; -class Subject extends Miniprogarampage +use common\Result; + +class Subject extends SmallProgram { diff --git a/wx/Template.php b/wx/Template.php index 2f13aff..39cf6db 100644 --- a/wx/Template.php +++ b/wx/Template.php @@ -8,7 +8,9 @@ namespace wchat; -class Template extends Miniprogarampage +use common\Result; + +class Template extends SmallProgram { private $keywords = []; diff --git a/wx/Token.php b/wx/Token.php index 4405d3a..99a206d 100644 --- a/wx/Token.php +++ b/wx/Token.php @@ -4,28 +4,9 @@ namespace wchat; -class Token extends Miniprogarampage +class Token extends SmallProgram { - private $url = 'https://api.weixin.qq.com/cgi-bin/token'; - - - /** - * @return mixed|null - */ - public function generateAccess_token() - { - $query = [ - 'grant_type' => 'client_credential', - 'appid' => $this->config->getAppid(), - 'secret' => $this->config->getAppsecret() - ]; - $param = $this->request->get($this->url, $query); - if (!$param->isResultsOK()) { - return null; - } - return $param->getData('access_token'); - } } diff --git a/wx/Wx.php b/wx/Wx.php deleted file mode 100644 index 8e42e39..0000000 --- a/wx/Wx.php +++ /dev/null @@ -1,123 +0,0 @@ -config; - } - - - /** - * @param Config $config - * @return $this - */ - public function setConfig(Config $config) - { - $this->config = $config; - return $this; - } - - /** - * @return Template - */ - public function getTemplate() - { - return Template::getInstance($this->config); - } - - - /** - * @return PublicTemplate - */ - public function getPublicTemplate() - { - return PublicTemplate::getInstance($this->config); - } - - /** - * @return Account - */ - public function getAccount() - { - return Account::getInstance($this->config); - } - - /** - * @return Message - */ - public function getMessage() - { - return Message::getInstance($this->config); - } - - /** - * @return Recharge - */ - public function getRecharge() - { - return Recharge::getInstance($this->config); - } - - /** - * @return Notify - */ - public function getNotify() - { - return Notify::getInstance($this->config); - } - - - /** - * @return Token - */ - public function getToken() - { - return Token::getInstance($this->config); - } - - /** - * @return WxClient - */ - public function getClient() - { - $client = WxClient::getInstance(); - $client->setAgent($this->config->getAgent()); - return $client; - } - - - /** - * @return Subject - */ - public function getSubject() - { - return Subject::getInstance($this->config); - } - -}