add clear

This commit is contained in:
as2252258@163.com
2019-11-11 18:14:47 +08:00
parent 62a2326e23
commit 7f138ef255
47 changed files with 2440 additions and 1100 deletions
+96
View File
@@ -0,0 +1,96 @@
<?php
use common\Config;
use common\Progaram;
/**
* Class Container
*/
class Container
{
/** @var Container */
private static $_instance;
/** @var \common\Config */
private $config;
private $container = [];
const QQ_SMALL_PROGRAM = 'QQ_SMALL_PROGRAM';
const QQ_LITTLE_GAME = 'QQ_LITTLE_GAME';
const WX_LITTLE_GAME = 'WX_LITTLE_GAME';
const WX_SMALL_PROGRAM = 'WX_SMALL_PROGRAM';
const WX_OFFICIAL_ACCOUNT = 'WX_OFFICIAL_ACCOUNT';
/**
* @param string $class
* @param Config $config
* @return mixed
*/
public static function newInstance($class, $config)
{
if (!(static::$_instance instanceof Container)) {
static::$_instance = new Container();
}
static::$_instance->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;
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
```php ```php
$config = new \wchat\Config(); $config = new \common\Config();
$config->setAppid(''); $config->setAppid('');
$config->setAppsecret(''); $config->setAppsecret('');
$config->setMchId(''); $config->setMchId('');
+38 -1
View File
@@ -1,7 +1,7 @@
<?php <?php
namespace wchat; namespace common;
class Config class Config
@@ -29,6 +29,9 @@ class Config
*/ */
private $device_info = 'WEB'; private $device_info = 'WEB';
private $token;
private $encodingAesKey;
/** /**
* @var string * @var string
* *
@@ -127,7 +130,41 @@ class Config
return $this; return $this;
} }
/**
* @return mixed
*/
public function getToken()
{
return $this->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 * @return string
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace common;
class Decode
{
private $sessionKey;
private $iv;
private $encryptedData;
private $appId;
private $OK = 0;
private $IllegalAesKey = -41001;
private $IllegalIv = -41002;
private $IllegalBuffer = -41003;
private $DecodeBase64Error = -41004;
/**
* @param mixed $sessionKey
* @return Decode
*/
public function setSessionKey($sessionKey)
{
$this->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;
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
<?php <?php
namespace wchat; namespace common;
class Help extends Miniprogarampage class Help extends Miniprogarampage
+190 -96
View File
@@ -1,11 +1,11 @@
<?php <?php
namespace wchat; namespace common;
use Swoole\Coroutine\Http\Client; use Swoole\Coroutine\Http\Client;
use Swoole\Coroutine\System; use Swoole\Coroutine\System;
class WxClient class HttpClient
{ {
private $host = 'api.weixin.qq.com'; private $host = 'api.weixin.qq.com';
@@ -17,6 +17,9 @@ class WxClient
private $url = ''; private $url = '';
private $isSSL = false; private $isSSL = false;
private $agent = ''; private $agent = '';
private $isFileStream = false;
private $errorCodeField = '';
private $errorMsgField = '';
const POST = 'post'; const POST = 'post';
const GET = 'get'; const GET = 'get';
@@ -24,22 +27,45 @@ class WxClient
const DELETE = 'delete'; const DELETE = 'delete';
const OPTIONS = 'option'; const OPTIONS = 'option';
/**
* HttpClient constructor.
*/
private function __construct() private function __construct()
{ {
} }
/** /**
* @return WxClient * @return HttpClient
*/ */
public static function getInstance() public static function NewRequest()
{ {
static $client = null; static $client = null;
if (!($client instanceof WxClient)) { if (!($client instanceof HttpClient)) {
$client = new WxClient(); $client = new HttpClient();
} }
return $client; return $client;
} }
/**
* @param string $name
* @return $this
*/
public function setErrorField(string $name)
{
$this->errorCodeField = $name;
return $this;
}
/**
* @param string $name
* @return $this
*/
public function setErrorMsgField(string $name)
{
$this->errorMsgField = $name;
return $this;
}
/** /**
* @param string $host * @param string $host
*/ */
@@ -102,11 +128,22 @@ class WxClient
$this->isSSL = $isSSL; $this->isSSL = $isSSL;
} }
/**
* @return bool
*/
public function getIsSSL() public function getIsSSL()
{ {
return $this->isSSL; return $this->isSSL;
} }
/**
* @param bool $isFIle
* 设置返回类型
*/
public function asFileStream($isFIle = true)
{
$this->isFileStream = $isFIle;
}
/** /**
* @param $url * @param $url
@@ -116,23 +153,13 @@ class WxClient
*/ */
private function request($url, $data = []) private function request($url, $data = [])
{ {
$data = $this->paramEncode($data);
if (function_exists('getIsCli') && getIsCli()) { if (function_exists('getIsCli') && getIsCli()) {
if (strpos($url, 'http://') !== FALSE) { return $this->coroutine($this->parseUrlHost($url), $url, $data);
$url = str_replace('http://', '', $url);
} else if (strpos($url, 'https://') !== FALSE) {
$url = str_replace('https://', '', $url);
} }
$explode = explode('/', $url); if ($this->isHttp($url) || $this->isHttps($url)) {
$ip = System::gethostbyname(array_shift($explode));
return $this->coroutine($ip, $url, $data);
}
if (
strpos($url, 'http://') === 0 ||
strpos($url, 'https://') === 0
) {
return $this->curl($url, $data); return $this->curl($url, $data);
} }
if ($this->isSSL) { if ($this->isSSL) {
return $this->curl('https://' . $this->host . '/' . $url, $data); return $this->curl('https://' . $this->host . '/' . $url, $data);
} else { } 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 $ip
* @param $url * @param $url
@@ -150,18 +211,15 @@ class WxClient
*/ */
private function coroutine($ip, $url, $data = []) private function coroutine($ip, $url, $data = [])
{ {
$_data = $this->paramEncode($data); $client = $this->generate_client($ip, $url, $data);
if ($this->method == 'get' && is_array($_data)) {
$url .= '?' . http_build_query($_data);
}
$client = $this->getClient($ip, $this->getHostPort(), $url, $data);
if ($client->statusCode < 0) { if ($client->statusCode < 0) {
throw new \Exception($client->errMsg); throw new \Exception($client->errMsg);
} }
$body = $client->body; $body = $client->body;
$client->close(); $client->close();
return $this->structure($body, $_data); return $this->structure($body, $data);
} }
/** /**
@@ -190,20 +248,18 @@ class WxClient
* @param $data * @param $data
* @return Client * @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)) { if (!empty($this->agent)) {
$this->header['User-Agent'] = $this->agent; $this->header['User-Agent'] = $this->agent;
} }
if (!empty($this->header)) { if (!empty($this->header)) {
$client->setHeaders($this->header); $client->setHeaders($this->header);
} }
switch (strtolower($this->method)) { if (strtolower($this->method) == self::GET) {
case self::GET: $client->get($url . '?' . $data);
$client->get($url); } else {
break;
default:
$client->post($url, $data); $client->post($url, $data);
} }
return $client; return $client;
@@ -215,43 +271,11 @@ class WxClient
* @return array|mixed|Result * @return array|mixed|Result
*/ */
private function curl($url, $data = []) 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(); $ch = curl_init();
if ($this->method == self::GET) { curl_setopt($ch, CURLOPT_URL, $this->createRequestUrl($url, $data));
if (is_array($_data)) {
$_data = http_build_query($_data);
}
$url = $url . '?' . $_data;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 超时设置 curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 超时设置
curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_HEADER, true);
if (!empty($this->header)) { if (!empty($this->header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $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_RETURNTRANSFER, TRUE);//返回内容
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); 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 $body
* @param $_data * @param $_data
* @param $header
* @return array|mixed|Result * @return array|mixed|Result
* 构建返回体 * 构建返回体
*/ */
private function structure($body, $_data) private function structure($body, $_data, $header = [])
{ {
$this->setIsSSL(false); $this->setIsSSL(false);
$this->setHeaders([]); $this->setHeaders([]);
if ($this->callback !== NULL) { if ($this->callback !== NULL) {
$result = call_user_func($this->callback, $body, $_data); $result = call_user_func($this->callback, $body, $_data, $header);
} else {
$result = $this->formatResponseBody($body);
}
$this->setCallback(null); $this->setCallback(null);
if (!is_array($result)) {
return $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); return new Result($result);
} }
/** /**
* @param $body * @return bool
* @return array|Result * check isPost Request
*/ */
private function formatResponseBody($body) public function isPost()
{ {
$result = []; return strtolower($this->method) === self::POST;
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'])) { * @return bool
$result['code'] = $results['errcode']; *
$result['message'] = $results['errmsg']; * check isGet Request
} else { */
$result['code'] = 0; public function isGet()
$result['message'] = 'system success.'; {
$result['data'] = $results; return strtolower($this->method) === self::GET;
}
return $result;
} }
/** /**
* @param $arr * @param $arr
* @param string $pushType
* *
* @return array|string * @return array|string
* 将请求参数进行编码 * 将请求参数进行编码
*/ */
private function paramEncode($arr, $pushType = 'post') private function paramEncode($arr)
{ {
if (!is_array($arr)) { if (!is_array($arr)) {
return $arr; return $arr;
@@ -335,8 +427,10 @@ class WxClient
foreach ($arr as $Key => $val) { foreach ($arr as $Key => $val) {
$_tmp[$Key] = $val; $_tmp[$Key] = $val;
} }
if ($this->isGet()) {
return ($pushType == 'post' ? $_tmp : http_build_query($_tmp)); return http_build_query($_tmp);
}
return $_tmp;
} }
/** /**
@@ -6,9 +6,11 @@
* Time: 10:23 * Time: 10:23
*/ */
namespace wchat; namespace common;
abstract class Miniprogarampage use common\Config;
abstract class Miniprogarampage implements Progaram
{ {
/** @var Config */ /** @var Config */
@@ -17,15 +19,61 @@ abstract class Miniprogarampage
/** @var Miniprogarampage $instance */ /** @var Miniprogarampage $instance */
protected static $instance = null; protected static $instance = null;
/** @var WxClient */ /** @var HttpClient */
protected $request = null; 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. * Miniprogarampage constructor.
*/ */
private function __construct() private function __construct()
{ {
$this->request = WxClient::getInstance(); $this->request = HttpClient::NewRequest();
$this->request->setIsSSL(true); $this->request->setIsSSL(true);
} }
@@ -49,6 +97,15 @@ abstract class Miniprogarampage
return static::$instance; return static::$instance;
} }
/**
* @param Config $config
* @return $this
*/
public function initConfig($config)
{
$this->config = $config;
return $this;
}
/** /**
* @return bool|mixed|string * @return bool|mixed|string
@@ -60,7 +117,7 @@ abstract class Miniprogarampage
if (!empty($access)) { if (!empty($access)) {
return $access; return $access;
} }
$this->request->setMethod(WxClient::GET); $this->request->setMethod(HttpClient::GET);
$data = $this->request->get('/cgi-bin/token', [ $data = $this->request->get('/cgi-bin/token', [
'grant_type' => 'client_credential', 'grant_type' => 'client_credential',
'appid' => $this->config->getAppid(), 'appid' => $this->config->getAppid(),
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace common;
interface Progaram
{
}
+7 -1
View File
@@ -1,6 +1,6 @@
<?php <?php
namespace wchat; namespace common;
/** /**
* Class Result * Class Result
@@ -144,11 +144,17 @@ class Result
return $this; return $this;
} }
/**
* @return mixed
*/
public function getMessage() public function getMessage()
{ {
return $this->message; return $this->message;
} }
/**
* @return mixed
*/
public function getCode() public function getCode()
{ {
return $this->code; return $this->code;
+7 -2
View File
@@ -14,8 +14,13 @@
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"wchat\\": "wx", "wchat\\": "wx",
"qq\\": "qq" "qq\\": "qq",
} "common\\": "common",
"officialaccount\\": "officialaccount"
},
"files": [
"Container.php"
]
}, },
"require": { "require": {
"php": ">= 7.0" "php": ">= 7.0"
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace officialaccount;
use common\HttpClient;
class AccessToken extends AfficialAccount
{
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace officialaccount;
use common\HttpClient;
use common\Miniprogarampage;
abstract class AfficialAccount extends Miniprogarampage
{
protected static $instance;
private $url = 'https://api.weixin.qq.com/cgi-bin/token?';
/**
* @return mixed
* @throws
*/
public function generateAccess_token()
{
if (!empty($this->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();
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
namespace officialaccount;
use officialaccount\dcaler\SnsInfo;
use common\HttpClient;
use officialaccount\dcaler\Authorization as DAuth;
class Authorization extends AfficialAccount
{
private $url = 'https://api.weixin.qq.com/cgi-bin/user/info';
private $turn = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=';
private $oauth2 = 'https://api.weixin.qq.com/sns/oauth2/access_token';
private $snsUserInfo = 'https://api.weixin.qq.com/sns/userinfo';
/**
* @param $code
* @return array|mixed|\wchat\Result
* @throws \Exception
*/
public function authorization_user_info($code)
{
$param = $this->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');
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace officialaccount;
use officialaccount\dcaler\Prpcrypt;
use officialaccount\dcaler\XMLParse;
class NewsManager extends AfficialAccount
{
const OK = 0;
const ValidateSignatureError = -40001;
const ParseXmlError = -40002;
const ComputeSignatureError = -40003;
const IllegalAesKey = -40004;
const ValidateAppidError = -40005;
const EncryptAESError = -40006;
const DecryptAESError = -40007;
const IllegalBuffer = -40008;
const EncodeBase64Error = -40009;
const DecodeBase64Error = -40010;
const GenReturnXmlError = -40011;
/**
* @param $code
* @return mixed|string
*/
public function toError($code)
{
$messages = [
self::ValidateSignatureError => '签名验证错误',
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';
}
/**
* 将公众平台回复用户的消息加密打包.
* <ol>
* <li>对要发送的消息进行AES-CBC加密</li>
* <li>生成安全签名</li>
* <li>将消息密文和安全签名打包成xml格式</li>
* </ol>
*
* @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;
}
/**
* 检验消息的真实性,并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名,进行签名验证</li>
* <li>若验证通过,则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @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);
}
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace officialaccount;
use common\HttpClient;
use common\Result;
class QrCode extends AfficialAccount
{
private $tick_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=';
private $temporary_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode';
private $permanent_qr_code_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=';
/**
* @param $scene_id
* @return mixed
* @throws \Exception
*/
public function temporaryQrCode($scene_id)
{
$requestParam['expire_seconds'] = 24 * 3600 * 30;
$requestParam['action_name'] = 'QR_SCENE';
$requestParam['action_info[scene][scene_id]'] = $scene_id;
$tick = $this->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');
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace officialaccount;
use common\HttpClient;
use common\Result;
class SourceMaterial extends AfficialAccount
{
private $uploadUrl = 'https://api.weixin.qq.com/cgi-bin/media/upload?';
private $getUploadUrl = 'https://api.weixin.qq.com/cgi-bin/media/get';
/**
* @param $file
* @return bool|mixed|Result
*/
public function ImageUpload($file)
{
if (!file_exists($file)) {
return $this->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();
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace officialaccount;
use common\HttpClient;
class Subscribe extends AfficialAccount
{
private $openid = '';
private $template_id = '';
private $url = '';
private $miniprogram = [];
private $scene = '';
private $title = '';
private $keywords = [];
private $pushUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=';
/**
* @param string $openid
* @return Subscribe
*/
public function setOpenid(string $openid): Subscribe
{
$this->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);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace officialaccount;
class Tag extends AfficialAccount
{
private $generate_url = 'https://api.weixin.qq.com/cgi-bin/tags/create?access_token=';
/**
* @param $tagName
* @return mixed
* @throws \Exception
*/
public function generate($tagName)
{
$url['tag[name]'] = $tagName;
$config = $this->config->getAccessToken();
$result = $this->request->post($this->generate_url . $config, $url);
if (!$result->isResultsOK()) {
throw new \Exception($result->getMessage());
}
return $result->getData();
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace officialaccount;
use common\Config;
class WxSDK
{
/**
* @param Config $config
* @return mixed
*/
public static function authorization(Config $config)
{
return Authorization::getInstance($config);
}
/**
* @param Config $config
* @return mixed
*/
public static function qrCode(Config $config)
{
return QrCode::getInstance($config);
}
/**
* @param Config $config
* @return mixed
*/
public static function news(Config $config)
{
return NewsManager::getInstance($config);
}
}
+360
View File
@@ -0,0 +1,360 @@
<?php
namespace officialaccount\dcaler;
class Authorization
{
private $subscribe;
private $openid;
private $nickname;
private $sex;
private $language;
private $city;
private $province;
private $country;
private $headimgurl;
private $subscribe_time;
private $unionid;
private $remark;
private $groupid;
private $tagid_list;
private $subscribe_scene;
private $qr_scene;
private $qr_scene_str;
/**
* @param $object
* @return Authorization
*/
public static function instance($object)
{
$class = new Authorization();
$class->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;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace officialaccount\dcaler;
class PKCS7Encoder
{
public static $block_size = 32;
/**
* @param $text
* @return string
*/
function encode($text)
{
$block_size = PKCS7Encoder::$block_size;
$text_length = strlen($text);
//计算需要填充的位数
$amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
if ($amount_to_pad == 0) {
$amount_to_pad = PKCS7Encoder::$block_size;
}
//获得补位所用的字符
$pad_chr = chr($amount_to_pad);
$tmp = "";
for ($index = 0; $index < $amount_to_pad; $index++) {
$tmp .= $pad_chr;
}
return $text . $tmp;
}
/**
* @param $text
* @return false|string
*/
function decode($text)
{
$pad = ord(substr($text, -1));
if ($pad < 1 || $pad > 32) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}
}
+119
View File
@@ -0,0 +1,119 @@
<?php
namespace officialaccount\dcaler;
use officialaccount\NewsManager;
class Prpcrypt
{
public $key;
/**
* Prpcrypt constructor.
* @param $k
*/
public function __construct($k)
{
$this->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;
}
}
+204
View File
@@ -0,0 +1,204 @@
<?php
namespace officialaccount\dcaler;
class SnsInfo
{
private $openid;
private $nickname;
private $sex;
private $province;
private $city;
private $country;
private $headimgurl;
private $privilege;
private $unionid;
/**
* @return mixed
*/
public function getOpenid()
{
return $this->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;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace officialaccount\dcaler;
use officialaccount\NewsManager;
class XMLParse
{
/**
* 提取出xml数据包中的加密消息
* @param string $xmltext 待提取的xml字符串
* @return array 提取出的加密消息字符串
*/
public function extract($xmltext)
{
try {
$xml = new \DOMDocument();
$xml->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 = "<xml>
<Encrypt><![CDATA[%s]]></Encrypt>
<MsgSignature><![CDATA[%s]]></MsgSignature>
<TimeStamp>%s</TimeStamp>
<Nonce><![CDATA[%s]]></Nonce>
</xml>";
return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
}
}
+11 -163
View File
@@ -8,35 +8,12 @@
namespace qq; namespace qq;
use wchat\Result; use common\Decode;
use wchat\WxClient; use common\HttpClient;
use wchat\Miniprogarampage; 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 * @param $code
* @return Result * @return Result
@@ -53,31 +30,12 @@ class Account extends Miniprogarampage
} }
$this->request->setHost('api.q.qq.com'); $this->request->setHost('api.q.qq.com');
$this->request->setMethod(WxClient::GET); $this->request->setMethod(HttpClient::GET);
$this->request->addHeader('Content-Type', 'text/xml'); $this->request->addHeader('Content-Type', 'text/xml');
return $this->request->get('sns/jscode2session', $param); 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 $encryptedData
* @param $iv * @param $iv
@@ -94,122 +52,12 @@ class Account extends Miniprogarampage
*/ */
public function decode($encryptedData, $iv, $sessionKey, $asArray = false) public function decode($encryptedData, $iv, $sessionKey, $asArray = false)
{ {
$config = QqSDK::getMiniProGaRamPage()->getConfig(); $decode = new Decode();
if (strlen($sessionKey) != 24) { $decode->setAppId($this->config->getAppid());
throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey); $decode->setIv($iv);
$decode->setEncryptedData($encryptedData);
$decode->setSessionKey($sessionKey);
return $decode->decode($asArray);
} }
$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;
}
/**
* @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;
}
} }
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace qq;
class GamePrePay extends SmallProgram
{
private $url = 'https://api.q.qq.com/api/json/openApiPay/GamePrePay?access_token=';
}
-314
View File
@@ -1,314 +0,0 @@
<?php
namespace qq;
use wchat\Miniprogarampage;
use wchat\Result;
use wchat\WxClient;
class Message extends Miniprogarampage
{
const TEXT = 0;
const IMAGE = 1;
const VOICE = 2;
const NEWS = 3;
const VIDEO = 4;
const MUSIC = 5;
const MINIPROGRAMPAGE = 6;
const WXCARD = 7;
private $openid = '';
private $msgData = [];
/**
* @param string $openid
*/
public function setOpenid(string $openid)
{
$this->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;
}
}
+2 -3
View File
@@ -3,10 +3,9 @@
namespace qq; namespace qq;
use wchat\Miniprogarampage; use common\Help;
use wchat\Help;
class Notify extends Miniprogarampage class Notify extends SmallProgram
{ {
public $appid = ''; public $appid = '';
public $mch_id = ''; public $mch_id = '';
-157
View File
@@ -1,157 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 9:49
*/
namespace qq;
use wchat\Miniprogarampage;
use wchat\Result;
class PublicTemplate extends Miniprogarampage
{
private $keywords = [];
private $templateId = '';
private $first = '';
private $remark = '';
private $openId = '';
private $defaultUrl = 'http://weixin.qq.com/download';
private $sendUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send';
private $miniprogram = [];
/**
* @param array $keywords
*/
public function setKeywords(array $keywords)
{
$this->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;
}
}
-116
View File
@@ -1,116 +0,0 @@
<?php
namespace qq;
use wchat\WxClient;
use wchat\Config;
class QqSDK
{
/** @var static $instance */
private static $instance = null;
/** @var Config $config */
private $config = null;
/**
* @return static
*/
public static function getMiniProGaRamPage()
{
if (static::$instance === null) {
static::$instance = new QqSDK();
}
return static::$instance;
}
/**
* @return Config
*/
public function getConfig()
{
return $this->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);
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace qq;
use common\HttpClient;
use common\Result;
class QrCode 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 $getwxacodeunlimit = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=';
private $savePath = __DIR__ . '/../../../';
/**
* @param $path
*/
public function setSavePath($path)
{
$this->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;
}
}
+5 -6
View File
@@ -8,12 +8,11 @@
namespace qq; namespace qq;
use wchat\Miniprogarampage; use common\HttpClient;
use wchat\Result; use common\Result;
use wchat\Help; use common\Help;
use wchat\WxClient;
class Recharge extends Miniprogarampage class Recharge extends SmallProgram
{ {
private $money = 0; private $money = 0;
@@ -175,7 +174,7 @@ class Recharge extends Miniprogarampage
private function send($url, $data) private function send($url, $data)
{ {
$this->request->setIsSSL(true); $this->request->setIsSSL(true);
$this->request->setMethod(WxClient::POST); $this->request->setMethod(HttpClient::POST);
$this->request->addHeader('Content-Type', 'text/xml'); $this->request->addHeader('Content-Type', 'text/xml');
return $this->request->send($url, $data); return $this->request->send($url, $data);
} }
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace qq;
use common\Miniprogarampage;
class SmallProgram extends Miniprogarampage
{
protected static $instance;
private $url = 'https://api.q.qq.com/api/getToken';
/**
* @return mixed|null
*/
public function generateAccess_token()
{
if (!empty($this->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');
}
}
+136
View File
@@ -0,0 +1,136 @@
<?php
namespace qq;
use common\Result;
class Subject extends SmallProgram
{
private $keywords = [];
private $templateId = '';
private $openId = '';
private $defaultUrl = '';
private $page = 'pages/index/index';
private $emphasis_keyword = '';
private $sendUrl = 'https://api.q.qq.com/api/json/subscribe/SendSubscriptionMessage';
/**
* @param array $keywords
*/
public function setKeywords(array $keywords)
{
$this->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;
}
}
+2 -5
View File
@@ -9,12 +9,9 @@
namespace qq; namespace qq;
use wchat\Miniprogarampage; use common\Result;
use wchat\Result;
use wchat\Help;
use wchat\WxClient;
class Template extends Miniprogarampage class Template extends SmallProgram
{ {
private $keywords = []; private $keywords = [];
+1 -20
View File
@@ -4,29 +4,10 @@
namespace qq; 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');
}
} }
+44 -10
View File
@@ -6,7 +6,10 @@
* Time: 18:38 * Time: 18:38
*/ */
$config = new \wchat\Config(); use officialaccount\AccessToken;
use wchat\Recharge;
$config = new \common\Config();
$config->setAppid(''); $config->setAppid('');
$config->setAppsecret(''); $config->setAppsecret('');
$config->setMchId(''); $config->setMchId('');
@@ -16,28 +19,59 @@ $config->setDeviceInfo('');
$config->setAccessToken(''); $config->setAccessToken('');
$instance = \wchat\Wx::getMiniProGaRamPage(); /** @var AccessToken $container */
$instance->setConfig($config); $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->setSavePath('');
$account->login(''); $account->login('');
try {
$account->createwxaqrcode('pages/index/index', 200); $account->createwxaqrcode('pages/index/index', 200);
$account->getwxacode('pages/index/index', 150, true); $account->getwxacode('pages/index/index', 150, true);
$account->getwxacodeunlimit('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->setOpenid('');
try {
$message->sendCardNews(''); $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(); }
try {
/** @var \wchat\Template $template */
$template = Container::newInstance(\wchat\Template::class, $config);
$template->setOpenid('');
$template->setOpenId(''); $template->setOpenId('');
$template->setFormId(''); $template->setFormId('');
$template->setTemplateId(''); $template->setTemplateId('');
$template->setPage(''); $template->setPage('');
$template->sendTemplate(); $template->sendTemplate();
} catch (Exception $exception) {
}
+17 -32
View File
@@ -7,7 +7,12 @@
*/ */
namespace wchat; 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='; 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['js_code'] = $code;
$param['grant_type'] = 'authorization_code'; $param['grant_type'] = 'authorization_code';
$this->request->setMethod(WxClient::GET); $this->request->setMethod(HttpClient::GET);
$this->request->addHeader('Content-Type', 'text/xml'); $this->request->addHeader('Content-Type', 'text/xml');
return $this->request->get('sns/jscode2session', $param); return $this->request->get('sns/jscode2session', $param);
@@ -62,7 +67,7 @@ class Account extends Miniprogarampage
'lang' => 'zh_CN' 'lang' => 'zh_CN'
]; ];
$this->request->setMethod(WxClient::GET); $this->request->setMethod(HttpClient::GET);
$this->request->setIsSSL(true); $this->request->setIsSSL(true);
return $this->request->get($this->publicInfo, $query); return $this->request->get($this->publicInfo, $query);
} }
@@ -84,33 +89,13 @@ class Account extends Miniprogarampage
*/ */
public function decode($encryptedData, $iv, $sessionKey, $asArray = false) public function decode($encryptedData, $iv, $sessionKey, $asArray = false)
{ {
$config = Wx::getMiniProGaRamPage()->getConfig(); $decode = new Decode();
if (strlen($sessionKey) != 24) { $decode->setSessionKey($sessionKey);
throw new \Exception('encodingAesKey 非法', $this->IllegalAesKey); $decode->setEncryptedData($encryptedData);
} $decode->setAppId($this->config->getAppid());
$decode->setIv($iv);
$aesKey = base64_decode($sessionKey); return $decode->decode($asArray);
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;
} }
@@ -127,7 +112,7 @@ class Account extends Miniprogarampage
$sendBody['path'] = $path; $sendBody['path'] = $path;
$sendBody['width'] = $width; $sendBody['width'] = $width;
$this->request->setMethod(WxClient::POST); $this->request->setMethod(HttpClient::POST);
$this->request->setCallback([$this, 'saveByPath']); $this->request->setCallback([$this, 'saveByPath']);
return $this->request->post($url, $sendBody); return $this->request->post($url, $sendBody);
@@ -155,7 +140,7 @@ class Account extends Miniprogarampage
$url = $this->getwxacode . $this->getAccessToken(); $url = $this->getwxacode . $this->getAccessToken();
$this->request->setMethod(WxClient::POST); $this->request->setMethod(HttpClient::POST);
$this->request->setCallback([$this, 'saveByPath']); $this->request->setCallback([$this, 'saveByPath']);
return $this->request->post($url, $sendBody); return $this->request->post($url, $sendBody);
} }
@@ -182,7 +167,7 @@ class Account extends Miniprogarampage
$url = $this->getwxacodeunlimit . $this->getAccessToken(); $url = $this->getwxacodeunlimit . $this->getAccessToken();
$this->request->setMethod(WxClient::POST); $this->request->setMethod(HttpClient::POST);
$this->request->setCallback([$this, 'saveByPath']); $this->request->setCallback([$this, 'saveByPath']);
return $this->request->post($url, $sendBody); return $this->request->post($url, $sendBody);
} }
+5 -4
View File
@@ -3,8 +3,9 @@
namespace wchat; namespace wchat;
use common\HttpClient;
class Message extends Miniprogarampage use common\Result;
class Message extends SmallProgram
{ {
const TEXT = 0; const TEXT = 0;
const IMAGE = 1; const IMAGE = 1;
@@ -253,7 +254,7 @@ class Message extends Miniprogarampage
$data = ['media' => $real_path, 'description[title]' => $title, 'description[introduction]' => $introduction]; $data = ['media' => $real_path, 'description[title]' => $title, 'description[introduction]' => $introduction];
} }
$this->request->setMethod(WxClient::POST); $this->request->setMethod(HttpClient::POST);
/** @var Result $body */ /** @var Result $body */
$data = $this->request->post($url, $data); $data = $this->request->post($url, $data);
@@ -298,7 +299,7 @@ class Message extends Miniprogarampage
$data = json_encode($this->msgData, JSON_UNESCAPED_UNICODE); $data = json_encode($this->msgData, JSON_UNESCAPED_UNICODE);
$url = '/cgi-bin/message/custom/send?access_token=' . $this->getAccessToken(); $url = '/cgi-bin/message/custom/send?access_token=' . $this->getAccessToken();
$this->request->setMethod(WxClient::POST); $this->request->setMethod(HttpClient::POST);
/** @var Result $body */ /** @var Result $body */
$body = $this->request->post($url, $data); $body = $this->request->post($url, $data);
+1 -1
View File
@@ -4,7 +4,7 @@
namespace wchat; namespace wchat;
class Notify extends Miniprogarampage class Notify extends SmallProgram
{ {
public $appid = ''; public $appid = '';
public $mch_id = ''; public $mch_id = '';
+3 -1
View File
@@ -8,7 +8,9 @@
namespace wchat; namespace wchat;
class PublicTemplate extends Miniprogarampage use common\Result;
class PublicTemplate extends SmallProgram
{ {
private $keywords = []; private $keywords = [];
+4 -1
View File
@@ -8,7 +8,10 @@
namespace wchat; namespace wchat;
class Recharge extends Miniprogarampage use common\Result;
use common\Help;
class Recharge extends SmallProgram
{ {
private $money = 0; private $money = 0;
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace wchat;
use common\Miniprogarampage;
class SmallProgram extends Miniprogarampage
{
protected static $instance;
private $url = 'https://api.weixin.qq.com/cgi-bin/token';
/**
* @return mixed
* @throws \Exception
*/
public function generateAccess_token()
{
if (!empty($this->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();
}
}
+3 -1
View File
@@ -4,7 +4,9 @@
namespace wchat; namespace wchat;
class Subject extends Miniprogarampage use common\Result;
class Subject extends SmallProgram
{ {
+3 -1
View File
@@ -8,7 +8,9 @@
namespace wchat; namespace wchat;
class Template extends Miniprogarampage use common\Result;
class Template extends SmallProgram
{ {
private $keywords = []; private $keywords = [];
+1 -20
View File
@@ -4,28 +4,9 @@
namespace wchat; 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');
}
} }
-123
View File
@@ -1,123 +0,0 @@
<?php
namespace wchat;
class Wx
{
/** @var static $instance */
private static $instance = null;
/** @var Config $config */
private $config = null;
/**
* @return static
*/
public static function getMiniProGaRamPage()
{
if (static::$instance === null) {
static::$instance = new Wx();
}
return static::$instance;
}
/**
* @return Config
*/
public function getConfig()
{
return $this->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);
}
}