Meet us at Print 18. Chicago, IL. Sept. 30 - Oct. 2.

Depositphotos Assets

Customer's Canvas editor allows your users to add assets to their products from remote sources. For example, you can enable the DepositPhotos source in the Asset Manager. For details on configuring this widget, you can refer to the corresponding topic.

After your users have browsed and added Depositphotos assets to their products, the editor displays a notification that they have to purchase those assets. When you implement the Depositphotos workflow, you can include the price of the added photos to the total order price, which your users confirm at the checkout. On the canvas, these assets appear with watermarks. Prior to printing, you need to replace the preview images in state files through the Web API.

Obtaining the List of Added Assets

When a Depositphotos image is added to a product, Customer's Canvas tags this image with the dp_data object containing the entire image details. The following example illustrates how you can use this tag to obtain a list of Depositphotos images.

JavaScript
// Getting the list of all Depositphotos images.
async function listImages() {
    // The resulting list.
    let depositPhotosItems = {};

    // Getting the list of all design elements in a product.
    const product = await editor.getProduct();
    const items = await product.getAllItems();

    items.forEach(function (item) {
        // Finding the Depositphotos images by the "dp_data" tag.
        if (item.tags["dp_data"] != null) {
            let dpData = JSON.parse(item.tags["dp_data"]);
            // Setting the CC id as a key and DP id as a value.
            depositPhotosItems[item.id] = dpData.id;
        }
    });

    // Displaying the list and number of images to be purchased.
    console.log(depositPhotosItems);
    console.log("total: " + Object.keys(depositPhotosItems).length);
}

In this example, the resulting list contains key-value pairs, where keys are ids that Customer's Canvas assigns to design elements, and values are ids of images provided by DepositPhotos. To find out how many images should be purchased, you can just get the length of this list.

Replacing the Previews in a Product

To replace the previews with purchased images, you need to implement the following three steps in your E-commerce system:

  1. Authorize on Depositphotos
  2. Purchase images
  3. Replace images

This section describes Web API that you need in these steps. The next section of this topic contains a working sample illustrating how you can get an image list and replace depositphotos previews with purchased images.

Authorizing on Depositphotos

The login method uses a username and a password and returns a unique session identifier.

JavaScript
$.ajax({ 
    type: "GET",
    url: "https://api.depositphotos.com?dp_command=login&dp_apikey=" + dp_apikey +
         "&dp_login_user=" + dp_login_user + "&dp_login_password=" + dp_login_password
});

This request takes the following URL parameters:

  • dp_command[string] - the command name (login).
  • dp_apikey[string] - the API key provided by a Depositphotos manager.
  • dp_login_user[string] - the user name at Depositphotos.
  • dp_login_password[string] - the user password.

The success response contains an object with the sessionid property, which you need in the next step.

{
  timestamp: "2018-08-12 12:28:14",                   // The current date and time in YYYY-MM-DD HH:MI:SS format.
  version: "1.3",                                     // An API version.
  apiKey: "e3a363b882a793835e6cccdfb5f267c4d037b042", // An API key.
  sessionid: "7547043a09bafe4d35498e496e9952b2",      // A session identifier, valid for 3 hours.
  type: "success"                                     // The query result.
}

Purchasing the Images

The getMedia method debits a certain amount from your reseller's account and returns a link to the purchased item.

JavaScript
$.ajax({ 
    type: "GET",
    url: "https://api.depositphotos.com?dp_command=getMedia&dp_apikey=" + dp_apikey +
         "&dp_session_id=" + sessionId + "&dp_media_id=" + imageId +
         "&dp_media_option=xl&dp_media_license=standard" +
         "&dp_purchase_currency=ondemand&dp_force_purchase_method=ondemand"
});

This request takes the following mandatory URL parameters:

  • dp_command[string] - the command name (getMedia).
  • dp_apikey[string] - the API key provided by a Depositphotos manager.
  • dp_session_id[string] - the session identifier.
  • dp_media_id[integer] - the identifier of the image necessary for purchase.
  • dp_media_option[string] - the image size, one of s | m | l | xl.
  • dp_media_license[string] - the necessary license, either standard or extended.
  • dp_purchase_currency[string] (optional) - the preferred purchase currency, one of credits | subscription | bonus | ondemand.
  • dp_force_purchase_method[string] (optional) - used to force purchase currency, one of credits | subscription | bonus | ondemand.

