Commit af63ccd6 authored by 杨培's avatar 杨培

加入更新用户信息API

数据库操作加入转义方法
parent 932a4770
<?php
/**
* Created by PhpStorm.
* User: pader
* Date: 2017/8/22
* Time: 18:07
*/
require '../class/connect.php';
require '../class/db_sql.php';
require '../class/q_functions.php';
require '../extend/internalApi/autoload.php';
require '../config/config_ibanshou.php';
$link = db_connect();
$empire = new mysqlquery();
class InternalApiWrap {
/**
* 同步更新用户信息
*
* @param int $uid
* @param array $data 用户中心传递来的信息可能包括以下字段 nickname, avatar, phone_number, updated_at
* @return bool
*/
public static function userUpdateSync($uid, $data)
{
global $empire, $link;
require_once '../member/class/user.php';
$member = $empire->fetch1("SELECT ".eReturnSelectMemberF('*')." FROM ".eReturnMemberTable()." WHERE ".egetmf('ucid')."={$uid} limit 1");
if (!$member) {
return false;
}
$updateSql = '';
foreach ($data as $k => $v) {
switch ($k) {
case 'avatar': $updateSql .= "`avatar`=".$empire->quote($v).","; break;
case 'nickname': $updateSql .= "`nickname`=".$empire->quote($v).","; break;
}
}
if ($updateSql) {
$updateSql = substr($updateSql, 0, -1);
$empire->query("UPDATE ".eReturnMemberTable()." SET $updateSql WHERE ".egetmf('userid')."='".$member['userid']."'");
return true;
}
return true;
}
}
$server = new \internalApi\base\Server($config['wxh.internal']['server_secret']);
$server->setApiMap([
'user' => [
'updateSync' => ['InternalApiWrap::userUpdateSync', 'uid', 'data']
]
]);
$server->invoke();
......@@ -110,5 +110,16 @@ class mysqlquery
{
return mysqli_affected_rows($GLOBALS['link']);
}
/**
* 转义并包裹指定字符串以使其可安全用于查询
*
* @param string $str
* @return string
*/
function quote($str)
{
return '\''.mysqli_real_escape_string($GLOBALS['link'], $str).'\'';
}
}
?>
\ No newline at end of file
......@@ -31,9 +31,7 @@ $config = [
//wxh_internal_api
'wxh.internal' => [
'server' => [
'secret' => 'U2FsdGVkX19ZiutUoO6F',
],
'server_secret' => 'TveYDczsq7LTllIUlM5t',
'client' => [
'ucenter' => [
'apiUrl' => 'http://u.yunya.com/api/server',
......
<?php
/**
* Created by PhpStorm.
* User: pader
* Date: 2017/7/6
* Time: 11:46
*/
namespace internalApi\base;
/**
* 接口异常
*
* 本异常为目标接口业务异常
* 所的目标接口抛出的异常到客户端后均抛出为本异常
*
* @package internalApi\base
*/
class ApiException extends \Exception
{
}
\ No newline at end of file
......@@ -19,235 +19,248 @@ namespace internalApi\base;
class Client
{
public $debug = false;
public $name;
protected $clientId;
protected $clientSecret;
protected $apiUrl;
protected $remoteIp;
protected static $instance = [];
protected static $config = [];
/**
* 获取 API 集的客户端实例
* 每个 API 集有一个实例用于签名和请求处理
*
* @return static
*/
protected static function getInstance()
{
$name = self::name();
if (!isset(self::$instance[$name])) {
self::$instance[$name] = new self($name);
}
return self::$instance[$name];
}
/**
* 获取 API 集的名称
*
* 如 internalApi\ucenter\Member 则名称为 ucenter
*
* @return bool|string
*/
public static function name()
{
$className = static::class;
$subName = strstr($className, '\\');
return substr($subName, 1, strpos($subName, '\\', 1)-1);
}
public function __construct($name)
{
if (isset(static::$config[$name])) {
foreach (static::$config[$name] as $k => $v) {
if ($this->$k === null) {
$this->$k = $v;
}
}
}
foreach (['clientId', 'clientSecret', 'apiUrl'] as $prop) {
if ($this->$prop === null) {
throw new ClientException("InternalApi $name initialize failed, \${$prop} not set!");
}
}
$this->name = $name;
}
public static function setDebug($debug=true)
{
$instance = self::getInstance();
$instance->debug = $debug;
}
public static function config($config)
{
self::$config = $config;
}
/**
* 调用请求,获取数据
*
* @param string $api
* @param array $params
* @return mixed
* @throws ClientException API 请求失败时,会抛出此异常
*/
protected static function call($api, $params=[])
{
$instance = self::getInstance();
$url = $instance->apiUrl.(strpos($instance->apiUrl, '?') !== false ? '&' : '?').'api='.urlencode($api);
list($sign, $timestamp, $nonce) = $instance->signature($api, $params);
$url .= "&client_id={$instance->clientId}&sign={$sign}&timestamp={$timestamp}&nonce={$nonce}";
list($httpCode, $response) = $instance->request($url, $params);
if ($httpCode == 403 && substr($response, 0, 6) === 'error:') {
$message = substr($response, 6);
throw new ClientException("接口 $api 调用失败: " . $message);
} elseif ($httpCode === 0) {
throw new ClientException('接口请求异常: '.$response, $httpCode);
} elseif ($httpCode != 200 || $response === false) {
throw new ClientException('接口响应异常: '.$response, $httpCode);
}
$data = @json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ClientException('接口返回数据异常: ' . $response);
}
return $data;
}
/**
* 对请求进程签名
*
* @param string $api
* @param array $params
* @return array
*/
protected function signature($api, $params)
{
$timestamp = time();
$nonce = uniqid();
ksort($params);
$str = $api.http_build_query($params).$this->clientId.$this->clientSecret.$timestamp.$nonce;
$sign = md5($str);
return [$sign, $timestamp, $nonce];
}
protected function request($url, $post='', $headers=[]) {
//如果设置了远程IP,则直接用IP连接,省去解析
if ($this->remoteIp) {
$host = parse_url($url, PHP_URL_HOST);
$url = substr_replace($url, $this->remoteIp, strpos($url, $host), strlen($host));
//$url = preg_replace('/^(https?:\/\/)[^\/]+/i', '${1}'.$this->remoteIp, $url, 1);
$headers[] = "Host: $host";
}
$ci = curl_init($url);
//添加客户端信息以辨服务端识别和调试
$userAgent = 'PHP/'.PHP_VERSION.' ('.PHP_OS.') Client/'.$this->clientId;
if (isset($_SERVER['HTTP_HOST'])) {
$userAgent .= ' ('.$_SERVER['HTTP_HOST'].')';
}
$curl = curl_version();
$userAgent .= " cURL/{$curl['version']} ({$curl['ssl_version']})";
//基础设置
curl_setopt_array($ci, [
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 8,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HEADER => false,
CURLOPT_USERAGENT => $userAgent
]);
//POST 请求
if ($post) {
$body = is_array($post) ? http_build_query($post) : $post;
curl_setopt_array($ci, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body
]);
}
//优化
$headers[] = 'Expect:';
curl_setopt_array($ci, [
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
//CURLOPT_DNS_USE_GLOBAL_CACHE => false
]);
//调试
if ($this->debug) {
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$responseHeaders = '';
curl_setopt($ci, CURLOPT_HEADERFUNCTION, function ($ci, $header) use (&$responseHeaders) {
$responseHeaders .= $header;
return strlen($header);
});
}
$response = curl_exec($ci);
$httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($response === false) {
$errno = curl_errno($ci);
$errmsg = curl_error($ci);
$response = "[$errno] $errmsg";
}
//获取调试信息
if ($this->debug) {
$httpInfo = curl_getinfo($ci);
}
curl_close($ci);
if ($this->debug) {
echo "<pre>\r\n=====INFO=====\r\n";
echo "Request URL: $url\r\n",
"Remote Address: {$httpInfo['primary_ip']}:{$httpInfo['primary_port']}\r\n",
"Local Address: {$httpInfo['local_ip']}:{$httpInfo['local_port']}\r\n",
"Namelookup Time: {$httpInfo['namelookup_time']}\r\n",
"Connect Time: {$httpInfo['connect_time']}\r\n",
"Pre Transfer Time: {$httpInfo['pretransfer_time']}\r\n",
"Start Transfer Time: {$httpInfo['starttransfer_time']}\r\n",
"File Time: {$httpInfo['filetime']}\r\n",
"Total Time: {$httpInfo['total_time']}\r\n";
if (isset($errno)) {
echo "\r\n=====ERROR=====\r\nErrorNo: $errno\r\nErrorMsg: $errmsg\r\n";
}
echo "\r\n=====REQUEST=====\r\n",$httpInfo['request_header'];
if (isset($body)) {
echo $body."\r\n";
}
echo "\r\n=====RESPONSE=====\r\n",$responseHeaders,$response;
echo "\r\n</pre>";
}
return [$httpCode, $response];
}
public $debug = false;
public $name;
protected $clientId;
protected $clientSecret;
protected $apiUrl;
protected $remoteIp;
protected static $instance = [];
protected static $config = [];
/**
* 获取 API 集的客户端实例
* 每个 API 集有一个实例用于签名和请求处理
*
* @return static
*/
protected static function getInstance()
{
$name = self::name();
if (!isset(self::$instance[$name])) {
self::$instance[$name] = new self($name);
}
return self::$instance[$name];
}
/**
* 获取 API 集的名称
*
* 如 internalApi\ucenter\Member 则名称为 ucenter
*
* @return bool|string
*/
public static function name()
{
$className = static::class;
$subName = strstr($className, '\\');
return substr($subName, 1, strpos($subName, '\\', 1)-1);
}
public function __construct($name)
{
if (isset(static::$config[$name])) {
foreach (static::$config[$name] as $k => $v) {
if ($this->$k === null) {
$this->$k = $v;
}
}
}
foreach (['clientId', 'clientSecret', 'apiUrl'] as $prop) {
if ($this->$prop === null) {
throw new ClientException("InternalApi $name initialize failed, \${$prop} not set!");
}
}
$this->name = $name;
}
public static function setDebug($debug=true)
{
$instance = self::getInstance();
$instance->debug = $debug;
}
public static function config($config)
{
self::$config = $config;
}
/**
* 调用请求,获取数据
*
* @param string $api
* @param array $params
* @return mixed
* @throws ClientException|ApiException 请求过程出错会抛出ClientException,若源API抛异常,则会抛出ApiException
*/
protected static function call($api, $params=[])
{
$instance = self::getInstance();
$url = $instance->apiUrl.(strpos($instance->apiUrl, '?') !== false ? '&' : '?').'api='.urlencode($api);
list($sign, $timestamp, $nonce) = $instance->signature($api, $params);
$url .= "&client_id={$instance->clientId}&sign={$sign}&timestamp={$timestamp}&nonce={$nonce}";
list($httpCode, $response) = $instance->request($url, $params);
if ($httpCode == 200 && $response !== false) {
$data = @json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ClientException("接口 $api 返回数据异常: " . $response);
}
return $data;
}
if ($httpCode == 403 && substr($response, 0, 6) === 'error:') {
$message = substr($response, 6);
throw new ClientException("接口 $api 调用失败: " . $message);
}
if ($httpCode == 500 && substr($response, 0, 10) === 'exception:') {
$e = substr($response, 10);
$e = json_decode($e, true);
throw new ApiException("{$e['class']}: {$e['message']}", $e['code']);
}
if ($httpCode == 0) {
throw new ClientException("接口 $api 请求异常: ".$response);
} else {
throw new ClientException("接口 $api 响应异常: ".$response, $httpCode);
}
}
/**
* 对请求进程签名
*
* @param string $api
* @param array $params
* @return array
*/
protected function signature($api, $params)
{
$timestamp = time();
$nonce = uniqid();
ksort($params);
$str = $api.http_build_query($params).$this->clientId.$this->clientSecret.$timestamp.$nonce;
$sign = md5($str);
return [$sign, $timestamp, $nonce];
}
protected function request($url, $post='', $headers=[]) {
//如果设置了远程IP,则直接用IP连接,省去解析
if ($this->remoteIp) {
$host = parse_url($url, PHP_URL_HOST);
$url = substr_replace($url, $this->remoteIp, strpos($url, $host), strlen($host));
//$url = preg_replace('/^(https?:\/\/)[^\/]+/i', '${1}'.$this->remoteIp, $url, 1);
$headers[] = "Host: $host";
}
$ci = curl_init($url);
//添加客户端信息以辨服务端识别和调试
$userAgent = 'PHP/'.PHP_VERSION.' ('.PHP_OS.') Client/'.$this->clientId;
if (isset($_SERVER['HTTP_HOST'])) {
$userAgent .= ' ('.$_SERVER['HTTP_HOST'].')';
}
$curl = curl_version();
$userAgent .= " cURL/{$curl['version']} ({$curl['ssl_version']})";
//基础设置
curl_setopt_array($ci, [
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 8,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HEADER => false,
CURLOPT_USERAGENT => $userAgent
]);
//POST 请求
if ($post) {
$body = is_array($post) ? http_build_query($post) : $post;
curl_setopt_array($ci, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body
]);
}
//优化
$headers[] = 'Expect:';
curl_setopt_array($ci, [
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
//CURLOPT_DNS_USE_GLOBAL_CACHE => false
]);
//调试
if ($this->debug) {
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$responseHeaders = '';
curl_setopt($ci, CURLOPT_HEADERFUNCTION, function ($ci, $header) use (&$responseHeaders) {
$responseHeaders .= $header;
return strlen($header);
});
}
$response = curl_exec($ci);
$httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($response === false) {
$errno = curl_errno($ci);
$errmsg = curl_error($ci);
$response = "[$errno] $errmsg";
}
//获取调试信息
if ($this->debug) {
$httpInfo = curl_getinfo($ci);
}
curl_close($ci);
if ($this->debug) {
$info = "=====INFO=====\r\n"
."Request URL: $url\r\n"
."Remote Address: {$httpInfo['primary_ip']}:{$httpInfo['primary_port']}\r\n"
."Local Address: {$httpInfo['local_ip']}:{$httpInfo['local_port']}\r\n"
."Namelookup Time: {$httpInfo['namelookup_time']}\r\n"
."Connect Time: {$httpInfo['connect_time']}\r\n"
."Pre Transfer Time: {$httpInfo['pretransfer_time']}\r\n"
."Start Transfer Time: {$httpInfo['starttransfer_time']}\r\n"
."File Time: {$httpInfo['filetime']}\r\n"
."Total Time: {$httpInfo['total_time']}\r\n";
if (isset($errno)) {
$info .= "\r\n=====ERROR=====\r\nErrorNo: $errno\r\nErrorMsg: $errmsg\r\n";
}
$info .= "\r\n=====REQUEST=====\r\n{$httpInfo['request_header']}";
if (isset($body)) {
$info .= $body."\r\n";
}
$info .= "\r\n=====RESPONSE=====\r\n{$responseHeaders}{$response}";
if (PHP_SAPI == 'cli' || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') || empty($_SERVER['HTTP_USER_AGENT'])) {
echo $info."\r\n";
} else {
echo '<pre>' . htmlspecialchars($info) . '</pre>';
}
}
return [$httpCode, $response];
}
}
\ No newline at end of file
......@@ -8,7 +8,14 @@
namespace internalApi\base;
class ClientException extends \ErrorException
/**
* 客户端异常
*
* 本异常为非业务异常
* 如调用请求发送失败,数据异常,网络异常,接口参数不一致等程序和服务器环境导致的无法正常发送和解析接口的请求问题
*
* @package internalApi\base
*/
class ClientException extends \Exception
{
}
\ No newline at end of file
......@@ -94,7 +94,11 @@ class Server
}
}
$data = call_user_func_array($callable, $params);
try {
$data = call_user_func_array($callable, $params);
} catch (\Exception $e) {
$this->responseException($e);
}
if ($return) {
return $data;
......@@ -104,6 +108,24 @@ class Server
}
}
/**
* @param \Exception $e
*/
public function responseException($e)
{
header('HTTP/1.0 500 Internal Server Error');
$exception = [
'class' => get_class($e),
'code' => $e->getCode(),
'message' => $e->getMessage(),
'line' => $e->getFile(),
'file' => $e->getFile(),
'traceString' => $e->getTraceAsString()
];
echo 'exception:'.json_encode($exception, JSON_UNESCAPED_UNICODE);
exit;
}
public function responseError($message)
{
header('HTTP/1.0 403 Forbidden');
......
<?php
/**
* Created by PhpStorm.
* User: pader
* Date: 2017/6/27
* Time: 16:44
*/
namespace internalApi\base;
class ServerException extends \Exception
{
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment