Current Location: Home> Latest Articles> Complete PHP Example for Accessing and Authenticating with Baidu Wenxin Yiyan API

Complete PHP Example for Accessing and Authenticating with Baidu Wenxin Yiyan API

gitbox 2025-06-07

Introduction

Baidu Wenxin Yiyan is an API platform that provides access to famous quotes, classical Chinese poetry, and more. Developers can integrate this API to enrich their website or app content and enhance user engagement.

API Authentication and Access Control Methods

Authentication is crucial for verifying the identity of API users and securing access. Below are four common authentication methods:

Basic Authentication

Basic authentication uses a username and password, which are sent in the request header encoded in base64. It's simple to implement but has security limitations since base64 encoding is not encryption and can be intercepted.

OAuth Authentication

OAuth is a widely adopted standard that allows applications to access APIs with user authorization, without exposing passwords. It's suitable for multi-platform scenarios and promotes secure, scalable integrations.

Digital Signature Authentication

This method adds a signature to the request, which the server verifies using a shared secret key. It's effective in ensuring that parameters haven’t been tampered with during transmission.

Token Authentication

Upon user login, a token is generated and included in subsequent API requests. The server verifies the token for each request. This method requires token lifecycle management and proper authorization flows.

Using PHP to Access Wenxin Yiyan API with Authentication

This example uses basic authentication to demonstrate how to integrate the Baidu Wenxin Yiyan API with PHP and control access securely.

First, obtain an API key from the official Baidu Wenxin Yiyan platform. Then, define it as a constant in your code:


define('API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

Next, implement a function called getRequest to make authenticated API calls:


function getRequest($url){
    // Build the full API URL
    $url = 'https://v1.hitokoto.cn/?' . $url;
    
    // Initialize curl
    $ch = curl_init();

    // Set curl options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Api-Key:' . API_KEY));

    // Execute request and fetch response
    $result = curl_exec($ch);
    curl_close($ch);

    // Return the response
    return $result;
}

This function attaches the API key in the request header, constructs the complete URL, sends the request using curl, and returns the response received from the API.

Code Demonstration and Best Practices

With the provided implementation, you can easily integrate Baidu Wenxin Yiyan into your PHP project. Just replace the API key and adjust the URL parameters based on your data needs.