The resulting object contains the downloadLink property, which you need in the next step.

{
  timestamp: "2018-08-05 12:12:58",       // The current date and time in YYYY-MM-DD HH:MI:SS format.
  version: "1.3",                         // An API version.
  downloadLink: "http://depositphoto...ff18fd5",  // A link to the purchased item download.
  licenseId: 1234567,                     // License ID of current purchase.
  type: "success"                         // The query result.
  method: "ondemand"                      // The Current purchase currency.
}

Replacing Images

For replacing images in a product, you can use the following method of the StateFiles controller.

JavaScript
const userId = "JohnWood";
const stateId = "1f190673-226d-4c31-87b4-0140805cc445";
const changeStateUrl = "https://example.com/api/users/" + userId + "/states/" + stateId;
let depositPhotosNewLinks = { [imageId]: downloadLink };
$.ajax({ 
    type: "PATCH",
    url: changeStateUrl,
    headers:  { "X-CustomersCanvasAPIKey": "UniqueSecurityKey" },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({
        type: "PatchImageItems",
        images: depositPhotosNewLinks
    })
});

The Sample

This code sample loads the editor and enables two buttons: for obtaining the list of Depositphotos previews and for replacing these previews with purchased images. The workflow includes the following steps:

  1. loadEditor loads a product from a state file.
  2. login performs user authentication at Depositphotos and returns sessionid.
  3. getPurchaseItems gets IDs of Depositphotos images in the product.
  4. purchase retrieves download links to original images from Depositphotos.
  5. getPurchaseItems creates a list of image items that need to be replaced by using these download links.
  6. replaceImageUrls uses the StateFiles controller to replace these image items in the state file and displays the Image was purchased notification in the case of successful results.

To make this sample working, replace stabs like "xxxxx" with proper values.

HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>The sample of Depositphotos API</title>
    <!-- The IFrame API script. IMPORTANT! Do not remove or change the ID. -->
    <script id="CcIframeApiScript" type="text/javascript" src="/Resources/SPEditor/Scripts/IFrame/IframeApi.js">
    </script>
</head>
<body>
    <!-- The iframe to display the editor in. -->
    <iframe id="editorFrame" style="width: 100%; height: 800px;"></iframe>
    <button onclick="listImages()">List the Depositphotos images</button>
    <button onclick="replaceImageUrls()">Replace images</button>
