Envato api verify-purchase response not working always!

Hi,

I’ve added this code to the verify-purchase functionality for all my WordPress themes. However, after receiving numerous customer inquiries, I’ve noticed that sometimes it doesn’t work. When I use var_dump on the response, it returns -1, but after a short while, the same code returns the correct result.

Here is my code:

<?php
if (!class_exists('EnvatoApi2')) 
{
    class EnvatoApi2
    {
        // Bearer, no need for OAUTH token, change this to your bearer string
        // https://build.envato.com/api/#token
        private static $bearer = "my_bearer_code";

        static function getPurchaseData($code)
        {

            //setting the header for the rest of the api
            $bearer = 'bearer ' . self::$bearer;
            $header = array();
            $header[] = 'Content-length: 0';
            $header[] = 'Content-type: application/json; charset=utf-8';
            $header[] = 'Authorization: ' . $bearer;

            $verify_url = 'https://api.envato.com/v1/market/private/user/verify-purchase:' . $code . '.json';

            $response = wp_remote_get(
                $verify_url . '?code=' . $code,
                [
                    'headers' => [
                        'Authorization' => 'Bearer ' . self::$bearer,
                        'Content-type' => 'application/json; charset=utf-8',
                        'Access-Control-Allow-Origin'=> "*",
                    ],
                ]
            );

            $body = wp_remote_retrieve_body($response);

            if ($body != "") {
                return json_decode($body);
            } else {
                return false;
            }

        }

        static function verifyPurchase($code)
        {
            $verify_obj = self::getPurchaseData($code);

            // Check for correct verify code
            if (
                (false === $verify_obj) ||
                !is_object($verify_obj) ||
                !isset($verify_obj->{"verify-purchase"}) ||
                !isset($verify_obj->{"verify-purchase"}->item_name)
            )
                return -1;

            // If empty or date present, then it's valid
            if (
                $verify_obj->{"verify-purchase"}->supported_until == "" ||
                $verify_obj->{"verify-purchase"}->supported_until != null
            )
                return $verify_obj->{"verify-purchase"};

            // Null or something non-string value, thus support period over
            return 0;

        }
    }
}

?>

Would you please help me find an effective solution?

It’s probably you’re on “testing/development” stage when the API gets used too many times, for security issue or other reason, it’s probably returning an error temporarily.

Addition to that, it’s harder to say if it’s your server or API has issues. Your server may not be sending the data as expected.