Advertisement
  1. Code
  2. JavaScript
  3. Web APIs

How to Use the Latest Updates to the Marketplace API

Scroll to top
Read Time: 18 min

The Envato Marketplaces are exploding, with more than 600k members and over 65k files!

A great addition to the marketplaces is the API, which is becoming more popular everyday, thanks to the latest updates! Our awesome marketplace devs are constantly listening to community feedback, and have added some sweet features to the edge release!

Be sure to check out some of the applications available around the web -- all powered by the Envato API.

Today, we'll take a look at the latest API features! Join me after the jump!


What is an API?

An Application Programming Interface (API) is a particular set of rules and specifications that a software program can follow to access and make use of the services and resources provided by another particular software program. It serves as an interface between different software programs and facilitates their interaction, similar to the way the user interface facilitates interaction between humans and computers.

Web API

Web APIs allow for the combination of multiple services into new applications, known as mashups.

When used in the context of web development, an API is typically a defined set of Hypertext Transfer Protocol (HTTP) request messages, along with a definition of the structure of response messages, which is usually in an Extensible Markup Language (XML) or JavaScript Object Notation (JSON) format.

While "Web API" is virtually a synonym for web service, the recent trend has been moving away from Simple Object Access Protocol (SOAP) based services, toward more direct Representational State Transfer (REST) style communications. Web APIs allow for the combination of multiple services into new applications known as mashups.


Are APIs Used Much?

Most developers will know the answer to this question, but for the others, the answer is a resounding YES.

API's are found everywhere; they're partcicularly popular in the social networking sector! Most large networks, including Twitter and Facebook, provide APIs to interact with their service.


New API Features

In this tutorial, we are only going to take a look at the new API features. If you want to learn more about the existing API features, be sure to check out Drew's tutorial on the topic.

Public

  • item - Details for a single item, specified by the given ID.
  • item-prices - Return available licences and prices for the given item ID.
  • user-items-by-site - Show the number of items an author has for sale on each site. Requires a username, e.g. collis.

Private

  • verify-purchase - Details of a purchase. Requires a purchase code, e.g. verify-purchase:550e8400-e29b-41d4-a716-446655440000.
  • download-purchase - URL to download purchase. Requires a purchase code, e.g. download-purchase:550e8400-e29b-41d4-a716-446655440000

Requirements

Tutorial imageTutorial imageTutorial image

In order to get started with the API, you will need an Envato Marketplace account and an API key.

You can retrieve your API key by visiting your account settings page.

Tutorial imageTutorial imageTutorial image

We'll be using a PHP function, called json_decode; this allows us to retrieve the API data and convert it to an array. This function is included in PHP 5 >= 5.2.0.

Got everything? Let's get started!


Step 1 - Building our Class

Let's begin by building a simple PHP class, which will allow us to retrieve data from the API.

Create a new project folder and create another directory called classes, to keep everything organized. Inside this folder, add a new PHP file called envato.api.class.php

First, we'll construct the basic skeleton of our class:

1
2
<?php
3
4
/**

5
 * Envato API

6
 *

7
 * An PHP class to interact with the Envato Marketplace API

8
 *

9
 * @author		Philo Hermans

10
 * @copyright	Copyright (c) 2011 NETTUTS+

11
 * @link		https://code.tutsplus.com

12
 */
13
 
14
/**

15
 * envatoAPI

16
 *

17
 * Create our new class called "envatoAPI"

18
 */ 
19
class envatoAPI{
20
21
}
22
 
23
?>

Step 2 - Global Variables

We need a couple of variables inside our class to make it flexible. To figure out which variables we need, we have to take a look at the API url formatting.

  • Public - https://marketplace.envato.com/api/edge/set.json
  • Private - http://marketplace.envato.com/api/edge/username/api-key/set.json

As you can see, we need a total of four variables:

  • API Url
  • Set
  • Username
  • API Key

Let's create these private variables like so:

