How we made friends with PayPal

    Dear foreign guest with a surname too famous to be called, a PayPal citizen just “got off the ship” to the domestic “pier”, but has already managed to become his own at a ball where electronic payment systems of the Russian segment actively dance dances of all styles and directions. We did not stand aside and hastened to make a useful acquaintance with such a respected comrade, adding, finally, his good name to our list of friends . Which side to approach, what to talk about and how to attract his attention we read in a short story under the cut.

    Friendship begins with a smile

    The first timid step on the road to great friendship is the presentation, that is, registration, where you must provide information about the company’s commercial activities in your personal data, which we conscientiously performed.

    However, instead of the easy and laid-back relationships that we managed to mentally rejoice at, we received an unfriendly message about the limitation of the account and a request to provide a number of additional documents to confirm our account. We did not have time to collect all the necessary things, but, fortunately, in mid-September PayPal greatly simplified the procedure for connecting legal entities. All that was required was to fill out a special form on the PayPal side. But now it was too early to rejoice - for the first few days the form simply did not work. We honestly filled in all required and optional fields, but each time we received a data transfer error and, no matter how hard we tried, this was repeated again and again. Without losing determination and having a lot of perseverance in reserve, a week later we repeated the “experiment” and, finally, received the long-awaited confirmation,

    A true friend is known in the API

    Understanding all the intricacies of the PayPal protocol is not easy. Scattered pieces of documentation scattered across different parts of the site, the heavy legacy of SOAP, the general mess of the protocol stack (NVP, SOAP, REST) ​​and the lack of examples did the trick. A typical example of confusion, an action implemented by one protocol, cannot be performed by another and vice versa.
    But the journey of a thousand miles begins with the first step, casting aside all doubts away, we will use the most popular REST API at the moment, and take their own PHP SDK as a wrapper for it . True, some things will still have to be thought out by ourselves when examining the code.

    The general idea can be described in the following steps:

    1. We register PayPal Application to receive pairs of client_id and secret_key values ​​for live and sandbox mode:

    2. We make OAuth authorization:
      $apiContext = new ApiContext(new OAuthTokenCredential(
      $clientId, $clientSecret));
      $apiContext->setConfig([ 'mode' => 'live']);

    3. We make a request to create a payment. If you plan to accept payment from a paypal account, as well as a card attached to it, do not forget to indicate the payment method: paypal
      $payer = new Payer();
      $amount = new Amount();
      $item1 = new Item();
      $item1->setName('Продажа товара/услуги')->setCurrency('RUB')->setQuantity(1)->setPrice('10');
      // Ид товара/услуги на вашей стороне
      $itemList = new ItemList();
      $transaction = new Transaction();
      $transaction->setDescription('Payment to UnitPay');
      $payment = new Payment();
          "return_url" => $resultUrl,
          "cancel_url" => $resultUrl

    4. In response, we get the payment number in PayPal and redirectURL of the payment form, where we transfer the user:
      // ID платежа, связываем его с заказом и сохраняем в БД
      $links = $payment->getLinks();
      foreach ($links as $link) {
          if ($link->getMethod() == 'REDIRECT') {

    5. Customer Account Confirmation:

    6. Automatic client return with GET parameters token, PayerID on $ resultUrl (see step 3).
    7. The money has been debited, but the payment has not yet been made. We tell PayPal that yes, we accurately confirm the payment:
      $apiContext = new ApiContext(new OAuthTokenCredential(
          $clientId, $clientSecret));
      $apiContext->setConfig([ 'mode' => 'live']);
      $payment = Payment::get($payment->getExternalPaymentId(), $apiContext);
      $paymentExecution= new PaymentExecution();
      $payment->execute($paymentExecution, $apiContext);

    8. Optionally PayPal produces a notification of payments to the specified URL, it is called their IPN :

      Each such notification received must be validated by a response request to PayPal. You also need to verify the payment amount, currency and email recipient. It remains only to wait for the cherished status of completed and the payment can be considered completed. If you do not want to contact IPN, then you can always simply ask the PayPal platform about the status of required payments, for example, via cron, although IPN is still more convenient:
      $ipn = new PPIPNMessage(null, array(['mode' => 'live']));
      if (!$ipn->validate()) {
      	throw new \Exception('Не пройдена валидация платежа на стороне PayPal');
      // $_GET['txn_id']          Ид платежа PayPal
      // $_GET['mc_gross']        Сумма платежа
      // $_GET['mc_currency']     Валюта платежа
      // $_GET['payer_email']     Еmail плательщика 
      // $_GET['item_number1']    Ид первого товара
      // $_GET['payment_status']  Статус заказа
      // $_GET['receiver_email']  Email получателя
      switch ($_GET['payment_status']) {
      	// Платеж успешно выполнен, оказываем услугу
      	case 'completed': break;
      	// Платеж не прошел
      	case 'failed': break;
      	// Платеж отменен продавцом
      	case 'denied': break;
      	// Деньги были возвращены покупателю
      	case 'refunded': break;

    In our opinion, most of the steps in this scheme are redundant: you can remove repeated checks to PayPal at the stage of payment notifications by simply signing the data sent in advance. The same applies to unnecessary actions with confirmation of a payment already made by the user. Also, in addition to storing the PayPal payment number, you will have to organize token storage for the unique identification of the order and step 7. An alternative is to generate a return Url with a unique key.

    At the moment, PayPal API is one of the most confusing and controversial among popular payment systems, but on the other hand, if, without minimizing, walking along the beaten path, then everything will work out.

    Do not have a hundred rubles, but have a hundred friends

    In turn, we have simplified the connection and work with PayPal and are ready to provide a number of payment instruments to choose from.

    If you are just thinking about how to implement payment acceptance for your project and what payment methods are suitable for you besides PayPal, then we recommend the fastest and easiest way to connect - the universal payment method UnitPay . Among other payment methods, PayPal will be available.

    For those who have already formed their list of payment systems and just want to expand it by connecting PayPal, we suggest using our API, a full description of which can be found on your project page.

    And what about the CIS countries?

    Unfortunately, while PayPal is not available for a number of countries closest to us. Many have a number of difficulties with this and offer quite different solutions . We think that soon this situation will change for the better.


    PayPal in Russia is still very young, but it has a rich past and huge potential. We hope that very little time will pass, and it will take its rightful place in the list of safe and convenient payment systems in the domestic market.

    Also popular now: