附錄-示例程式碼

示例程式碼說明

        以下多種語言程式碼僅供參考,不建議直接複製使用,需要結合實際業務情況進行處理,為了示例方便,以下程式碼均使用同一個擇吉日API,存取金鑰 (API Key)已做脫敏處理。
特別說明:
1.由於安全性考慮,前端語言(例如 JavaScript、Vue.js 框架)在執行跨域請求時會受到瀏覽器同源策略的限制,可能導致請求被阻止。建議採用後端語言(如 PHP、Node.js、Java、Python 等)代理請求,以確保資料安全和跨域訪問的穩定性。
2.若使用 Java 作為後端代理工具,推薦優先使用 OkHttp 替代原生 HttpClient。原生 HttpClient 的 User-Agent 特徵(如 Apache-HttpClient/4.5.14)易被識別為非瀏覽器請求,反爬蟲機制。

PHP SDK 程式碼示例

💡 SDK 設計說明:
官方 SDK 提供基礎的請求封裝、API Key 鑑權及異常處理能力。
為保證輕量與易用性,目前僅內置少數API(八字排盤、八字測算、八字運勢)。
👉 平臺全部API(近百種能力)均可通過通用方法呼叫:
$client->request('/api/v1/Xxx/xxx', $params, 'POST');
👉 無需等待 SDK 更新,即可使用所有API能力

        對於 PHP 開發者,我們強烈推薦使用官方提供的 SDK,極速接入,免去繁瑣的底層 cURL 封裝和驗簽過程。
        第一步: 通過 Composer 一鍵安裝 SDK: composer require yuanfenju/sdk
        第二步: 引入並呼叫API(以下以八字排盤和擇日擇時為例):

                        
<?php
require 'vendor/autoload.php';

use Yuanfenju\Sdk\Client;
use Yuanfenju\Sdk\Exception\ApiException;

// 1. 初始化 SDK (填入您的 API Key)
$client = new Client('wD******XhOUW******pvr');

try {
    // 方式一:呼叫專屬封裝API(例如:八字排盤)
    $baziResult = $client->getBaziPaipan([
        'name'   => '張三',
        'sex'    => 1,           // 1女 0男
        'type'   => 1,           // 0農曆 1公曆
        'year'   => 1990,
        'month'  => 1,
        'day'    => 1,
        'hours'  => 8,
        'minute' => 0
    ]);
    print_r($baziResult);

    echo "--------------------------\n";

    // 方式二:使用通用 request 方法呼叫任何API (例如文件中的擇日擇時)
    $zeshiResult = $client->request('/v1/Gongju/zeshi', [
        'future'   => '0',
        'incident' => '3'
    ], 'POST');
    print_r($zeshiResult);

} catch (ApiException $e) {
    // 捕獲 API 業務錯誤或網路錯誤
    echo "請求失敗: " . $e->getMessage();
}
                        
                    

PHP原生 cURL 示例(POST)

                        
//您的存取金鑰 (API Key)
$api_secret = "wD******XhOUW******pvr";
//請求擇日擇時API
$gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

//請求參數
$request_data = [
    'api_key' => $api_secret,
    'future' => '0',
    'incident' => '3',
];

//curl
function curlSend($process_gateway, $data_arr, $type = 1) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $process_gateway);
    curl_setopt($ch, CURLOPT_POST, $type);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data_arr));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_FAILONERROR, true); // Set this option to handle errors

    $response = curl_exec($ch);

    if ($response === false) {
        $error_message = curl_error($ch);
        // Handle or output the error message as needed
        echo "cURL error: " . $error_message;
    }

    curl_close($ch);
    return $response;
}

function process_host($curlPost,$gateway_url) {
    $response = curlSend($gateway_url,$curlPost,1);
    print_r($response);

}

process_host($request_data,$gateway_host_url);
                        
                    

PHP程式碼示例(GET)

                        
//您的存取金鑰 (API Key)
$api_secret = "wD******XhOUW******pvr";

//請求擇日擇時API
$gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

//目標頁面的URL
$url = $gateway_host_url. "?" . "api_key=" . $api_secret . "&future=0" . "&incident=3";

// 使用 cURL 的錯誤處理
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 禁用 SSL 證書驗證
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$content = curl_exec($ch);

if (curl_errno($ch)) {
    // 打印 cURL 錯誤資訊
    echo 'Curl error: ' . curl_error($ch);
} else {
    // 打印返回結果
    echo $content;
}

curl_close($ch);
                        
                    

Python程式碼示例

                        
import requests