1
2
class envatoAPI{
3
	
4
	private $api_url = 'http://marketplace.envato.com/api/edge/'; // Default URL

5
	private $api_set; // This will hold the chosen API set like "user-items-by-site"

6
	private $username; // The username of the author only needed to access the private sets

7
	private $api_key; // The api key of the author only needed to access the private sets

8
	
9
}

Step 3 - Setter & Getter Methods

I like to use setter and getter methods when building classes in PHP. So what exactly are these methods? I've made a small example below:

1
2
$API = new envatoAPI();
3
4
$API->api_url = 'https://code.tutsplus.com';
5
echo $API->api_url ;

The code above will not work and should return the following error:

1
Fatal error: Cannot access private property envatoAPI::$api_url

Because the variable is set to private, we cannot access or change it. If we need to change the API url without editing the class file, we could do something along the lines of:

1
2
$API = new envatoAPI();
3
4
$API->set_api_url('https://code.tutsplus.com');
5
echo $API->get_api_url();

Now switch back to the PHP class and add the function, set_api_url.

1
2
/**

3
* set_api_url()

4
*

5
* Set the API URL

6
*

7
* @access	public

8
* @param	string

9
* @return	 	void		

10
*/
11
public function set_api_url($url)
12
{
13
    $this->api_url = $url;
14
}

Since this function is within our class, we can access and change the private api_url variable. Now in this tutorial, we don't really need getters, but let's still create one to provide you with a better understanding of the concept.

1
2
/**

3
* get_api_url()

4
*

5
* Return the API URL

6
*

7
* @access	public

8
* @return	 	string		

9
*/
10
public function get_api_url()
11
{
12
    return $this->api_url;
13
}

As you may have inferred at this point, we don't need a get function for the API key for example. This makes our class more secure.


Step 4 - Completing the Rest of the Setters

We already finished a setter, so there are three remaining and all of them have the same structure.

Set Username

1
2
/**

3
* set_username()

4
*

5
* Set the Username

6
*

7
* @access	public

8
* @param	string	

9
* @return	 	void	

10
*/
11
public function set_username($username)
12
{
13
    $this->username = $username;
14
}

Set API Key

1
2
/**

3
* set_api_key()

4
*

5
* Set the API key

6
*

7
* @access	public

8
* @param	string

9
* @return	 	void		

10
*/
11
public function set_api_key($api_key)
12
{
13
    $this->api_key = $api_key;
14
}

Set API Set

1
2
/**

3
* set_api_set()

4
*

5
* Set the API set

6
*

7
* @access	public

8
* @param	string

9
* @return	 	void		

10
*/
11
public function set_api_set($api_set)
12
{
13
    $this->api_set = $api_set;
14
}

We are now able to set all variables like so:

1
2
<?php
3
4
include('classes/envato.api.class.php');
5
6
$API = new envatoAPI();
7
8
// $API->set_api_url();  - We don't need to change the API URL

9
// $API->set_api_key('ahdio270410ayap20hkdooxaadht5s'); - We only need to set the API key to fetch data from the private set

10
//$API->set_username('JohnDoe'); // - We only need to set the Envato Marketplace Username to fetch data from the private set

11
$API->set_api_set('popular:codecanyon'); // Set the API set to request

12
13
?>

Step 4 - Request Data

Let's build a function that will request the data from the Envato Marketplace API. We begin by creating a new public function called request.

1
2
/**

3
* request()

4
*

5
* Request data from the API

6
*

7
* @access	public

8
* @param	void

9
* @return	 	array		

10
*/
11
public function request()
12
{
13
}

We can use the same technique used in the previous tutorial. To request the data from the API, we can use cURL. Let's start of by building the API URL -- if the username and API key are set, we require a different url.

1
2
if(!empty($this->username) && !empty($this->api_key))
3
{
4
    // Build the private url

5
    $this->api_url .= $this->username . '/'.$this->api_key.'/'.$this->api_set . '.json'; // Sample: http://marketplace.envato.com/api/edge/JohnDoe/ahdio270410ayap20hkdooxaadht5s/popular:codecanyon.json

6
}
7
else
8
{
9
    // Build the public url

10
    $this->api_url .=  $this->api_set . '.json'; // Sample: http://marketplace.envato.com/api/edge/popular:codecanyon.json

11
}

