/**
 * 影领授权云 - C++ (OpenSSL + libcurl) 接入示例
 * 激活 / 验证 / 心跳 / 解绑
 *
 * 编译：g++ -o auth sample_cpp.cpp -lssl -lcrypto -lcurl
 *
 * 签名规则：sign = HMAC-SHA256("{action}|{product}|{code}|{machine}|{ts}", api_key)
 */

#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <curl/curl.h>
#include <unistd.h>

#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

namespace {

const char* kApiUrl = "https://pay.hbylsjcm.cn/api/verify";
const char* kApiKey = "your_api_key_here";
const char* kProduct = "your_product_code";

std::string ToHex(const unsigned char* data, size_t len) {
    std::ostringstream ss;
    for (size_t i = 0; i < len; i++) {
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(data[i]);
    }
    return ss.str();
}

std::string HmacSha256(const std::string& key, const std::string& message) {
    unsigned char result[EVP_MAX_MD_SIZE];
    unsigned int len = 0;
    HMAC(EVP_sha256(), key.c_str(), static_cast<int>(key.size()),
         reinterpret_cast<const unsigned char*>(message.c_str()), message.size(),
         result, &len);
    return ToHex(result, len);
}

std::string Sha256(const std::string& input) {
    unsigned char hash[EVP_MAX_MD_SIZE];
    unsigned int len = 0;
    EVP_MD_CTX* ctx = EVP_MD_CTX_new();
    EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr);
    EVP_DigestUpdate(ctx, input.c_str(), input.size());
    EVP_DigestFinal_ex(ctx, hash, &len);
    EVP_MD_CTX_free(ctx);
    return ToHex(hash, len);
}

// 机器码：示例用主机名哈希，生产环境建议叠加 MAC 地址 / 硬盘序列号
std::string GetMachineCode() {
    char hostname[256] = {0};
    if (gethostname(hostname, sizeof(hostname) - 1) != 0) {
        return Sha256("unknown-host");
    }
    return Sha256(hostname);
}

size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    static_cast<std::string*>(userp)->append(static_cast<char*>(contents), size * nmemb);
    return size * nmemb;
}

// 注意：业务字段不含引号与反斜杠，这里直接拼接；
// 若接入方允许外部输入参与拼接，必须先做 JSON 转义
std::string CallApi(const std::string& action, const std::string& code) {
    const std::string ts = std::to_string(std::time(nullptr));
    const std::string machine = GetMachineCode();
    const std::string sign = HmacSha256(
        kApiKey, action + "|" + kProduct + "|" + code + "|" + machine + "|" + ts);

    const std::string body = std::string("{")
        + "\"action\":\"" + action + "\","
        + "\"product\":\"" + kProduct + "\","
        + "\"code\":\"" + code + "\","
        + "\"machine\":\"" + machine + "\","
        + "\"ts\":\"" + ts + "\","
        + "\"sign\":\"" + sign + "\""
        + "}";

    CURL* curl = curl_easy_init();
    if (!curl) return "{}";

    std::string response;
    curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_URL, kApiUrl);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L);

    const CURLcode rc = curl_easy_perform(curl);
    if (rc != CURLE_OK) {
        response = std::string("{\"ok\":false,\"error\":\"network: ")
                 + curl_easy_strerror(rc) + "\"}";
    }

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    return response;
}

}  // namespace

int main() {
    const std::string licenseCode = "YL-XXXX-XXXX-XXXX";

    std::cout << "激活: " << CallApi("activate", licenseCode) << std::endl;
    std::cout << "验证: " << CallApi("verify", licenseCode) << std::endl;

    // 运行期建议每 5 分钟调用一次 CallApi("heartbeat", licenseCode)
    return 0;
}
