Full PHP Integration Guide

A complete guide for integration, suitable for PHP based sites and custom e-Shops

Deprecated

Note: This page is now deprecated. See the new Integration Guide for the most up-to-date information.

General overview

This guide relies on the Youstice PHP library. The library is compatible with PHP 5.3+ and allows any developer to integrate Youstice platform easily, comfortably and blazingly fast. It wraps the Restful API and speeds up the integration by pre-built UI elements and data-exchange processes. There are only a handful of API calls you have to make in order to start using the Youstice platform on your site. The library provides a fluent interface with easy to understand and easily readable API calls.

If your site is actually based on Prestashop, Magento, VirtueMart, WooCommerce, OpenCart, ShopWare or Shopify, you're better of by getting one of the specific plug-ins for those e-Shop platforms.

This guide will walk you through the integration steps with the following goals:

  • Show the 'Youstice Widget' on your website
  • Ability to file claims (after having the purchase verified and validated)
  • See claim details by redirecting the customer to Youstice
  • Ability to file claims for unregistered customers (e.g. anonymous claims), by verifying the email and the order number

See the quick PHP integration guide if you only want to show the Youstice widget, and file claims, without a more interactive experience for your visitors.

Download PHP library here. Last updated: Feb. 27, 2015

Since all our maintained plug-ins in the Plug-in Section utilize the aforementioned PHP library, their source are a very good place to look for examples, how to utilize the library to achieve the best possible effect and integration with your e-Shop platform or website.

Logos of various color scheme and size are available here

Our recommendation: Place this logo on a visible location on your website as a link to the Youstice Badge (clicking on the logo would display the widget).

Prerequisites

  • Target environment for the integration: SANDBOX, or PRODUCTION
  • Successful registration into Youstice (either SANDBOX, or PRODUCTION) as a retailer with at least 1 shop
  • The API Key for your shop
  • Familiarity with the API Sequence diagram
  • Familiarity with the PHP programming language

This guide assumes integration into the SANDBOX environment, which is a good place to get started.

Integrating the PHP library into your site

