评论
[新手]PHP请求一个携带app_secre的API数据返回JSON给小程序

[新手]PHP请求一个携带app_secre的API数据返回JSON给小程序

​有时候,我会静静地想起你,想起那些与你共度的时光。虽然现在我们已不再相遇,但你在我心中留下的记忆,依然清晰如初

[新手]PHP请求一个携带app_secre的API数据返回JSON给小程序

在调用某接口的时候需要appid和app_secret,如果将它们直接写在小程序前端容易暴露

放在PHP后端请求,可以不用担心小程序个给扒下来直接看到秘钥;对方可以下载到网站的Html文件,但不一定可以下载到PHP文件

[新手]PHP请求一个携带app_secre的API数据返回JSON给小程序

因此小程序只需要携带参数访问到我们写的PHP文件,PHP接到参数后发起请求,将属于结果以Json的格式返回给小程序

 方式一

保存保证一个新手都可以看懂直接用的

小程序请求URL

https://xxxxx.com?fr=请求参数

PHP后端文件

<?php
// 获取请求中的'fr'参数
$fr = $_REQUEST['fr'];
​
// 对链接进行Base64编码
$encoded_link = base64_encode($fr);
​
​
// 将编码后的链接作为'fr'参数发送到指定的API
$app_id = 'xxxxxxxxxxxxx';
$app_secret = 'xxxxxxxxxxxxxxxx';
$api_url = "https://xxxxx.com?app_id={$app_id}&app_secret={$app_secret}&url={$encoded_link}";
​
// 发送GET请求
$response = file_get_contents($api_url);
​
// 输出API的响应
header('Content-Type: application/json');
echo $response;
?>

方式二

保证多掉几根头发

<?php  
header('Content-Type: application/json');  
​
// 获取请求中的'fr'参数
$encoded_link = $_REQUEST['fr'];
​
// 接口参数  
$app_id = 'your_app_id';  
$app_secret = 'your_app_secret';  
$url = "https://xxxxx.com?app_id={$app_id}&app_secret={$app_secret}&url={$encoded_link}";;  
​
// 构建请求头  
$headers = array(  
    'Authorization: Basic ' . base64_encode($app_id . ":" . $app_secret),  
);  
​
// 发送请求  
$options = array(  
    CURLOPT_HTTPHEADER => array('Content-type: application/json'),  
    CURLOPT_HEADER => false,  
    CURLOPT_RETURNTRANSFER => true,  
    CURLOPT_SSL_VERIFYPEER => false,  
    CURLOPT_TIMEOUT => 30,  
);  
$ch = curl_init();  
curl_setopt_array($ch, $options);  
curl_setopt($ch, CURLOPT_URL, $url);  
$response = curl_exec($ch);  
​
// 检查请求是否成功  
if (curl_errno($ch)) {  
    echo "请求失败:".curl_error($ch);  
    exit;  
}  
​
// 解码响应数据  
$json = json_decode($response, true);  
​
// 输出 JSON 格式数据  
echo json_encode($json);  
​
// 关闭 cURL 句柄  
curl_close($ch);  
?>