We send a request to the API using cURL like so:

1
2
$ch = curl_init($this->api_url); // Initialize a cURL session & set the API URL

3
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect

4
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string instead of outputting it out directly.

5
$ch_data = curl_exec($ch); // Perform a cURL session

6
curl_close($ch);  //Close a cURL session

We now have a variable, called $ch_data which contains a JSON formatted string. Before we can do something with this, we need to decode it into a array.

1
2
// Check if the variable contains data

3
if(!empty($ch_data))
4
{
5
    return json_decode($ch_data, true); // Decode the requested data into an array

6
}
7
else
8
{
9
    return('We are unable to retrieve any information from the API.'); // Return error message

10
}

The function in its entirety looks like so:

1
2
public function request()
3
{
4
    
5
    if(!empty($this->username) && !empty($this->api_key))
6
    {
7
    	// Build the private url

8
    	$this->api_url .= $this->username . '/'.$this->api_key.'/'.$this->api_set . '.json';
9
    }
10
    else
11
    {
12
    	// Build the public url

13
    	$this->api_url .=  $this->api_set . '.json';
14
    }
15
    
16
    $ch = curl_init($this->api_url); // Initialize a cURL session & set the API URL

17
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect

18
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string instead of outputting it out directly.

19
    $ch_data = curl_exec($ch); // Perform a cURL session

20
    curl_close($ch);  //Close a cURL session

21
    
22
    // Check if the variable contains data

23
    if(!empty($ch_data))
24
    {
25
    	return json_decode($ch_data, true); // Decode the requested data into an array

26
    }
27
    else
28
    {
29
    	return('We are unable to retrieve any information from the API.'); // Return error message

30
    }
31
    
32
}

Step 5 - Testing the Function

Let's try our class and request some data from the API:

1
2
<?php
3
include('classes/envato.api.class.php');
4
5
$API = new envatoAPI();
6
7
//$API->set_api_url();

8
//$API->set_api_key('ahdio270410ayap20hkdooxaadht5s');

9
//$API->set_username('JohnDoe'); // Envato username

10
$API->set_api_set('popular:codecanyon'); // Set the API set to request

11
12
echo '<pre>';
13
print_r( $API->request() );
14
echo '</pre>';
15
?>
Tutorial imageTutorial imageTutorial image

Step 6 - Testing out the New Features of the Public API

Now that our class is working, it is time to build some examples with the new API features.

Item

To request information about a marketplace item, we must supply the API with an item ID. You can find the item ID within the URL of the marketplace item.

Tutorial imageTutorial imageTutorial image

Now that we have our ID, let's request the item information:

1
2
<?php
3
4
include('classes/envato.api.class.php');
5
6
$API = new envatoAPI();
7
$API->set_api_set('item:147510'); // Set the API set to request

8
9
echo '<pre>';
10
print_r( $API->request() );
11
echo '</pre>';
12
?>

The following data should be returned:

1
2
Array
3
(
4
    [item] => Array
5
        (
6
            [sales] => 16
7
            [rating] => 5
8
            [cost] => 25.00
9
            [user] => Philo01
10
            [uploaded_on] => Tue Dec 21 03:13:24 +1100 2010
11
            [url] => https://codecanyon.net/item/wordpress-car-dealer/147510
12
            [live_preview_url] => http://s3.envato.com/files/1410781/1_preview.__large_preview.jpg
13
            [thumbnail] => http://s3.envato.com/files/1410780/Car_dealer_avatar.jpg
14
            [tags] => easy to use, easy to setup, car inventory, car dealer, dealership, 2 build in sliders, native post type & taxonomies, over 35 settings, list all your cars, inventory system
15
            [id] => 147510
16
            [item] => WordPress Car Dealer
17
        )
18
19
)

Now let's build a simple page that will display the information above in a way that other users will understand it. First, we need to assign the API data to a variable:

1
2
$API = new envatoAPI();
3
$API->set_api_set('item:147510'); // Set the API set to request

4
5
$data = $API->request();