</body>
<script>
    // The user identifier in Customer's Canvas.
    const userId = "testUser";
    // The state file representing a product with previews of Depositphotos images.
    const stateId = "1e79aa1b-be29-4720-87d1-7d5646d7acf7";
    // URLs to the Web API.
    const changeStateUrl = "https://localhost:44300/api/users/" + userId + "/states/" + stateId;
    const depositPhotosApiUrl = "https://api.depositphotos.com";
    // Your API key provided by a Depositphotos manager. 
    const dp_apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    // Your API key provided by a Depositphotos manager. 
    const dp_login_user = "xxxxxxxxxxxxxxxxxxxxxxxxx";
    const dp_login_password = "xxxxxxx12345";
    // The identifier of a Depositphotos image we need to purchase. 
    const testImageId = "69915919";

    var iframe = document.getElementById("editorFrame");
    var editor = null;

    loadEditor().then(function (e) { editor = e; });  

    // Loading the Customer's Canvas editor.
    async function loadEditor() {
        let promise = new Promise(function (resolve, reject) {
            // Loading a product from the state file.
            CustomersCanvas.IframeApi.loadEditor(iframe, stateId, { userId: userId })
                    .then(function (e) {
                        resolve(e);
                    })
                    .catch(function (error) {
                        console.error("The editor failed to load with an exception: ", error);
                        reject(error);
                    });
        });

        return promise;
    }

    // Getting the list of all Depositphotos images.
    async function listImages() {
        // The resulting list.
        let depositPhotosItems = {};

        // Getting the list of all design elements in your product.
        const product = await editor.getProduct();
        const items = await product.getAllItems();

        items.forEach(function (item) {
            // Finding the Depositphotos images by the "dp_data" tag.
            if (item.tags["dp_data"] != null) {
                let dpData = JSON.parse(item.tags["dp_data"]);
                console.log(dpData);
                // Setting the CC id as a key and DP id as a value.
                depositPhotosItems[item.id] = dpData.id;
            }
        });

        // Displaying the list and number of images to be purchased.
        console.log(depositPhotosItems);
        console.log("total: " + Object.keys(depositPhotosItems).length);
    }

    // Replacing URLs of Depositphotos images.
    async function replaceImageUrls() {
        // Authorization to the Depositphotos server.
        let loginInfo = await login();
        // Obtaining the session identifier.
        let sessionId = loginInfo.sessionid;

        // Retrieving the list of purchased images.
        let depositPhotosItemsChanges = await getPurchaseItems(sessionId);

        // Replacing the URLs.
        fetch(changeStateUrl, {
            method: "PATCH",
            headers: {
                "X-CustomersCanvasAPIKey": "UniqueSecurityKey",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                type: "PatchImageItems",
                images: depositPhotosItemsChanges
            })
        })
        .then(async function(response) {
            if (response.ok) {
                // Notification about the successful replacement.
                alert("Image was purchased");
                editor = await loadEditor();
            }
            else
                console.log("Failed to reload images");
        });
    }

    // Authorization to the Depositphotos server.
    async function login() {
        let params = {
            dp_apikey: dp_apikey,
            dp_login_user: dp_login_user,
            dp_login_password: dp_login_password
        };

        let promise = new Promise(function (resolve, reject) {
            fetch(depositPhotosApiUrl + "?dp_command=login&dp_apikey=" + dp_apikey + "&dp_login_user=" +
                dp_login_user + "&dp_login_password=" + dp_login_password, { method: "GET" })
            .then(function (response) {
                if (response.ok)
                    resolve(response.json());
                else
                    console.log("Failed to login");
            });
        });

        return promise;
    }

    // Purchasing the images.
    async function purchase(sessionId, mediaId) {
        var purchaseParams = {
            dp_apikey: dp_apikey,
            dp_session_id: sessionId,
            dp_media_id: mediaId,
            dp_media_option: "xl:",
            dp_media_license: "standard",
            dp_purchase_currency: "ondemand"
        };

        let promise = new Promise(function (resolve, reject) {
            fetch(depositPhotosApiUrl + "?dp_command=getMedia&dp_apikey=" + dp_apikey + "&dp_session_id=" +
                sessionId + "&dp_media_id=" + mediaId + "&dp_media_option=xl&dp_media_license=standard" +
                "&dp_purchase_currency=ondemand&dp_force_purchase_method=ondemand", { method: "GET" })
            .then(function (response) {
                if (response.ok)
                    resolve(response.json());
                else
                    console.log("Failed to prchase item with id: " + mediaId);
            });
        });

        return promise;
    }

    // Getting the list of all elements and purchasing Depositphotos images.
    async function getPurchaseItems(sessionId) {
        // Getting the list of all design elements in your product.
        const product = await editor.getProduct();
        const items = await product.getAllItems();

        let depositPhotosItemsChanges = {};

        // Generating the list of Depositphotos images.
        await asyncForEach(items, async function (item) {
            if (item.tags["dp_data"] != null) {
                let dpData = JSON.parse(item.tags["dp_data"]);

                // Purchasing the image with the specified identifier.
                if (dpData.id == testImageId) {
                    let purchaseInfo = await purchase(sessionId, dpData.id);
                    depositPhotosItemsChanges[item.id] = purchaseInfo.downloadLink;
                }
            }
        });

        return depositPhotosItemsChanges;
    }

    // A helper function.
    async function asyncForEach(array, callback) {
        for (let index = 0; index < array.length; index++) {
            await callback(array[index], index, array)
        }
    }
</script>
</html>

See Also

Manual

Downloads