Depositphotos
- 8 minutes to read
The Design 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 telling them they must purchase those assets. When you implement the Depositphotos workflow, you can include the price of the added photos in the total order price, which your users confirm at 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, the Design Editor specifies two tags for this image: sourceType with the "DepositPhotosSource" value and the sourceData object containing the entire image details. The following example illustrates how you can use these tags to obtain a list of Depositphotos images.
// 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 model = await product.getProductModel();
const items = model.getAllItems({ ignoreMockups: true, flatGroupItems: true, excludeGroupItems: true });
items.forEach(function (item) {
// Finding the Depositphotos images with the "sourceType" tag.
var tagItem = item.content != null ? item.content : item;
if (tagItem.tags["sourceData"] != null && tagItem.tags["sourceType"] === "DepositPhotosSource") {
let dpData = tagItem.tags["sourceData"];
// 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 Design Editor assigns to design elements, and values are ids of images provided by Depositphotos. To find out how many images should be purchased, you can 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:
This section describes the 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.
Authorization on Depositphotos
The login method uses a username and a password and returns a unique session identifier.
$.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.
$.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 ofs
|m
|l
|xl
|ds
.dp_media_license
[string] - the necessary license, eitherstandard
orextended
.dp_purchase_currency
=[string] (optional) - the preferred purchase currency, one ofcredits
|subscription
|bonus
|ondemand
.dp_force_purchase_method
=[string] (optional) - used to force a purchase currency, one ofcredits
|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.
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 Design Editor and enables two buttons: one for obtaining the list of Depositphotos previews and one for replacing these previews with purchased images. The workflow includes the following steps:
loadEditor
loads a product from a state file.login
performs user authentication at Depositphotos and returnssessionid
.getPurchaseItems
gets the IDs of Depositphotos images in the product.purchase
retrieves download links to original images from Depositphotos.getPurchaseItems
creates a list of image items that need to be replaced by using these download links.replaceImageUrls
uses the StateFiles controller to replace these image items in the state file and displays the Image was purchased notification if the result is successful.
To make this sample work, replace stubs like "xxxxx"
with proper values. You can also download this sample.
<!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/Generated/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 user name and password provided by a Depositphotos manager.
const dp_login_user = "xxxxxxxxxxxxxxxxxxxxxxxxx";
const dp_login_password = "xxxxxxx12345";
// The identifier of a Depositphotos image you 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 model = await product.getProductModel();
const items = model.getAllItems({ ignoreMockups: true, flatGroupItems: true, excludeGroupItems: true });
items.forEach(function (item) {
// Finding the Depositphotos images with the "sourceType" tag.
var tagItem = item.content != null ? item.content : item;
if (tagItem.tags["sourceData"] != null && tagItem.tags["sourceType"] === "DepositPhotosSource") {
let dpData = tagItem.tags["sourceData"];
// 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 of 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 model = await product.getProductModel();
const items = model.getAllItems({ ignoreMockups: true, flatGroupItems: true, excludeGroupItems: true });
let depositPhotosItemsChanges = {};
// Generating the list of Depositphotos images.
await asyncForEach(items, async function (item) {
var tagItem = item.content != null ? item.content : item;
if (tagItem.tags["sourceData"] != null && tagItem.tags["sourceType"] === "DepositPhotosSource") {
let dpData = tagItem.tags["sourceData"];
// Purchasing the image with the specified identifier.
if (dpData.id == testImageId) {
let purchaseInfo = await purchase(sessionId, dpData.id);
depositPhotosItemsChanges[tagItem.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>