We can now display data from the API in the following format: $data['item']['key'].

1
2
<?php
3
4
include('classes/envato.api.class.php');
5
6
$API = new envatoAPI();
7
$API->set_api_set('item:147510'); // Set the API set to request

8
9
$data = $API->request();
10
11
?>
12
13
<h2><a href="<?php echo $data['item']['url']; ?>"><?php echo $data['item']['item']; ?></a></h2>
14
<img src="<?php echo $data['item']['live_preview_url']; ?>" alt="" />
15
<p>By <?php echo $data['item']['user']; ?>, available for only <?php echo $data['item']['cost']; ?>!</p>

The HTML after the PHP is parsed:

1
2
<h2><a href="https://codecanyon.net/item/wordpress-car-dealer/147510">WordPress Car Dealer</a></h2>
3
<img src="http://s3.envato.com/files/1410781/1_preview.__large_preview.jpg" alt="" />
4
<p>By Philo01, available for only 25.00!</p>
Tutorial imageTutorial imageTutorial image

item-prices

Instead of creating a new API request to find out more about the item price and license, we can simply add it to the current API set.

1
2
$API = new envatoAPI();
3
$API->set_api_set('item:147510+item-prices:147510'); // Set the API set to request

4
5
$data = $API->request();

The API's response is below:

1
2
[item-prices] => Array
3
    (
4
        [0] => Array
5
            (
6
                [licence] => Regular Licence
7
                [price] => 25.00
8
            )
9
10
        [1] => Array
11
            (
12
                [licence] => Extended License
13
                [price] => 175.00
14
            )
15
16
    )

Now we can use this returned information in our item page.

1
2
<h2><a href="<?php echo $data['item']['url']; ?>"><?php echo $data['item']['item']; ?></a></h2>
3
<img src="<?php echo $data['item']['live_preview_url']; ?>" alt="" />
4
<p>By <?php echo $data['item']['user']; ?></p>
5
6
<p><strong>Pricing:</strong></p>
7
<ul>
8
	<?php 
9
	// Loop trough all the licenses & prices

10
	foreach( $data['item-prices'] as $p)
11
	{
12
		echo '<li>' . $p['licence'] . ' - $' . $p['price'] . '</li>';
13
	}
14
	?>
15
</ul>
Tutorial imageTutorial imageTutorial image

user-items-by-site

To finish it off, we are going to append the number of items the user has. We can simply add it to the API set.

1
2
$API->set_api_set('item:147510+item-prices:147510+user-items-by-site:Philo01');

And the response:

1
2
[user-items-by-site] => Array
3
    (
4
        [0] => Array
5
            (
6
                [site] => ThemeForest
7
                [items] => 1
8
            )
9
10
        [1] => Array
11
            (
12
                [site] => CodeCanyon
13
                [items] => 5
14
            )
15
16
    )

Let's add this information to our page.

1
2
<h2><a href="<?php echo $data['item']['url']; ?>"><?php echo $data['item']['item']; ?></a></h2>
3
<img src="<?php echo $data['item']['live_preview_url']; ?>" alt="" />
4
<p>By <?php echo $data['item']['user']; ?></p>
5
6
<p><strong>Pricing:</strong></p>
7
<ul>
8
	<?php 
9
	// Loop trough all the licenses & prices

10
	foreach( $data['item-prices'] as $p)
11
	{
12
		echo '<li>' . $p['licence'] . ' - $' . $p['price'] . '</li>';
13
	}
14
	?>
15
</ul>
16
17
<p><strong><?php echo $data['item']['user']; ?> has more items at the Envato Marketplace</strong></p>
18
<ul>
19
	<?php 
20
	// Loop trough all the marketplaces

21
	foreach( $data['user-items-by-site'] as $p)
22
	{
23
		echo '<li>' . $p['items'] . ' at ' . $p['site'] . '</li>';
24
	}
25
	?>
26
</ul>
Tutorial imageTutorial imageTutorial image

Step 7 - Testing the New Features of the Private API

In order to use the private API features, you will need a marketplace account and a purchase code from one of your customers. We first need to define this information.

