Xsolla SDK

PHP SDK

Xsolla PHP SDK is an open source library for interacting with Xsolla API. You can find the link to this project on GitHub here.

Features

  1. Full customization of the payment UI with the help of different methods of getting a token.
  2. Client for all API methods, making your integration easy and convenient. Use it to set up and update virtual currency, items and subscription plans, to manage the user’s balance, to check your finance information with the help of Report API, and more.
  3. Convenient webhook server:
    • You only need one callback function to start.
    • All security checking is already implemented: signature authentication and IP whitelisting.
    • Full customization of notification processing logic if the standard server class doesn’t suit you.
  4. SDK is built on Guzzle v3, and utilizes many of its features, including persistent connections, parallel requests, events and plugins (via Symfony2 EventDispatcher), service descriptions, over-the-wire logging, caching, flexible batching, and request retrying with truncated exponential back off.

Getting Started

Please register your Publisher Account and create the project. In order to use the PHP SDK Library you’ll need:

  • MERCHANT_ID
  • API_KEY
  • PROJECT_ID
  • PROJECT_KEY

You can obtain these parameters using the information in your company settings and project settings.

System Requirements

  • PHP 5.3.9+
  • The following PHP extensions are required:
    • curl
    • json

Installing

The recommended way to install Xsolla PHP SDK is through Composer.

$ cd /path/to/your/project
$ composer require xsolla/xsolla-sdk-php

Please visit our GitHub project site for other ways of installing.

Usage

Get Token

To integrate the payment UI into your game, you should obtain an access token. An access token is a string that identifies game, user, and purchase parameters.

There are a number of ways for getting a token. The easiest one is to use the createCommonPaymentUIToken method. You only need to pass the project ID in the Xsolla system and the user ID in your game:

use Xsolla\SDK\API\XsollaClient;

$client = XsollaClient::factory(array(
    'merchant_id' => MERCHANT_ID,
    'api_key' => API_KEY
));
$paymentUIToken = $client->createCommonPaymentUIToken(PROJECT_ID, USER_ID,
$sandboxMode = true);

You can pass more parameters in JSON for token:

<?php

use Xsolla\SDK\API\XsollaClient;
use Xsolla\SDK\API\PaymentUI\TokenRequest;


$tokenRequest = new TokenRequest($projectId, $userId);
$tokenRequest->setUserEmail('email@example.com')
    ->setExternalPaymentId('12345')
    ->setSandboxMode(true)
    ->setUserName('USER_NAME')
    ->setCustomParameters(array('key1' => 'value1', 'key2' => 'value2'));

$xsollaClient = XsollaClient::factory(array(
    'merchant_id' => MERCHANT_ID,
    'api_key' => API_KEY
));
$token = $xsollaClient->createPaymentUITokenFromRequest($tokenRequest);

If you want to use some custom parameters for opening the payment UI (e.g., “settings.ui.theme”), you can use this example:

<?php

use Xsolla\SDK\API\XsollaClient;

$tokenContent = array (
    'user' =>
        array (
            'id' =>
                array (
                    'value' => '1234567',
                    'hidden' => true,
                )
        ),
    'settings' =>
        array (
            'project_id' => 14004,
            'ui' =>
                array(
                    'theme' => 'dark'
                )
        )
);


$xsollaClient = XsollaClient::factory(array(
    'merchant_id' => MERCHANT_ID,
    'api_key' => API_KEY
));
$response = $xsollaClient->CreatePaymentUIToken(array('request' => $tokenContent));
$token = $response['token'];

Integrate payment UI (Pay Station)

You can use the following code to add the payment UI on your page:

<html>
<head lang="en">
    <meta charset="UTF-8">
</head>
<body>
    <button data-xpaystation-widget-open>Buy Credits</button>

    <?php \Xsolla\SDK\API\PaymentUI\PaymentUIScriptRenderer::send($paymentUIToken, $isSandbox = true); ?>
</body>
</html>

Please follow this link for more information and examples about the payment UI integration.

Receive Webhooks

There is a built-in server class to help you handle the webhooks.

<?php

use Xsolla\SDK\Webhook\WebhookServer;
use Xsolla\SDK\Webhook\Message\Message;
use Xsolla\SDK\Exception\Webhook\XsollaWebhookException;

$callback = function (Message $message) {
    switch ($message->getNotificationType()) {
        case Message::USER_VALIDATION:
            /** @var Xsolla\SDK\Webhook\Message\UserValidationMessage $message */
            // TODO if user not found, you should throw Xsolla\SDK\Exception\Webhook\InvalidUserException
            break;
        case Message::PAYMENT:
            /** @var Xsolla\SDK\Webhook\Message\PaymentMessage $message */
            // TODO if the payment delivery fails for some reason, you should throw Xsolla\SDK\Exception\Webhook\XsollaWebhookException
            break;
        case Message::REFUND:
            /** @var Xsolla\SDK\Webhook\Message\RefundMessage $message */
            // TODO if you cannot handle the refund, you should throw Xsolla\SDK\Exception\Webhook\XsollaWebhookException
            break;
        default:
            throw new XsollaWebhookException('Notification type not implemented');
    }
};

