Giter Club home page Giter Club logo

xsolla-sdk-php's Introduction

Xsolla SDK for PHP

Latest Stable Version Build Status Code Coverage Scrutinizer Code Quality Downloads Join the chat at https://gitter.im/xsolla/xsolla-sdk-php GitHub license

An official PHP SDK for interacting with Xsolla API

Payment UI screenshot

This SDK can be used for:

  • obtaining an authorization token
  • processing of basic webhooks (user_validation, payment, refund, etc.)

Features

  • Full customisation of Payment UI with the help of different methods of getting token.
  • Client for all API methods, making your integration easy and convenient. You can use it for setting up and updating virtual currency, items and subscription plans, for managing the users balance, for checking the finance information with the help of Report API and so on.
  • Convenient webhook server:
    • To start you need only one callback function.
    • All security checking already implemented: signature authentication and IP whitelisting.
    • Full customisation of notification processing logic, if standard server class doesn’t suit you.
  • 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.

Requirements

  • PHP ^7.3 or ^8.0
  • The following PHP extensions are required:
    • curl
    • json

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 Profile and Project Settings.

Installation

Installing via Composer

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

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

After installing, you need to require Composer's autoloader:

require '/path/to/vendor/autoload.php';

Installing via Phar

You can download the packaged phar and include it in your scripts to get started:

require '/path/to/xsolla.phar';

Installing via Zip

You can download the zip file, unzip it into your project to a location of your choosing, and include the autoloader:

require '/path/to/xsolla-autoloader.php';

Quick Examples

Receive webhooks

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

Solution with webhook server:

<?php

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

