How to validate Envato Purchase Code in PHP



PHP Snippet 1:

<?php 
$code = "86781236-23d0-4b3c-7dfa-c1c147e0dece";

// If you took $code from user input it's a good idea to trim it:

$code = trim($code);

// Make sure the code is valid before sending it to Envato:

if (!preg_match("/^(\w{8})-((\w{4})-){3}(\w{12})$/", $code))
    throw new Exception("Invalid code");

// Query using CURL:

$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => "https://api.envato.com/v3/market/author/sale?code={$code}",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,

    CURLOPT_HTTPHEADER => array(
        "Authorization: Bearer KEY_HERE",
        "User-Agent: Enter a description of your app here for the API team"
    )
));

PHP Snippet 2:

function verify_purchase_code($code) {
    $code = urlencode($code);
    $url = "https://envato.eduardofiorini.com/index.php?item=35215272&code=" . $code . "&domain=" . $_SERVER['HTTP_HOST'];

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array('Content-type: application/json'));

    $ret = curl_exec($ch);
    curl_close($ch);

    if (!$ret) {
        $ret = file_get_contents($url);
    }

    $data = json_decode($ret??"{}",true);

    if($data["error"]){
        echo json_encode(array("success" => false, "message" => $data["msg"]));
        exit();
    }else{
        return true;
    }
}