php--php调java接口验签

时间:2021-11-29 09:13:25
<?php
namespace Fmall_cloud\Model;
use Think\Model;
class DealJavaModel extends Model {
/**
* @title 处理向java传参
* @param $url java接口地址
* @param $data 业务参数
*/
public function dealJavaParam($url,$data){
//调java接口地址
$url=C('java_php').$url;
$token=C('token');
$apiKey=C('apiKey');
$timestamp=time();
$version=C('version');
$source=;
$data=json_encode($data);
//签名
$paramArr=array(
'token'=>$token,
'timestamp'=>$timestamp,
'source'=>$source,
'version'=>$version,
'data'=>$data
);
$sign=$this->createSign($paramArr,$apiKey);
$header = array('Content-Type: application/json; charset=utf-8',"token:$token","timestamp:$timestamp","source:$source","version:$version","sign:$sign","data:$data");
$result=$this->tocurl($url, $header,$data);
$res_info=json_decode($result,true);
return $res_info;
}
/**
* @title 签名函数
* @param $paramArr 系统参数
* @param $apiKey apikey
* @return string 返回签名
*/
private function createSign ($paramArr,$apiKey) {
ksort($paramArr);
$sign='';
foreach ($paramArr as $key => $val) {
if ($key != '' && $val != '') {
$sign .= $key."=".$val."&";
}
}
$sign=rtrim($sign,"&");
$sign .=$apiKey;
$sign=strtolower($sign);
$sign = md5($sign);
return $sign;
}
/**
* @title 远程调java接口函数
* @param $url java接口地址
* @param $header 要传的头信息
* @param $data 业务参数
*/
private function tocurl($url, $header, $data){
$ch = curl_init();
if(substr($url,,)=='https'){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if($error=curl_error($ch)){
die($error);
}
curl_close($ch);
return $response;
}
}

最近公司有个需求,需要调java接口,然后开始再往上查找相关资料,然后根据java端提供的接口调用说明文档写了这个公共方法,

该公共方法在处理接口调用验证时比较方便和实用,只需要继承这个类就可以了,其他业务参数正常传,系统参数是放到header里传过里啊,这样比较安全。