1. Initialization

  • Include the youstice.css file (located in public folder in downloaded zip) into your pages. This CSS includes all images inline, so there is no need for a specific image directory.
  • Create an array holding the DB credentials (either with host:port or using a socket):
  • $db = array( 'driver' => 'mysql', 'host' => 'server', 'user' => 'usr', 'pass' => 'pwd', 'name' => 'dbname', 'prefix' => 'tables_prefix' );

    Connecting via socket is also possible (note that host must not be specified)

    $db = array( 'driver' => 'mysql', 'socket' => '/tmp/mysql51.sock', 'user' => 'usr', 'pass' => 'pwd', 'name' => 'dbname', 'prefix' => 'tables_prefix' );

  • Construct the Youstice API object and provide all required parameters, most notably the API key. API will throw exceptions on any errors, e.g. if a provided API key is invalid.
  • $yapi = Youstice_Api::create() ->setDbCredentials($db) ->setLanguage('sk') ->setShopSoftwareType('custom-myshop', 'version-string') ->setApiKey($api_key, $is_sandbox) ->setUserId($logged_in_user_id);

    Now you can run this command to start using this libary (note that it must be called before any output was sent to a browser due to session initialization):

    $yapi->run();

    Notice: if this is the first time you use the API, call $yapi->install();. This creates any necessary database tables. The call can be made on every request, installation takes place only once.

    You're now ready to use the API in your code.


    2. Display the Youstice Widget

    The following code snippet will display the Youstice Widget (logo + generic info):

    echo $yapi->getLogoWidgetHtml('/report-claims-for-logged-out-users');

    No extra developer interactions are required. Method takes exactly one parameter, URL to page that is handling reporting claims. The link with this url is shown in logo widget. You can pass different url addresses: to 'report claims page' for not logged in users (see section 5), or to page which maintains order history (see section 3). The Youstice Widget should look like this:

    Youstice - logo widget

    3. Integrate Youstice to the Order History page

    3.1 One button to show them all (Optional)

    To limit misuse, it's a good practice to hide the "file the claim" buttons, by default. To reveal the on explicit request, we place a button to our Order page that makes the claim filing buttons visible. Note: Buttons are only hidden as long as the client has not filed any claim yet. To place such a button on your page, do the following:

    echo $yapi->getShowButtonsWidgetHtml();

    Returned html code looks like:

    <a href="#" class="yrsShowButtons yrsButton" data-has-reports="1">Would you like to file a complaint?</a>

    Note: Using this button is not necessary, it does not have influence on any other buttons or the Youstice Widget.

    Tip: In case when a button's data-has-reports attribute is set to 'true', you can implement a handler, which load other buttons immediately.


    3.2 Populate the shop orders for the API

    Calling code should call the following method each and every time the order history page is displayed in your shop:

    $yapi->orderHistoryViewed();

    Calling this method is critical for resetting any shown user claim updates in the logo widget. Count of updated cases should be dismissed after showing the order history page.

    Next, the programmer creates an array of \Youstice\ShopOrder classes. Each instance represents one shop order. All orders shown on the order history page should be constructed this way. Below is an example PrestaShop implementation of constructing one single \Youstice\ShopOrder class:

    public function createShopOrder($order_id) { $order = $this->getOrder($order_id); if (empty($order)) exit('Operation not allowed'); $currency = Currency::getCurrencyInstance((int)$order['id_currency']); $shop_order = Youstice_ShopOrder::create(); $shop_order->setName('#'.$order_id); ->setDescription('') ->setCurrency($currency->iso_code) ->setPrice((float)$order['total_paid']) ->setId($order_id) ->setDeliveryDate($order['delivery_date']) ->setOrderDate($order['date_add']); if ($order['is_paid']) $shop_order->setPaymentState(Youstice_ShopOrder::PAID); if($order['is_delivered']) $shopOrder->setDeliveryState(Youstice_ShopOrder::DELIVERED); $shop_order->setHref($this->createOrderReportHref($order_id)); ...

    Next, we add every single product for this order:

    foreach ($products as $product) { $shop_product = $this->createShopProduct($product, $order_id); $shop_product->setCurrency($currency->iso_code) ->setDeliveryDate($order->delivery_date) ->setOrderDate($order->invoice_date); $shop_order->addProduct($shop_product); } return $shop_order; }

    3.3 Populate orders items

    Reporting a single item in an order (either a product or service) is also self explanatory. Creates the \Youstice\ShopProduct class and fill in the required information.

    public function createShopProduct(array $product, $order_id) { $product_obj = new Product($product['product_id'], false, Context::getContext()->language->id); $shop_product = Youstice_ShopProduct::create(); ->setName($product['product_name']); ->setId($product['id_order_detail']); ->setPrice((float)$product['unit_price_tax_incl']); ->setDescription($product_obj->description); ->setOtherInfo(Tools::jsonEncode($this->buildDataArray(null, $product_obj))); //add image if exists if (count($product['image']) > 0) { $image_path = _PS_PROD_IMG_DIR_.$product['image']->getExistingImgPath().'.jpg'; $shop_product->setImagePath($image_path); } $shop_product->setOrderId($order_id); $shop_product->setHref($this->createProductReportHref($order_id, $product['id_order_detail'])); return $shop_product; }

    These classes hold all the information about any orders your customers have. API requires no further product / order information.


    3.4 Displaying the buttons

    After the ShopOrder classes are constructed, they can be passed to simple rendering functions in the appropriate place of your HTML template.

    $yapi->getOrderDetailButtonHtml('/my-custom-code?section=getOrderDetail&order_id=' . $order_id, $shop_order);

    This code renders the order detail button, that can be shown in three states. All is handled by the API, and no further developer interaction is required.

    The provided URL should point to a code branch that renders the full order detail (usually shown in pop-up - use jQuery plug-in if desired). Example PrestaShop implementation follows:

    public function getOrderDetail($in) { $order = $this->getOrder(Tools::getValue('order_id')); if (!$order || $order['id_customer'] != $this->context->customer->id) exit('Operation not allowed'); $shop_order = $this->createShopOrder($order); echo $this->yapi->getOrderDetailHtml($shop_order); exit; }

    3.5 Submit the claim

    Order link in the code above points to code that submits the claim. Example implementation:

    public function orderReportPost($in) { $shop_order = $this->createShopOrder((int)$in['order_id']); $redirect_link = $this->yapi->createOrderReport($shop_order); header('Location: '.$redirect_link); exit; }

    Nothing more. The code redirects the user to Youstice complaint filling form, and handles everything else. Report won't be created twice, so you don't have to worry about it.


    4. Submit claims unrelated to an order

    Everything else is displayed / handled in the same manner. To display the button to file an claim unrelated to an order (e.g. the 'web-report button') use the following line of code. The Url provided must be a location of your code to handle the button-click action:

    echo $yapi->getWebReportButtonHtml('modules/yousticeresolutionsystem/index.php?section=webReportPost');

    The button-click handling code would then look like this:

    public function webReportPost() { $redirect_url = $this->yapi->createWebReport(); header('Location: '.$redirect_url); exit; }

    5. Completing claims by customer

    After submitting the claim by API to a specified order, product or web, user should be redirected to url returned by these API calls. Customer can specify details of his claim on the Youstice.com site. No other activity for integration is required.

    6. Anonymous claims

    A significant percentage of users is purchasing from e-Shops anonymously (they wish not to register, just provide their address for notifications and delivery). Some eShops do not create accounts, other may do create hidden accounts. A good practice is to allow such users also to file claims, should they wish to do so.

    You may want to create a simple form, that accepts an email and orderNumber and validates those. If the provided information points to a valid purchase, you can go on to construct the order class and submit the claim similarly to section 3.5 above.

    Links to the form to submit anonymous claims can be put to your web's information section, as well as to the emails notifying the customer about shipping and delivery.

    More information about filing anonymous claims guide can be found in the anonymous claims page. You can also check out how it's done inside the code of the prestashop plug-in

    Error handling

    Library throws the following exceptions. Catching them in your implementation is highly recommended.

    Invalid API key

    This exception is thrown only if set API Key is invalid

    try { $redirectUrl = $this->api->get()->createWebReport(); } catch (Youstice_InvalidApiKeyException $e) { exit('Connection to remote server failed, please try again later'); }

    Could not connect to remote server

    This exception is thrown when connection problems occurs, or if remote server is unavailable.

    try { $redirectUrl = $this->api->get()->createWebReport(); } catch (Youstice_FailedRemoteConnectionException $e) { exit('Connection to remote server failed, please try again later'); }

    Youstice: [module] is not installed, please install it.

    This exception is thrown when specific extensions needed to run API properly are missing. Depending on server's configuration the exception are thrown when cURL, PDO, or PECL finfo extensions are disabled. Get the exception's message by calling $e->getMessage();

    try { $api->run(); } catch (Youstice_ApiException $e) { if ($e->getCode() == Youstice_Api::CURL_NOT_INSTALLED) ... elseif ($e->getCode() == Youstice_Api::PDO_NOT_INSTALLED) ... elseif ($e->getCode() == Youstice_Api::FINFO_NOT_INSTALLED) ... }