文件
mashangyoujiu/Application/Common/Lib/MaiyatianBase.class.php

93 行
3.0 KiB
PHP
可执行文件

<?php
namespace Common\Lib;
class MaiyatianBase {
protected $store = null;
protected $appKey = '';
protected $appSecret = '';
protected $redirectUri = '';
public function __construct()
{
$this->appKey = C('MYT_APPKEY');
$this->appSecret = C('MYT_APPSECRET');
$this->redirectUri = C('MYT_REDIRECT_URI');
}
public function sign(array $data, $command, $token = '')
{
$signData = [
'app_key' => $this->appKey,
'command' => $command,
'data' => $data['data'],
'timestamp' => $data['timestamp'],
'token' => $token,
];
ksort($signData);
$dataToSign = '';
foreach ($signData as $k => $v) {
$dataToSign .= $k . '=' . $v . ',';
}
$dataToSign = substr($dataToSign, 0, -1);
$hash = hash_hmac('sha256', $dataToSign, $this->appSecret, true);
$signData['signature'] = strtr(base64_encode($hash), '+/', '-_');
unset($signData['command']);
return $signData;
}
protected function request($url, $data)
{
$token = '';
$command = explode('/', $url);
if (!in_array($command, ['access_token']) && $this->store) {
$token = $this->store['maiyatian_token'];
}
$data = array_merge($this->sign(array_merge([
'timestamp' => round(microtime(true) * 1000),
'data' => json_encode($data)
]), $command[count($command) - 1], $token), [
'request_id' => strtoupper(str_replace([chr(123), chr(125)], '', \Org\Util\String::uuid())),
]);
$response = $this->post(C('MYT_DOMAIN') . $url, $data);
if (C('MYT_LOGS')) {
(new \Common\Model\LogsModel())->add([
'url' => C('MYT_DOMAIN') . $url,
'data' => @json_encode($data, JSON_UNESCAPED_UNICODE),
'response' => @json_encode($response, JSON_UNESCAPED_UNICODE),
'create_time' => time(),
]);
}
return $response;
}
private function post($url, $data = [])
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if (is_array($data)) {
$data = json_encode($data);
}
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length:' . strlen($data),
'Cache-Control: no-cache',
'Pragma: no-cache'
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return @json_decode($result, true);
}
}