1
2
$API->set_api_key('ahdio270410ayap20hkdooxaadht5s');
3
$API->set_username('JohnDoe');

verify-purchase

This will automatically change the API URL from public to the private set. To make things a bit more dynamic, we can create a little form where the user can enter some information to verify his purchase.

Note: When building your own website, don't use inline styles like this!

1
2
<style>
3
form{
4
	background: #f8f8f8;
5
	width: 300px;
6
	border: 1px solid #e2e2e2;
7
}
8
form fieldset{
9
	border: 0;
10
}
11
form label{
12
	display: block;
13
	padding: 3px;
14
}
15
form input[type=text]{
16
	padding: 3px;
17
	border: 1px solid #d7d7d7;
18
}
19
</style>
20
21
<h2>Verify Purchase</h2>
22
23
<form action="" method="post">
24
	<fieldset>
25
		<p><label>Marketplace Username:</label>
26
		<input type="text" name="username" value="" /></p>
27
		
28
		<p><label>Item ID:</label>
29
		<input type="text" name="item_id" value="" /></p>
30
		
31
		<p><label>Purchase code:</label>
32
		<input type="text" name="purchase_code" value="" /></p>
33
		
34
		<p><input type="submit" name="submit" value="Verify" /></p>
35
	</fieldset>
36
</form>

This gives us a basic form like so:

Tutorial image

Now let's get to the PHP part.

First, we need to check whether the form has been submitted with the requisite fields filled. If you are using this on a live website, remember to add more validation to make things more secure.

1
2
if(isset($_POST['submit']))
3
{
4
	
5
	// Assign data to variables

6
	$username = $_POST['username'];
7
	$item_id = $_POST['item_id'];
8
	$purchase_code = $_POST['purchase_code'];
9
	
10
	// Check if all fields are filled in

11
	if(!empty($username) && !empty($item_id) && !empty($purchase_code))
12
	{
13
		// API Request

14
	}
15
}

And now the API request.

1
2
if(isset($_POST['submit']))
3
{
4
	
5
	// Assign data to variables

6
	$username = $_POST['username'];
7
	$item_id = $_POST['item_id'];
8
	$purchase_code = $_POST['purchase_code'];
9
	
10
	// Check if all fields are filled in

11
	if(!empty($username) && !empty($item_id) && !empty($purchase_code))
12
	{
13
		$API = new envatoAPI();
14
		$API->set_api_key('ahdio270410ayap20hkdooxaadht5s');
15
		$API->set_username('JohnDoe');
16
		$API->set_api_set('verify-purchase:' . $purchase_code);
17
		
18
		$data = $API->request();
19
	}
20
}

A valid API response will look like so:

1
2
Array
3
(
4
    [verify-purchase] => Array
5
        (
6
            [licence] => Regular Licence
7
            [item_id] => 147510
8
            [buyer] => EnvatoDemo
9
            [created_at] => Thu Dec 31 08:28:03 +1100 2009
10
            [item_name] => WordPress Car Dealer
11
        )
12
13
)

If the request is invalid, the API will return an empty array. If we get a response from the API, it means that the purchase code is correct. In the interest of making it more secure, we'll match it to the entered item id and username.

1
2
if(isset($_POST['submit']))
3
{
4
	
5
	// Assign data to variables

6
	$username = $_POST['username'];
7
	$item_id = $_POST['item_id'];
8
	$purchase_code = $_POST['purchase_code'];
9
	
10
	// Check if all fields are filled in

11
	if(!empty($username) && !empty($item_id) && !empty($purchase_code))
12
	{
13
		$API = new envatoAPI();
14
		$API->set_api_key('ahdio270410ayap20hkdooxaadht5s');
15
		$API->set_username('JohnDoe');
16
		$API->set_api_set('verify-purchase:' . $purchase_code);
17
		
18
		$data = $API->request();
19
		
20
		if(!empty($data))
21
		{
22
			// We got a valid API response let's match the item id and the username

23
			if($data['verify-purchase']['item_id'] == $item_id && $data['verify-purchase']['buyer'] == $username)
24
			{
25
				// Everything seems to be correct! Purchase verified!

26
				// Show some info like purchase date and licence

27
				echo '<p>You have purchased the item on ' . $data['verify-purchase']['created_at'] . ' with the ' . $data['verify-purchase']['licence'] . '!</p>';
28
			}
29
			
30
		}
31
		else{
32
			// Response from the API was empty, return error

33
			echo '<p>Sorry, we are unable to verify your purchase.</p>';
34
		}
35
		
36
	}
37
}
Tutorial imageTutorial imageTutorial image

