PHP code implements request authentication and access control of Baidu Wenxin Yiyan API interface
[Abstract] Baidu Wenxin Yiyan is an API that provides random sentences Service, this article will introduce the method of using PHP code to implement request authentication and access control for this API interface, and provide code examples.
[Text]
The random sentence API is often used in development. It can be used to generate some copywriting, famous quotes, and aphorisms. Baidu provides a free API service called Baidu Wenxin Yiyan, which can obtain random sentences. However, in order to ensure the security of the interface, we need to perform authentication and access control in the request.
Below, we will use PHP code as an example to demonstrate how to perform request authentication and access control through Baidu Wenxin Yiyan API.
First of all, before using the API, we need to register an application on Baidu Open Platform and obtain the corresponding API Key and Secret Key. After the registration is completed, we can get the following parameters:
<?php $apiKey = "YOUR_API_KEY"; // 替换为你的API Key $secretKey = "YOUR_SECRET_KEY"; // 替换为你的Secret Key
Next, we need to sign the request to ensure the legitimacy of the request. The specific steps for signing are as follows:
The following is a signed PHP code example:
<?php $apiUrl = "https://api.xxfgo.net/oneapi"; // API接口地址 // 获取当前时间戳 $timestamp = time(); // 计算签名 $sign = base64_encode(strtoupper(md5($apiKey . $timestamp . $secretKey))); // 构造请求参数 $params = array( "apiKey" => $apiKey, "timestamp" => $timestamp, "sign" => $sign ); // 发起请求 $url = $apiUrl . "?" . http_build_query($params); $response = file_get_contents($url); $data = json_decode($response, true); if ($data && $data["status"] == "success") { // 请求成功 echo $data["data"]["content"]; } else { // 请求失败 echo "请求失败:" . $data["message"]; } ?>
Through the above code example, we can implement request authentication and access control for the Baidu Wenxin Yiyan API interface. In actual applications, please replace "YOUR_API_KEY" and "YOUR_SECRET_KEY" with the API Key and Secret Key you obtained when registering the application on Baidu Open Platform.
[Conclusion]
This article introduces the method of using PHP code to implement request authentication and access control for Baidu Wenxin Yiyan API interface. By signing requests, we can guarantee the legitimacy of the request and ensure the security of the interface. I hope this article will be helpful to everyone when using Baidu Wenxin Yiyan API.
The above is the detailed content of PHP code implements request authentication and access control of Baidu Wenxinyiyan API interface. For more information, please follow other related articles on the PHP Chinese website!