h5利用api接口實現數據加密傳輸,具體方法如下:
function CurlPost($url, $param = null, $timeout = 10)
{
//初始化curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url); // 設置請求的路徑
curl_setopt($curl, CURLOPT_POST, 1); //設置POST提交
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //顯示輸出結果
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
//提交數據
if (is_array($param)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
} else {
curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
}
//執行請求
$data = $data_str = curl_exec($curl);
//處理錯誤
if ($error = curl_error($curl)) {
$log_data = array(
'url' => $url,
'param' => $param,
'error' => '' . $error . '',
);
}
# 關閉CURL
curl_close($curl);
//json數據轉換為數組
$data = json_decode($data, true);
//api返回數據解密
$api_des = config('api.mcrypt');
if ($api_des['is_open']) {
$data1 = Des::decode($data, $api_des['key'], $api_des['iv']);
$des_str = json_decode($data1, true);
}
if (!is_array($des_str)) {
$des_str = $data_str;
}
return $des_str;
}
如需要確保數據不出現泄露,還可以在數據傳輸中添加數據簽名
//添加數據簽名
function makeClientSign($param){
//數組排序
ksort($param)
//轉換成json串
$json_str = json_encode($param);
//md5生成sign
$md5_result = md5($json_str);
return $md5_result;
}