download-purchase

The download-purchase set allows you to download your own purchases without visiting the marketplace.

Note: The download purchase only works when you are using your own API key and a purchase code of a product that you've purchased.

1
2
<form action="" method="post">
3
	<fieldset>
4
		<p><label>Marketplace Username:</label>
5
		<input type="text" name="username" value="" /></p>
6
		
7
		<p><label>Item ID:</label>
8
		<input type="text" name="item_id" value="" /></p>
9
		
10
		<p><label>Purchase code:</label>
11
		<input type="text" name="purchase_code" value="" /></p>
12
		
13
		<p><input type="checkbox" name="download" value="1" /> Download Item</p>
14
		
15
		<p><input type="submit" name="submit"  value="Verify" /></p>
16
	</fieldset>
17
</form>

Now that we have our checkbox, let's make some changes to the verification process.

We'll begin by creating a new variable.

1
2
// Assign data to variables

3
$username = $_POST['username'];
4
$item_id = $_POST['item_id'];
5
$purchase_code = $_POST['purchase_code'];
6
$download = (isset($_POST['download'])) ? $_POST['download'] : '';

We also need to make some changes to the remaining code:

1
2
if(isset($_POST['submit']))
3
{
4
	
5
	// Assign data to variables

6
	$username = $_POST['username'];
7
	$item_id = $_POST['item_id'];
8
	$purchase_code = $_POST['purchase_code'];
9
	$download = (isset($_POST['download'])) ? $_POST['download'] : '';
10
	
11
	// Check if all fields are filled in

12
	if(!empty($username) && !empty($item_id) && !empty($purchase_code))
13
	{
14
		$API = new envatoAPI();
15
		$API->set_api_key('ahdio270410ayap20hkdooxaadht5s');
16
		$API->set_username('JohnDoe');
17
		
18
		// If download is checked request the download-purchase set

19
		if(!empty($download))
20
		{
21
			$API->set_api_set('download-purchase:' . $purchase_code);
22
			$data = $API->request();
23
			
24
			// Set the header location to the download URL provided by the API

25
			header("Location: " . $data['download-purchase']['download_url']);
26
		}
27
		else
28
		{
29
			
30
			// The download checkbox was not checked so verify the purchase

31
			$API->set_api_set('verify-purchase:' . $purchase_code);
32
			$data = $API->request();
33
			
34
			if(!empty($data))
35
			{
36
				// We got a valid API response let's match the item id and the username

37
				if($data['verify-purchase']['item_id'] == $item_id && $data['verify-purchase']['buyer'] == $username)
38
				{
39
					
40
					// Everything seems to be correct! Purchase verified!

41
						// Show some info like purchase date and licence

42
						echo '<p>You have purchased the item on ' . $data['verify-purchase']['created_at'] . ' with the ' . $data['verify-purchase']['licence'] . '!</p>';
43
				}
44
				
45
			}
46
			else
47
			{
48
				// Response from the API was empty, return error

49
				echo '<p>Sorry, we are unable to verify your purchase.</p>';
50
			}
51
		}
52
		
53
	}
54
}

With those changes in place, the response should look like so:

1
2
Array
3
(
4
    [download-purchase] => Array
5
        (
6
            [download_url] => http://download/ourfile.zip?AWSAccessKeyId=12345&Expires=6789&Signature=HAoYF962%53faf
7
        )
8
9
)

Conclusion

I hope you've learned a bit about Envato's marketplace API. If so, then put this knowledge to use and build some sweet applications! Thank you so much for reading, and let us know if you have any questions or concerns.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.