版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37935476/article/details/78999598
一、从接口管理员那里物理获取AppID、AppSecret(生成方式可参考 生成自己的AppID、AppSecret)
二、ThinkPHP
cURL查询参数构造:
API采用签名方式验证,事先每个需要调用API接口的系统应申请appid和appsecret,调用接口时,请求参数:
appid(事先申请获取的appid),
random(随机数,调用时随机生成),
timestamp(时间戳,调用时生成当前时间的时间戳),
param(查询参数:province、year、major、type等),
sign(签名,算法:md5(random+timestamp+param+appsecret))
验证:根据appid,获取appsecret,再根据sign的生成规则(md5(random+timestamp+param+appsecret))生成sign,与调用提交的sign对比,一致则验证成功,否则验证失败 。
curl请求:
$appArr = M('Config')->field('appid,appsecret')->find();
$appid = $appArr['appid'];
$appsecret = $appArr['appsecret']; //后台可视化界面中设置输入AppID、AppSecret模块,录入进配置表后查询出
$random = mt_rand(1,1000000);
$timestamp = time();
$sign = $random.$timestamp.$otherParameter.$appsecret;//签名 ($otherParameter为必要的请求参数,根据自己的需要添加)
$ch = curl_init();
$url = "http://localhost/index.php/Api?m=Inquire&a=getData&appid=".$appid."&random=".$random."¤t=".$timestamp."&otherParameter=".$otherParameter."&sign=".$sign; //调用接口地址
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
$res = curl_exec($ch);
curl_close($ch);
$res_decode = json_decode($res,true);
switch ($res_decode['msg']){
case 0 : $error = '验证超时,请重新提交';break;
case 2 : $error = '暂无数据';break;
case 3 : $error = '验证失败,请重新提交';break;
}
$planList = $res_decode['info'];
$this->assign('error',$error);
$this->assign('total',$res_decode['total']);
$this->assign('count',$res_decode['count']);
$this->assign('dataList',$dataList);
接口:
public function getData()
{
$dao = M('Data'); //数据表
$random =intval($_GET['random']);
$timestamp = intval($_GET['current']);
$otherParameter = dHtml(htmlCv($_GET['otherParameter']));//必要请求参数
$appidGet = dHtml(htmlCv($_GET['appid']));
$mapAppid['appid'] = $appidGet;
$appsecretGet = M('Proof')->where($mapAppid)->getField('appsecret');//proof表:存储appid、appsecert
$signCheck = md5($random.$timestamp.$otherParameter.$appsecretGet);
$sign = md5(dHtml(htmlCv($_GET['sign'])));//获取的签名
if ($sign === $signCheck){
$now = time();
if (($now - $timestamp) > 600){ //十分钟
$data["msg"]="0"; //超时验证失败
echo json_encode($data);
exit;
}else{
$condition = array();
$otherParameter && $condition['otherParameter'] = array('eq',$otherParameter);
$count = $dao->where($condition)->count();
$page = intval($_GET['p']);//获取前台传过来的页码
$pageSize=30; //设置每页显示的条数
$start=($page-1)*30; //从第几条开始取记录
$totalPage = ceil($count / $pageSize); //总页数
$dataList = $dao->where($condition)->Limit($start.','.$pageSize)->select();
if ($dataList !== null){
$data["msg"]="1"; //状态码
$data['total'] = $totalPage; //总页数
$data['info'] = $dataList; //数据列表
$data['count'] = $count; //记录数
echo json_encode($data);
exit;
}else{
$data["msg"]="2"; //暂无数据
echo json_encode($data);
exit;
}
}
}else{
$data["msg"]="3"; //sign验证失败
echo json_encode($data);
exit;
}
}
不再关心宇宙从哪来到哪去
只想低下头好好珍惜身边人的普普通程序员