How to verify a purchase code using the Envato API

Hi Everyone,

I’m new on envato marketplace and i’m trying to start selling wordpress theme on themeforest and i need help from community or from expert authors.

I used “Look up sale by purchase code” technique from envato api docs but i’m stuck at point where page is not returning any response after submission of fake purchase code since i don’t have any real purchase code of customer.

I have created the app as describe on envato docs page and use the token key in the code but still no luck. Can anyone help me out please :frowning:

1 Like

Basic information

Invalid purchase codes

If the purchase code is invalid then the API will return a 404 Not Found response with the error in JSON like below:

{
    "error": 404,
    "description": "No sale belonging to the current user found with that code"
}

Valid purchase codes

If the purchase code is valid and belongs to one of your items, you’ll get a response similar to the following. In this case you should check the item’s name or ID to make sure the purchase code belongs to the expected item. Here’s an example response.

{
  "amount": "19.84",
  "sold_at": "2016-09-07T10:54:28+10:00",
  "license": "Regular License",
  "support_amount": "0.00",
  "supported_until": "2017-03-09T01:54:28+11:00",
  "item": {
    "id": 17022701,
    "name": "SEO Studio - Professional Tools for SEO",
    "author_username": "baileyherbert",
    "updated_at": "2017-11-02T15:57:41+11:00",
    "site": "codecanyon.net",
    "price_cents": 2000,
    "published_at": "2016-07-13T19:07:03+10:00"
  },
  "buyer": "buyers_username",
  "purchase_count": 1
}

Important: The buyer property contains the buyer’s username if it is available. If the buyer used guest checkout, this property will be null. Further, remember that buyers can change their username at any time, so make sure to account for that. Unfortunately there is no way to get a unique ID for the buyer yet without using OAuth.

Working example in PHP

This is tested and working on PHP 5.3+. You should run this code on your own server or computer – never share your personal token with others and never hard-code it into any of your items.

  • Be sure to replace the values of the first three lines.
  • $code is the purchase code you want to check.
  • $personalToken is your API key (go here to generate one) (also see this screenshot).
  • $userAgent is a brief description of what you are using the API for. The API team can see this and it’s solely for their reference. Please make sure it’s accurate.
<?php 

$code = "86781236-23d0-4b3c-7dfa-c1c147e0dece";
$personalToken = "your api key here";
$userAgent = "Purchase code verification on mywebsite.com";

// Surrounding whitespace can cause a 404 error, so trim it first
$code = trim($code);

// Make sure the code looks valid before sending it to Envato
if (!preg_match("/^([a-f0-9]{8})-(([a-f0-9]{4})-){3}([a-f0-9]{12})$/i", $code)) {
    throw new Exception("Invalid code");
}

// Build the request
$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 {$personalToken}",
        "User-Agent: {$userAgent}"
    )
));

// Send the request with warnings supressed
$response = @curl_exec($ch);

// Handle connection errors (such as an API outage)
// You should show users an appropriate message asking to try again later
if (curl_errno($ch) > 0) { 
    throw new Exception("Error connecting to API: " . curl_error($ch));
}

// If we reach this point in the code, we have a proper response!
// Let's get the response code to check if the purchase code was found
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// HTTP 404 indicates that the purchase code doesn't exist
if ($responseCode === 404) {
    throw new Exception("The purchase code was invalid");
}

// Anything other than HTTP 200 indicates a request or API error
// In this case, you should again ask the user to try again later
if ($responseCode !== 200) {
    throw new Exception("Failed to validate code due to an error: HTTP {$responseCode}");
}

// Parse the response into an object with warnings supressed
$body = @json_decode($response);

// Check for errors while decoding the response (PHP 5.3+)
if ($body === false && json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception("Error parsing response");
}

// Now we can check the details of the purchase code
// At this point, you are guaranteed to have a code that belongs to you
// You can apply logic such as checking the item's name or ID

$id = $body->item->id; // (int) 17022701
$name = $body->item->name; // (string) "SEO Studio - Professional Tools for SEO"

Response codes

  • 200 – Everything was okay and the purchase code is valid!
  • 404 – The purchase code was invalid, not real, or was not from one of your customers.
  • 403 – The personal token is incorrect or does not have the required permission(s).
  • 401 – The authorization header is missing or malformed. Verify that your code is correct.
  • 400 – A parameter or argument in the request was invalid.