$callback = function (Message $message) {
    switch ($message->getNotificationType()) {
        case NotificationTypeDictionary::USER_VALIDATION:
            /** @var Xsolla\SDK\Webhook\Message\UserValidationMessage $message */
            // TODO if user not found, you should throw Xsolla\SDK\Exception\Webhook\InvalidUserException
            break;
        case NotificationTypeDictionary::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 NotificationTypeDictionary::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();

Solution with just helper classes in some php function:

public function handleRequest()
{
    $request = Request::createFromGlobals();
    $message = Message::fromArray($request->toArray());

    switch ($message->getNotificationType()) {
        case NotificationTypeDictionary::USER_VALIDATION:
            /**
             * https://developers.xsolla.com/webhooks/operation/user-validation/
             * @var Xsolla\SDK\Webhook\Message\UserValidationMessage $message 
             */
            if ($message->getUserId() !== 'our_user_id') {
                return YourResponseClass(json_encode(['error' => ['code' => 'INVALID_USER', 'message' => 'Invalid user']]), 400);
            }
            
            break;
        case NotificationTypeDictionary::PAYMENT:
            /** @var Xsolla\SDK\Webhook\Message\PaymentMessage $message */
            break;
        case NotificationTypeDictionary::REFUND:
            /** @var Xsolla\SDK\Webhook\Message\RefundMessage $message */
            break;
        default:
            throw new \Exception('Notification type not implemented');
    }
    
    return YourResponseClass('', 200);
}

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.

Troubleshooting

You can find solutions for the most frequently encountered errors in our documentation.

Contributing

Please take a look at the CONTRIBUTING.md to see how to get your changes merged in.

Additional resources

xsolla-sdk-php's People

Contributors

aanisimova avatar abetsxsolla avatar aklimenkoxsolla avatar amoseev avatar anastasiatw avatar aszhvakin avatar bralva avatar coocos100500 avatar craaazy19 avatar doncode avatar e-chernykh avatar ghostzero avatar ichekhaxsolla avatar ipanyukov avatar katerinapsperm avatar kokspflanze avatar l-malinin avatar nanaya avatar nasyrovyuri avatar renatko avatar s-kachulin avatar sanagrishin avatar sebalas avatar shionyr avatar shlykov avatar slatyshev avatar timur987 avatar valetanddama avatar vlepigeo avatar zakharovvi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xsolla-sdk-php's Issues

PHP-FPM: Authorization header not found in Xsolla webhook request

Если на сервере включено PHP-FPM, то подсказка из хелпа
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
не работает.
Потому что Authorization теперь выглядит как
[REDIRECT_HTTP_AUTHORIZATION] => Signature 89b146d1f356337ac3b5813a1e0fed76fb7fd34b
и, конечно же, в headers не попадает. В webhook проверку авторизации не проходит.

Я не гуру в php, но вот этот костыль работает (WebhookAuthentificator.php)

    public function authenticateSignature(WebhookRequest $webhookRequest)
    {
	$headers = [];
	if (isset($_SERVER["REDIRECT_HTTP_AUTHORIZATION"]))
		$headers = array('authorization' => $_SERVER["REDIRECT_HTTP_AUTHORIZATION"]);
	else
        $headers = $webhookRequest->getHeaders();
...

How to add virtual item which is Nonconsumable

I am using this SDK with laravel project. I am using api for creating virtual item. There is no document how to use with php and also request parameters are also different then mentioned in API reference of the official document. I somehow found the code from the source of the sdk. I did following code.

            $virtualItem = [
                'sku' => $request->sku,
                'name' => [
                    'en' => $request->name,
                ],
                'description' => [
                    'en' => $request->description,
                ],
                'prices' => [
                    'USD' => $request->price,
                ],
                'default_currency' => 'USD',
                'enabled' => $request->enabled,
                'free' => $request->free,
                'disposable' => false,
            ];

            $client = XsollaClient::factory(array(
                'merchant_id' => config('configuration.xsolla_merchant_id'),
                'api_key' => config('configuration.xsolla_api_key'),
            ));
            $response = $client->CreateVirtualItem([
                'project_id' => config('configuration.xsolla_project_id'),
                'request' => $virtualItem,
            ]);

As you can see for the php SDK there is difference with API reference. Now I want to create virtual item which is Nonconsumable. I tried item_type=>'Consumable' , item_type=>Nonconsumable', is_consumable=>false' , but nothing seems working.

Please help me how to do that also where can I find proper documentation.

Composer php max version

"php": ">=7.1.3 <=7.3"
this involves using the maximum version 7.3.0. It may be worth changing to
"php": "~7.1.3 | ~7.2 | ~7.3" or "php": ">=7.1.3 <7.4"

Update to php version 7.4

Seriosly no answers from developers in Xsolla?

There is pull request which will be work with higher version of php, it's really problem to merge it and test it?

Webhook Authorization Header issue

I don't know if it's unlucky me, but I'm using Apache and php7.3, everything is working fine except the array_key_exists('authorization', $headers) in the WebhookAuthentication which I had to change to array_key_exists('Authorization', $headers) might be just me tho

Error Message: Config must be an array or Collection

Code

        define('MERCHANT_ID',   '***');
        define('API_KEY',       '***');
        define('SECRET_KEY',    '***');
        define('PROJECT_ID',    '***');
        define('USER_ID',       '***');

        $tokenRequest = new TokenRequest(PROJECT_ID, MERCHANT_ID);

        $tokenRequest->setUserEmail('[email protected]')
            ->setExternalPaymentId(12345)
            ->setSandboxMode(true)
            ->setUserName('USER_NAME')
            ->setCustomParameters(array('key1' => 'value1', 'key2' => 'value2'));

        $xsollaClient = new XsollaClient(MERCHANT_ID, API_KEY);
        $token = $xsollaClient->createPaymentUITokenFromRequest($tokenRequest);

Error

An uncaught Exception was encountered

Type: Guzzle\Common\Exception\InvalidArgumentException

Message: Config must be an array or Collection

Filename: /vendor/guzzle/guzzle/src/Guzzle/Http/Client.php

Line Number: 93

Backtrace:

File: /vendor/guzzle/guzzle/src/Guzzle/Http/Client.php
Line: 75
Function: setConfig 
  • guzzle/guzzle v3.9.3
  • xsolla/xsolla-sdk-php v2.0.0

Laravel 7.16.1 - Package requiring is failing

Hi,

I wanted to give Xsolla a try in my Laravel 7.16.1 project but unfortunately the command composer require xsolla/xsolla-sdk-php fails with the following error log: https://pastebin.com/raw/R9hh2BLD

A couple weeks ago I tried the same, but then a PHP error occurred. This error has been fixed by some PR I assume but now I am facing this issue.

Hope someone is able to help me out. I assume that there should be a new update coming that will cover this issue.

Thanks :)

Edit: I assume the composer package did not get updated yet, according to this reply.

Upgrade guzzle client to ~7.0

Currently the sdk requires guzzle in version ~6.0 and actually tries to install version 6.5.5.

New features and also security update seem to only happen for version ^7.0. Also added php 8.x support and so on are features, that at least we use in our code base, so right now we are not able to install both guzzle ^7.0 and the sdk simultaneously.

I checked the sdk and the guzzle changelog. There don't seem to be any BC breaks relevant for the sdk itself.

Of course there is the new implementation of get, head, put and so on methods, which might be relevant for XsollaClient::__call(), however I don't think it should be that big a problem, as the README promotes using the custom methods the XsollaClient::class adds.

Still the upgrade should probably be a major version, as users of the sdk might configure the guzzle client a bit differently than default. Especially concerning would be the dropped/changed request and pool options.

문서를 제대로 만드세요.

Add to your documentation how to respond to webhook errors.
I've been working on various payment modules, but I've never seen a case where the documentation was messed up like Xsolla.

Client error response [status code] 422

I get this error when creating a client:

Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: 'POST https://api.xsolla.com/merchant/v2/merchants/xxxxxx/token' resulted in a '422 Unprocessable Entity' response: { "http_status_code": 422, "message": "JSON is not valid against json schema, please check documentation https:\ (truncated...) in E:\xamppp\htdocs\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 E:\xamppp\htdocs\vendor\guzzlehttp\guzzle\src\Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 E:\xamppp\htdocs\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 E:\xamppp\htdocs\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array) #3 E:\xamppp\htdocs\vendor\guzzlehttp\promises\src\TaskQueue.php(47): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}() #4 in E:\xamppp\htdocs\vendor\xsolla\xsolla-sdk-php\src\Exception\API\XsollaAPIException.php on line 46

How to fix?

Help me!

Hello! I need help with integration xsolla-sdk-php, as I can not understand how can I install the mobile payments to your online project.

Guzzle 3 has been deprecated

guzzle3 has been deprecated since the start of 2015, are there any plans to release a new version of the SDK with updated dependencies?

In it's current state we cannot use the sdk in a production environment.

"Authorization" header not found in Xsolla webhook request.

Happens due to class WebhookAutheticator in function authenticateSignature:

//This checks for case sensitive key: "authorization"

 if (!array_key_exists('authorization', $headers)) {
            throw new InvalidSignatureException('"Authorization" header not found in Xsolla webhook request. Please check troubleshooting section in README.md https://github.com/xsolla/xsolla-sdk-php#troubleshooting');
        }

In my case I was getting the key "Authorization" (with capital 'A') in the header and it was throwing InvalidSignatureException.

Quick Solution for individual is to dump your headers and check for this key and make changes according.
A more permanent solution will be to read case insensitive header key to avoid this issue.

PHP 7.3 support

There's currently a version requirement of <7.3. I tried the package with 7.3 and it seems to work fine in my (basic) test.

Incompatible with your PHP version (7.4.0) 😥

[InvalidArgumentException]
  Package xsolla/xsolla-sdk-php at version 4.1.0 has a PHP requirement incompatible with your PHP version (7.4.0)

😒😥 please add ^PHP7.4 support

hm...
[InvalidArgumentException] Package xsolla/xsolla-sdk-php at version 4.1.0 has a PHP requirement incompatible with your PHP version (7.3.12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.