$webhookServer = WebhookServer::create($callback, PROJECT_KEY);
$webhookServer->start();

If the standard server class does not suit you, then you can create your own:

<?php

use Xsolla\SDK\Webhook\WebhookRequest;
use Xsolla\SDK\Webhook\Message\Message;
use Xsolla\SDK\Webhook\WebhookResponse;
use Xsolla\SDK\Exception\Webhook\XsollaWebhookException;

$httpHeaders = array();//TODO fetch HTTP request headers from $_SERVER or apache_request_headers()
$httpRequestBody = file_get_contents('php://input');
$clientIPv4 = $_SERVER['REMOTE_ADDR'];
$request = new WebhookRequest($httpHeaders, $httpRequestBody, $clientIPv4);
//or $request = WebhookRequest::fromGlobals();

$this->webhookAuthenticator->authenticate($request, $authenticateClientIp = true);// throws Xsolla\SDK\Exception\Webhook\XsollaWebhookException

$requestArray = $request->toArray();

$message = Message::fromArray($requestArray);
switch ($message->getNotificationType()) {
    case Message::USER_VALIDATION:
        /** @var Xsolla\SDK\Webhook\Message\UserValidationMessage $message */
        $userArray = $message->getUser();
        $userId = $message->getUserId();
        $messageArray = $message->toArray();
        // TODO if user not found, you should throw Xsolla\SDK\Exception\Webhook\InvalidUserException
        break;
    case Message::PAYMENT:
        /** @var Xsolla\SDK\Webhook\Message\PaymentMessage $message */
        $userArray = $message->getUser();
        $paymentArray = $message->getTransaction();
        $paymentId = $message->getPaymentId();
        $externalPaymentId = $message->getExternalPaymentId();
        $paymentDetailsArray = $message->getPaymentDetails();
        $customParametersArray = $message->getCustomParameters();
        $isDryRun = $message->isDryRun();
        $messageArray = $message->toArray();
        // TODO if the payment delivery fails for some reason, you should throw Xsolla\SDK\Exception\Webhook\XsollaWebhookException
        break;
    case Message::REFUND:
        /** @var Xsolla\SDK\Webhook\Message\RefundMessage $message */
        $userArray = $message->getUser();
        $paymentArray = $message->getTransaction();
        $paymentId = $message->getPaymentId();
        $externalPaymentId = $message->getExternalPaymentId();
        $paymentDetailsArray = $message->getPaymentDetails();
        $customParametersArray = $message->getCustomParameters();
        $isDryRun = $message->isDryRun();
        $refundArray = $message->getRefundDetails();
        $messageArray = $message->toArray();
        // TODO if you cannot handle the refund, you should throw Xsolla\SDK\Exception\Webhook\XsollaWebhookException
        break;
    default:
        throw new XsollaWebhookException('Notification type not implemented');
}

Once you’ve finished the handling of notifications on your server, please set up the URL that will receive all webhook notifications on the Settings page for your project.

After passing the tests, you’re ready to go live. If you’ve used the sandbox parameters, please don’t forget to remove them from the code.

Troubleshooting

Here you can find some tips for handling and preventing the most frequently encountered errors returned by Xsolla PHP SDK.

[curl] 77: error setting certificate verify locations: CAfile

You may see this kind of error when you send the request to our server using Xsolla PHP SDK, for example when getting a token. By default we enable SSL certificate verification and use the default CA bundle provided by your operating system. However not all system’s have a known CA bundle on disk. For example, Windows and OS X do not have a single common location for CA bundles.

There are several ways this problem can be resolved.

Development. You can disable the certificate verification, when you’re in development mode. You will need additional testing of this issue on Production environment.

use Xsolla\SDK\API\XsollaClient;

$client = XsollaClient::factory(array(
    'merchant_id' => MERCHANT_ID,
    'api_key' => API_KEY
));
$client->setDefaultOption('ssl.certificate_authority', false);

Production. The more secure and reliable way is to provide the correct CA bundle. You can specify the CA path to the file using the following code:

use Xsolla\SDK\API\XsollaClient;

$client = XsollaClient::factory(array(
    'merchant_id' => MERCHANT_ID,
    'api_key' => API_KEY
));
$сlient->setDefaultOption('ssl.certificate_authority', '/path/to/file');

In Windows this file can be located in the following paths:

  • C:\windows\system32\curl-ca-bundle.crt
  • C:\windows\curl-ca-bundle.crt

Please check the existence of these files, and set the appropriate CA path.

If you don’t have this certificate located in the mentioned places, you can try to use the certificate provided by Mozilla, which can be downloaded here (provided by the maintainer of cURL).

In some versions of PHP for Windows there is a problem with programmatic configuration of certificate paths. In order to solve this problem, download the file cacert.pem and specify the path to this file directly in php.ini: curl.cainfo=c:/cacert.pem.

"INVALID_SIGNATURE" error code with message "Authorization header not found in Xsolla webhook request"