Working example in Node.js

If you’re using Node.js, you can quickly install my envato npm package to work with the API. Below is an example of how to verify a purchase code. Note that this example is using the await operator. If you’d like, you can use promises instead.

const { Client } = require('envato');

const client = new Client('personal token here');
const sale = await client.private.getSale('purchase code here');

if (sale) {
    // See my example response above for the properties of "sale"
    console.log('Valid purchase code!');    
    console.log('Buyer:', sale.buyer);
    console.log('Item:', sale.item.id, sale.item.name);
}
else {
    // Returns `undefined` if the code wasn't found
    console.log('Invalid purchase code!');    
}
14 Likes

Hello Sir HTTp Error 404.I am already check View your items’ sales history but Same error.

please Help Me and how to check puchase Key in envato api …

Please help Me.

404 means the purchase code is invalid.

Yes How To check purchase_key…

Yes Sir…But how check Purchase_key valid

Please Full Code Finally check when the purchase key then check valid or valid answer.

The example I posted above works 100%. There’s no way to test it without a real purchase code, unfortunately. I’m afraid I can’t help you further than that.

My example above will throw an exception if the code is invalid or incorrect, and if you scroll all the way down, you’ll see this comment:

// The purchase code was valid, implement logic here.

That part of the code only runs when the purchase code is valid, so you can put your own code there.

Some valid purchase_key in my hand but not check this purchase_key.Please Help me.

When valid purchase key in input why this error:

The purchase code was invalidFailed to validate code due to an error: HTTP 404
Notice: Undefined property: stdClass::$item in D:\xampp\htdocs\php\key.php on line 49

Notice: Trying to get property ‘id’ of non-object in D:\xampp\htdocs\php\key.php on line 49
The purchase code provided is for a different item

Try this:

  1. Go to https://build.envato.com/
  2. Click “Sign in” at the top
  3. Click the “API” page at the top
  4. In the sidebar, click “Private User Details” > “Look up sale by code”
  5. Enter the code into the textbox and click “Try it out!”

Does this work or does it say “no content”? If it says “no content”, the purchase code isn’t real.

Keep in mind the purchase code must belong to one of your buyer’s. It can’t be your own or someone else’s.

3 Likes
	$theme_purchasecode = trim(get_option('envato_purchase_code'));
	
	$heme_url = 'https://api.envato.com/v3/market/buyer/purchase?code=1c8fbfa2-cbc5-44fb-9c28-2f5b627cc2c5';

	$response = wp_remote_get($theme_url); 
	
	$response_decode = json_decode($response['body']);
	
	print_r($response_decode);

I am also trying to verify theme purchase code plz can anyone help me?

You need to set the Authorization and User-Agent headers.

$response = wp_remote_get($url,
    array(
        'headers' => array(
            'Authorization' => "Bearer KEY_HERE",
            'User-Agent' => "Enter a description of your app here for the API team"
        )
    )
);
1 Like

thanks for your prompt reply.

Hi,

I added as your guide but the same result unauthorized.

$theme_purchasecode = get_option('envato_purchase_code');

$theme_url = 'https://api.envato.com/v3/market/buyer/purchase?code='.urlencode(trim($theme_purchasecode)).'';

$response = wp_remote_get($theme_url,
       
	    array(
		'headers' => array(
        'Authorization' => '',
        'user-agent' => 'WordPress/'. get_bloginfo( 'version' ) .'; '. network_site_url(),

		)
)
    
); 

$response_decode = json_decode($response['body']);

print_r($response_decode);

You need to keep the “Bearer” in the Authorization header. Only replace KEY_HERE. For instance:

Authorization: Bearer aep3hf4v3c3efb5qvfgyfjl5xmaw76d4

1 Like

Hi,

thanks lot for your kind guide to bring me up to this stage.

now i got result like this

[body] => {“error”:“Unauthorized operation - please use a valid token with the required permissions. Reason scope required purchase:verify”,“response_code”:403,“reason”:“scope-missing”

Actually, I didn’t notice this, but you’re also using the wrong URL for the API.

Use this one:

https://api.envato.com/v3/market/author/sale?code=

but the i got this api from the envanto api did they give wrong one?

The one you’re using is for a buyer to verify their own purchase code. It won’t work for authors.

The one I posted is meant for authors to verify purchase codes from their buyers. :slight_smile:

1 Like