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 ...@@ -110,5 +110,16 @@ class mysqlquery
{ {
return mysqli_affected_rows($GLOBALS['link']); 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 = [ ...@@ -31,9 +31,7 @@ $config = [
//wxh_internal_api //wxh_internal_api
'wxh.internal' => [ 'wxh.internal' => [
'server' => [ 'server_secret' => 'TveYDczsq7LTllIUlM5t',
'secret' => 'U2FsdGVkX19ZiutUoO6F',
],
'client' => [ 'client' => [
'ucenter' => [ 'ucenter' => [
'apiUrl' => 'http://u.yunya.com/api/server', '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; ...@@ -19,235 +19,248 @@ namespace internalApi\base;
class Client class Client
{ {
public $debug = false; public $debug = false;
public $name; public $name;
protected $clientId; protected $clientId;
protected $clientSecret; protected $clientSecret;
protected $apiUrl; protected $apiUrl;
protected $remoteIp; protected $remoteIp;
protected static $instance = []; protected static $instance = [];
protected static $config = []; protected static $config = [];
/** /**
* 获取 API 集的客户端实例 * 获取 API 集的客户端实例
* 每个 API 集有一个实例用于签名和请求处理 * 每个 API 集有一个实例用于签名和请求处理
* *
* @return static * @return static
*/ */
protected static function getInstance() protected static function getInstance()
{ {
$name = self::name(); $name = self::name();
if (!isset(self::$instance[$name])) { if (!isset(self::$instance[$name])) {
self::$instance[$name] = new self($name); self::$instance[$name] = new self($name);
} }
return self::$instance[$name]; return self::$instance[$name];
} }
/** /**
* 获取 API 集的名称 * 获取 API 集的名称
* *
* 如 internalApi\ucenter\Member 则名称为 ucenter * 如 internalApi\ucenter\Member 则名称为 ucenter
* *
* @return bool|string * @return bool|string
*/ */
public static function name() public static function name()
{ {
$className = static::class; $className = static::class;
$subName = strstr($className, '\\'); $subName = strstr($className, '\\');
return substr($subName, 1, strpos($subName, '\\', 1)-1); return substr($subName, 1, strpos($subName, '\\', 1)-1);
} }
public function __construct($name) public function __construct($name)
{ {
if (isset(static::$config[$name])) { if (isset(static::$config[$name])) {
foreach (static::$config[$name] as $k => $v) { foreach (static::$config[$name] as $k => $v) {
if ($this->$k === null) { if ($this->$k === null) {
$this->$k = $v; $this->$k = $v;
} }
} }
} }
foreach (['clientId', 'clientSecret', 'apiUrl'] as $prop) { foreach (['clientId', 'clientSecret', 'apiUrl'] as $prop) {
if ($this->$prop === null) { if ($this->$prop === null) {
throw new ClientException("InternalApi $name initialize failed, \${$prop} not set!"); throw new ClientException("InternalApi $name initialize failed, \${$prop} not set!");
} }
} }
$this->name = $name; $this->name = $name;
} }
public static function setDebug($debug=true) public static function setDebug($debug=true)
{ {
$instance = self::getInstance(); $instance = self::getInstance();
$instance->debug = $debug; $instance->debug = $debug;
} }
public static function config($config) public static function config($config)
{ {
self::$config = $config; self::$config = $config;
} }
/** /**
* 调用请求,获取数据 * 调用请求,获取数据
* *
* @param string $api * @param string $api
* @param array $params * @param array $params
* @return mixed * @return mixed
* @throws ClientException API 请求失败时,会抛出此异常 * @throws ClientException|ApiException 请求过程出错会抛出ClientException,若源API抛异常,则会抛出ApiException
*/ */
protected static function call($api, $params=[]) protected static function call($api, $params=[])
{ {
$instance = self::getInstance(); $instance = self::getInstance();
$url = $instance->apiUrl.(strpos($instance->apiUrl, '?') !== false ? '&' : '?').'api='.urlencode($api); $url = $instance->apiUrl.(strpos($instance->apiUrl, '?') !== false ? '&' : '?').'api='.urlencode($api);
list($sign, $timestamp, $nonce) = $instance->signature($api, $params); list($sign, $timestamp, $nonce) = $instance->signature($api, $params);
$url .= "&client_id={$instance->clientId}&sign={$sign}&timestamp={$timestamp}&nonce={$nonce}"; $url .= "&client_id={$instance->clientId}&sign={$sign}&timestamp={$timestamp}&nonce={$nonce}";
list($httpCode, $response) = $instance->request($url, $params); list($httpCode, $response) = $instance->request($url, $params);
if ($httpCode == 403 && substr($response, 0, 6) === 'error:') { if ($httpCode == 200 && $response !== false) {
$message = substr($response, 6); $data = @json_decode($response, true);
throw new ClientException("接口 $api 调用失败: " . $message); if (json_last_error() !== JSON_ERROR_NONE) {
} elseif ($httpCode === 0) { throw new ClientException("接口 $api 返回数据异常: " . $response);
throw new ClientException('接口请求异常: '.$response, $httpCode); }
} elseif ($httpCode != 200 || $response === false) { return $data;
throw new ClientException('接口响应异常: '.$response, $httpCode); }
}
if ($httpCode == 403 && substr($response, 0, 6) === 'error:') {
$data = @json_decode($response, true); $message = substr($response, 6);
throw new ClientException("接口 $api 调用失败: " . $message);
if (json_last_error() !== JSON_ERROR_NONE) { }
throw new ClientException('接口返回数据异常: ' . $response);
} if ($httpCode == 500 && substr($response, 0, 10) === 'exception:') {
$e = substr($response, 10);
return $data; $e = json_decode($e, true);
} throw new ApiException("{$e['class']}: {$e['message']}", $e['code']);
}
/**
* 对请求进程签名 if ($httpCode == 0) {
* throw new ClientException("接口 $api 请求异常: ".$response);
* @param string $api } else {
* @param array $params throw new ClientException("接口 $api 响应异常: ".$response, $httpCode);
* @return array }
*/ }
protected function signature($api, $params)
{ /**
$timestamp = time(); * 对请求进程签名
$nonce = uniqid(); *
ksort($params); * @param string $api
$str = $api.http_build_query($params).$this->clientId.$this->clientSecret.$timestamp.$nonce; * @param array $params
$sign = md5($str); * @return array
*/
return [$sign, $timestamp, $nonce]; protected function signature($api, $params)
} {
$timestamp = time();
protected function request($url, $post='', $headers=[]) { $nonce = uniqid();
//如果设置了远程IP,则直接用IP连接,省去解析 ksort($params);
if ($this->remoteIp) { $str = $api.http_build_query($params).$this->clientId.$this->clientSecret.$timestamp.$nonce;
$host = parse_url($url, PHP_URL_HOST); $sign = md5($str);
$url = substr_replace($url, $this->remoteIp, strpos($url, $host), strlen($host));
//$url = preg_replace('/^(https?:\/\/)[^\/]+/i', '${1}'.$this->remoteIp, $url, 1); return [$sign, $timestamp, $nonce];
$headers[] = "Host: $host"; }
}
protected function request($url, $post='', $headers=[]) {
$ci = curl_init($url); //如果设置了远程IP,则直接用IP连接,省去解析
if ($this->remoteIp) {
//添加客户端信息以辨服务端识别和调试 $host = parse_url($url, PHP_URL_HOST);
$userAgent = 'PHP/'.PHP_VERSION.' ('.PHP_OS.') Client/'.$this->clientId; $url = substr_replace($url, $this->remoteIp, strpos($url, $host), strlen($host));
//$url = preg_replace('/^(https?:\/\/)[^\/]+/i', '${1}'.$this->remoteIp, $url, 1);
if (isset($_SERVER['HTTP_HOST'])) { $headers[] = "Host: $host";
$userAgent .= ' ('.$_SERVER['HTTP_HOST'].')'; }
}
$ci = curl_init($url);
$curl = curl_version();
$userAgent .= " cURL/{$curl['version']} ({$curl['ssl_version']})"; //添加客户端信息以辨服务端识别和调试
$userAgent = 'PHP/'.PHP_VERSION.' ('.PHP_OS.') Client/'.$this->clientId;
//基础设置
curl_setopt_array($ci, [ if (isset($_SERVER['HTTP_HOST'])) {
CURLOPT_CONNECTTIMEOUT => 5, $userAgent .= ' ('.$_SERVER['HTTP_HOST'].')';
CURLOPT_TIMEOUT => 8, }
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false, $curl = curl_version();
CURLOPT_HEADER => false, $userAgent .= " cURL/{$curl['version']} ({$curl['ssl_version']})";
CURLOPT_USERAGENT => $userAgent
]); //基础设置
curl_setopt_array($ci, [
//POST 请求 CURLOPT_CONNECTTIMEOUT => 5,
if ($post) { CURLOPT_TIMEOUT => 8,
$body = is_array($post) ? http_build_query($post) : $post; CURLOPT_RETURNTRANSFER => true,
curl_setopt_array($ci, [ CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true, CURLOPT_HEADER => false,
CURLOPT_POSTFIELDS => $body CURLOPT_USERAGENT => $userAgent
]); ]);
}
//POST 请求
//优化 if ($post) {
$headers[] = 'Expect:'; $body = is_array($post) ? http_build_query($post) : $post;
curl_setopt_array($ci, [
curl_setopt_array($ci, [ CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $body
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0, ]);
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, }
//CURLOPT_DNS_USE_GLOBAL_CACHE => false
]); //优化
$headers[] = 'Expect:';
//调试
if ($this->debug) { curl_setopt_array($ci, [
curl_setopt($ci, CURLINFO_HEADER_OUT, true); CURLOPT_HTTPHEADER => $headers,
$responseHeaders = ''; CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
curl_setopt($ci, CURLOPT_HEADERFUNCTION, function ($ci, $header) use (&$responseHeaders) { CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
$responseHeaders .= $header; //CURLOPT_DNS_USE_GLOBAL_CACHE => false
return strlen($header); ]);
});
} //调试
if ($this->debug) {
$response = curl_exec($ci); curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE); $responseHeaders = '';
curl_setopt($ci, CURLOPT_HEADERFUNCTION, function ($ci, $header) use (&$responseHeaders) {
if ($response === false) { $responseHeaders .= $header;
$errno = curl_errno($ci); return strlen($header);
$errmsg = curl_error($ci); });
$response = "[$errno] $errmsg"; }
}
$response = curl_exec($ci);
//获取调试信息 $httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($this->debug) {
$httpInfo = curl_getinfo($ci); if ($response === false) {
} $errno = curl_errno($ci);
$errmsg = curl_error($ci);
curl_close($ci); $response = "[$errno] $errmsg";
}
if ($this->debug) {
echo "<pre>\r\n=====INFO=====\r\n"; //获取调试信息
echo "Request URL: $url\r\n", if ($this->debug) {
"Remote Address: {$httpInfo['primary_ip']}:{$httpInfo['primary_port']}\r\n", $httpInfo = curl_getinfo($ci);
"Local Address: {$httpInfo['local_ip']}:{$httpInfo['local_port']}\r\n", }
"Namelookup Time: {$httpInfo['namelookup_time']}\r\n",
"Connect Time: {$httpInfo['connect_time']}\r\n", curl_close($ci);
"Pre Transfer Time: {$httpInfo['pretransfer_time']}\r\n",
"Start Transfer Time: {$httpInfo['starttransfer_time']}\r\n", if ($this->debug) {
"File Time: {$httpInfo['filetime']}\r\n", $info = "=====INFO=====\r\n"
"Total Time: {$httpInfo['total_time']}\r\n"; ."Request URL: $url\r\n"
."Remote Address: {$httpInfo['primary_ip']}:{$httpInfo['primary_port']}\r\n"
if (isset($errno)) { ."Local Address: {$httpInfo['local_ip']}:{$httpInfo['local_port']}\r\n"
echo "\r\n=====ERROR=====\r\nErrorNo: $errno\r\nErrorMsg: $errmsg\r\n"; ."Namelookup Time: {$httpInfo['namelookup_time']}\r\n"
} ."Connect Time: {$httpInfo['connect_time']}\r\n"
."Pre Transfer Time: {$httpInfo['pretransfer_time']}\r\n"
echo "\r\n=====REQUEST=====\r\n",$httpInfo['request_header']; ."Start Transfer Time: {$httpInfo['starttransfer_time']}\r\n"
."File Time: {$httpInfo['filetime']}\r\n"
if (isset($body)) { ."Total Time: {$httpInfo['total_time']}\r\n";
echo $body."\r\n";
} if (isset($errno)) {
$info .= "\r\n=====ERROR=====\r\nErrorNo: $errno\r\nErrorMsg: $errmsg\r\n";
echo "\r\n=====RESPONSE=====\r\n",$responseHeaders,$response; }
echo "\r\n</pre>";
} $info .= "\r\n=====REQUEST=====\r\n{$httpInfo['request_header']}";
return [$httpCode, $response]; 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 @@ ...@@ -8,7 +8,14 @@
namespace internalApi\base; 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 ...@@ -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) { if ($return) {
return $data; return $data;
...@@ -104,6 +108,24 @@ class Server ...@@ -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) public function responseError($message)
{ {
header('HTTP/1.0 403 Forbidden'); 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