# 您的存取金鑰 (API Key)
api_secret = "wD******XhOUW******pvr"
# 請求擇日擇時API
gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi"

# 請求參數
request_data = {
    'api_key': api_secret,
    'future': '0',
    'incident': '3',
}

def process_host(data, url):
    try:
        response = requests.post(url, data=data)
        response.raise_for_status()  # Raise an HTTPError for bad responses
        print(response.text)
    except requests.exceptions.RequestException as e:
        # Handle or output the error message as needed
        print(f"Request error: {e}")

process_host(request_data, gateway_host_url)
                        
                    

Java程式碼示例

                        
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Your API secret
        String apiSecret = "wD******XhOUW******pvr";

        // API endpoint URL
        String gatewayHostUrl = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

        // Request parameters
        Map< String, String> requestData = Map.of(
                "api_key", apiSecret,
                "future", "0",
                "incident", "3"
        );

        // Process the request
        processHost(requestData, gatewayHostUrl);
    }

    private static void processHost(Map< String, String> postData, String gatewayUrl) {
        try {
            URL url = new URL(gatewayUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Enable input/output streams
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // Set request method to POST
            connection.setRequestMethod("POST");

            // Build POST data
            StringBuilder postDataStringBuilder = new StringBuilder();
            for (Map.Entry< String, String> entry : postData.entrySet()) {
                if (postDataStringBuilder.length() != 0) {
                    postDataStringBuilder.append('&');
                }
                postDataStringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                postDataStringBuilder.append('=');
                postDataStringBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }

            // Write POST data to connection
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] postDataBytes = postDataStringBuilder.toString().getBytes("UTF-8");
                outputStream.write(postDataBytes);
                outputStream.flush();
            }

            // Get response
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder responseStringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    responseStringBuilder.append(line);
                }
                System.out.println(responseStringBuilder.toString());
            }

            // Close connection
            connection.disconnect();

        } catch (IOException e) {
            // Handle or output the error message as needed
            e.printStackTrace();
        }
    }
}
                        
                    

Node.js程式碼示例

                        
const axios = require('axios');
const qs = require('qs');

// 您的存取金鑰 (API Key)
const api_secret = "wD******XhOUW******pvr";
// 請求擇日擇時API
const gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

// 請求參數
const request_data = {
    api_key: api_secret,
    future: '0',
    incident: '3',
};

// 發送請求的函數
async function sendRequest(url, data) {
    try {
        const response = await axios.post(url, qs.stringify(data), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        });
        console.log(response.data);
    } catch (error) {
        if (error.response) {
            // 伺服器返回一個狀態碼範圍在2xx之外
            console.error('Response error:', error.response.status, error.response.data);
        } else if (error.request) {
            // 請求已發送但沒有收到響應
            console.error('No response received:', error.request);
        } else {
            // 設定請求時發生錯誤
            console.error('Error setting up request:', error.message);
        }
    }
}

// 執行請求
sendRequest(gateway_host_url, request_data);

                        
                    

Go程式碼示例

                        
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	// 您的存取金鑰 (API Key)
	apiSecret := "wD******XhOUW******pvr"

	// 請求擇日擇時API
	gatewayHostURL := "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi"

	// 請求參數
	apiKey := apiSecret
	future := "0"
	incident := "3"

	// 構造請求參數
	requestData := fmt.Sprintf("api_key=%s&future=%s&incident=%s", apiKey, future, incident)

	// 發送請求並打印響應
	response, err := sendRequest(gatewayHostURL, requestData)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(response)
}

func sendRequest(processGateway, data string) (string, error) {
	resp, err := http.Post(processGateway, "application/x-www-form-urlencoded", bytes.NewBufferString(data))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body), nil
}
                        
                    

C#程式碼示例

                        
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // 您的存取金鑰 (API Key)
        string api_secret = "wD******XhOUW******pvr";

        // 請求擇日擇時API
        string gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

        // 請求參數
        string api_key = api_secret;
        string future = "0";
        string incident = "3";

        // 構造請求參數
        string request_data = $"api_key={api_key}&future={future}&incident={incident}";

        // 發送請求並打印響應
        string response = await SendRequestAsync(gateway_host_url, request_data);
        Console.WriteLine(response);
    }

    static async Task< string> SendRequestAsync(string process_gateway, string data)
    {
        using (HttpClient client = new HttpClient())
        {
            // 發送 POST 請求
            HttpResponseMessage httpResponse = await client.PostAsync(process_gateway, new StringContent(data));

            // 讀取響應內容
            string response = await httpResponse.Content.ReadAsStringAsync();
            return response;
        }
    }
}