参数传递方式:
所有参数key、value键值对,转json然后base64(urlencode(json))转码,传递给接口。
PHP接口端使用 file_get_contents('php://input') 接收后解码
PHP接收端
$data=file_get_contents('php://input');
$data=json_decode(urldecode(base64_decode($data)),true);
PHP发送端
function curl_post($curlHttp, $postdata, $isJson = true)
{
$ch = curl_init(); //用curl发送数据给api
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $curlHttp);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($isJson)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache"));
}
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result;
}
前端基于jquery xhr请求
var data = {
"a" : 1,
"b" : 2,
"c" : [
{"x":1},
{"x":2}
]
};
data = window.btoa(encodeURIComponent(JSON.stringify(data)));
$.post("api_url",data,function(req){
},'json');
参数验证规则:
<?php
/**
* 判定是否是正常的访问
* @deprecated 根据参数来进行判定访问的合法性
*/
function isValidRequire($requestkey = '')
{
if (empty($requestkey)) {
$requestkey = config('DEFAULT_REQUEST_KEY');
}
$tempParams = array();
array_push($tempParams, $requestkey);
$params = get_input();
$publickey = $params['public_key']; // 内定的验证字段 publickey
unset($params['public_key']);
ksort($params);
foreach ($params as $key => $value) {
if (is_array($value)) {
$value = json_encode($value);
}
array_push($tempParams, $key . '=' . $value);
}
$str_token = hash('md5', implode('&', $tempParams));
if ($str_token != $publickey) {
$this->error('非法访问');
}
return true;
}
/**
* 生成访问的安全验证token
* $params 参数
*/
function buildValidToken(array $params, $requestkey = '')
{
$tempParams = array();
if (empty($requestkey)) {
$requestkey = config('DEFAULT_REQUEST_KEY');
}
array_push($tempParams, $requestkey);
if (!empty($params)) {
ksort($params);
foreach ($params as $key => $value) {
if (is_array($value)) {
$value = json_encode($value);
}
array_push($tempParams, $key . '=' . $value);
}
}
return hash('md5', implode('&', $tempParams));
}
function encode_data($arr)
{
return base64_encode(urlencode(json_encode($arr)));
}
function get_input()
{
$data = file_get_contents('php://input');
return json_decode(urldecode(base64_decode($data)), true);
}
网友评论