Php-cgi under Apache does not pass HTTP Basic user/pass to PHP by default. In order to get this working you need to add the following line to .htaccess or httpd.conf Apache file:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

"INVALID_CLIENT_IP" error code in your webhook server

By default Xsolla PHP SDK is checking the IPs from which the webhook was sent for security reasons. The error code “INVALID_CLIENT_IP” can be returned if you test your webhook server from a localhost in development environment, or your application server works behind some sort of proxy — like a load balancer — on production.

If you are behind a proxy, you should manually whitelist your proxy.

If you are in development environment, you can disable the IP checking using the following code:

use Xsolla\SDK\Webhook\WebhookServer;

$webhookServer = WebhookServer::create($callback, PROJECT_KEY);
$webhookServer->start($webhookRequest = null, $authenticateClientIp = false);

More secure and reliable way is to set your reverse proxy IP address to webhook server:

use Xsolla\SDK\Webhook\WebhookServer;
use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();
$request->setTrustedProxies(array('YOUR_PROXY_SERVER_IP_OR_CIDR'));

$webhookServer = WebhookServer::create($callback, PROJECT_KEY);
$webhookServer->start();

More information is available in Symfony Documentation.

Android SDK

Xsolla created Android Client SDK for accepting payments from your application. You can check its work by downloading this apk.

Before starting, please choose one of the modules listed here, implement the Webhook handling, and create an access token.

System Requirements

  • Minimum required Android OS version: 4.0
  • Internet Connection is essential for the Xsolla Android SDK

Download

Download via Jcentral:

<dependency><groupId>com.xsolla.android</groupId>
  <artifactId>xsollasdk</artifactId>
  <version>2.3.0</version></dependency>>

or Gradle:

compile 'com.xsolla.android:xsollasdk:2.3.0'

Installing

You can add our Xsolla Android SDK in Android Studio. Please follow these steps:

  1. Import module - File > Import Module > xsollasdk
  2. Add dependency - File > Project Structure > Your App Module > Dependency > + > Module Dependency > xsollasdk
  3. Add to your build gradlew in android section the following:
    packagingOptions {
       exclude 'META-INF/LICENSE'
       exclude 'META-INF/NOTICE'
    }

You can find the link to this project on GitHub here.

Make a Payment

For the SDK to work properly, please make sure that you have an access token. More information about getting a token is available here.

Let’s take as an example the simple application that has a payment button — when clicked our store UI is opened.

public class MainActivity extends Activity {

 public void openShop(String token, boolean isTestPayment) {
    XsollaSDK.createPaymentForm(this, token, isTestPayment);
 }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   switch (requestCode){
     case XsollaActivity.REQUEST_CODE:
       if(data != null) {
         long objectId = data.getExtras().getLong(XsollaActivity.EXTRA_OBJECT_ID);
         if (resultCode == RESULT_OK) {
           XStatus statusData = (XStatus) XsollaObject.getRegisteredObject(objectId);
           Toast.makeText(this, statusData.toString(), Toast.LENGTH_LONG).show();
         } else {
           XError error = (XError) XsollaObject.getRegisteredObject(objectId);
           Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
         }
       }
   }
 }
}

Once the payment has been processed, your application can get a result in OnActivityResult. Also we will send a webhook on your server, even if the application has been closed.

Unity SDK

Xsolla created Unity SDK for accepting payments in desktop, web or mobile applications.

Download the latest release of Xsolla Unity SDK from GitHub.

System Requirements

Xsolla Unity SDK works with Unity 5.0 and above.

Integration

Main Features:

  • Saved payment methods
  • Purchase of virtual currency
  • Purchase of virtual items
  • Purchase of subscriptions
  • Promotions
  • Redeem coupon
  • User’s payment history

If you would like to accept payments through Xsolla’s payment UI, follow these steps:

  • Set up webhook handling
  • Get an access token to conduct payments with maximum security
  • Add Xsolla SDK script to any object or use prefab from Resources > Prefabs folder
  • Call XsollaSDK(instance) to generate ready to use payment form
  • Call the method CreatePaymentForm(token, actionOk(XsollaStatusData), actionError(XsollaError), actionMore(string))
Parameter Description
token Your purchase token was received using Get Token method.
actionOk Is called when the payment process is completed. Insert your payment accepting function here.
actionError Is called when the payment process is canceled or failed for any reason. Insert your event handling function here.

You can also use XsollaSDK.InitPaystation(string token) to launch the payment UI in the native browser.

If you want to have your own payment UI, you should write your own class which extends XsollaPaystation class. For example, you can use XsollaPaystationController.

SDK Response Objects:

public class XsollaResult {
    public string invoice{ get; set;}
    public Status status{ get; set;}
    public Dictionary<string, object> purchases;
}

Try it!

Give it a try and take a look at our demo. We also have test scenes in XsollaUnitySDK > Resources > _Scenes folder:

  • XsollaFarmFreshScene - emulates item shop
  • XsollaTokenTestScene - you can test your token here