paypal api signature что это

Знакомимся с PayPal API

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что этоНа данный момент, PayPal — это самая популярная платформа электронных платежей. Именно то, насколько легко можно открыть счет и начать получать на него средства, по сравнению с традиционными способами получения платежей, и является причиной #1 его запредельной популярности. Второй причиной, многие со мной согласятся, является мощный API, предоставляемый PayPal. В этом топике я по порядку разложу все способы и трюки, связанные с работой PayPal API, чтобы вы избежали проблем с его интеграцией.

Предупреждение: PayPal API является одним из самых отвратительных, что я когда либо видел. Несоответствующая действительности, кое-где неполная или несогласованная документация, непредсказумые отказы и существенная разница между работой API в реальных условиях и в песочнице, все это по сути боль в заднице, с которой приходится сталкиваться.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

PayPal предлагает целый спектр способов платежей, что не может не запутать человека, малознакомого с PP:

Экспресс-платеж
Основной сервис из целого ряда аналогичных, предлагаемых PayPal. Экспресс-платеж позволит вам получать средства, не имея аккаунта продавца, и в общем-то каких бы то ни было особых требований, окромя банального подтверждения аккаунта (либо через банковский аккаунт, либо через кредитную\дебетовую карту), нет. Раньше, пользователи могли принимать экспресс-платежи только от других пользователей PayPal, но с тех пор, как в систему ввели возможность оплаты прямо с банковской карты для тех, у кого нет аккаунта, получать платежи можно практически от всех, у кого есть карта. Прошу заметить, что экспресс-платежи целиком и полностью выполняются на платформе PayPal, таким образом данный метод невозможно в полной мере интегрировать на ваш веб-сайт.

Прямой платеж
Этот метод позволит вам получать платежи с банковских карт через простейший вызов API. Это позволит вам полностью интегрировать весь процесс перевода на ваш веб-сайт, что, в некоторых случаях, сделает покупки для ваших пользователей более удобными. Есть еще одна вариация прямого платежа, которая позволит вам авторизовать перевод и выполнить его только через некоторый промежуток времени. Метод с откладыванием платежа доступен только пользователям из США, Канады и Соединенного Королевства.

Повторяющийся платеж
Этот метод позволит вам повторно снимать средства со счета пользователя (к примеру, он используется в ежемесячной оплате за какую-нибудь подписку).

Массовый платеж
Массовый платеж позволит разделить полученные средства между несколькими аккаунтами.

Адаптивные платежи
Этот вариант в принципе выполняет ту же функцию, что и предыдущий, но с некоторыми отличиями (я вроде бы уже упомянул о том, что PayPal API запутанный и полный излишеств).

Этот список нельзя назвать полным, но в нем перечислены самые популярные способы получения средств (Хотите больше — добро пожаловать в документацию).

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
PayPal поддерживает два формата передачи данных через протокол HTTP: NVP и SOAP. NVP — аббревиатура к Name-Value Pair (Пара Имя-Значение), тем временем SOAP означает Simple Object Access Protocol. Я расскажу только о NVP, так как он гораздо более гибок по сравнению с SOAP.

Запросы передаются с помощью протокола HTTPS. Для примера мы будем использовать cURL для формирования нашего простого запроса, а затем поместим весь процесс в отдельный класс:

Обратите внимание на то, что я использовал CA-сертификат для SSL-валидации. Файл сертификата можно найти на сайте cURL. Не забудьте изменить путь к сертификату в соответствии с тем расположением, куда вы его загрузили.

Ответ на запрос будет в формате NVP, и я его разбил в массив. Параметр ACK указывает результат обработки запроса: Success или SuccessWithWarning в случае, если запрос был успешным, Error или Warning в случае, если запрос провалился.

Запрос может быть отклонен по множеству причин, причем для каждого метода платежа есть свои причины, которые детально рассматриваются в документации. Чуть позже мы рассмотрим некоторые из них и научимся их устранять. Кстати, обратите внимание на то, что все параметры в запросе чувствительны к регистру, зачастую именно это является причиной сбоя.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Одним из самых популярных способов перевода средств является экспресс-платеж, который позволяет получать средства без открытия специального аккаунта (Website Payments Pro), который доступен только гражданам США, причем платеж проводится на стороне PayPal, что не требует никакой защиты.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Запуск процесса экспресс-оплаты происходит путем отправки данных о платеже в PayPal API, после чего мы получаем токен, который идентифицирует нашу транзакцию. Этот токен пригодится на следующем шаге, когда мы направим пользователя на платформу PayPal.

Переменная m идентифицирует конкретный товар (используйте один и тот же индекс переменной для параметров, применимых к одному и тому же товару).

Существует еще целое множество необязательных параметров, которые вы с легкостью можете найти в документации.

Мы используем функцию, написанную нами ранее в ч. 2, чтобы сформировать запрос SetExpressCheckout :

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Если запрос был успешным, мы получим токен в параметре TOKEN в ответе от PayPal.
Теперь пользователь отправляется на платформу PayPal, где будет обрабатываться весь процесс перевода. Когда пользователь успешно проведет или отменит платеж, его отправит на одну из соответствующих страниц, которые мы указали в запросе.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Прямой платеж позволяет полностью контролировать весь процесс перевода средств прямо на вашем сайте. По какой-то непонятной причине, в этом случае покупатели без PayPal-аккаунта не смогут оплачивать услуги и товары на вашем сайте, но зато можно будет сделать весь процесс максимально простым, что положительно скажется на мнении пользователей. Полный контроль над процессом фактически позволяет нам оптимизировать и увеличивать продажи.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Прямой платеж, как и было сказано ранее, требует указания совершенно иных параметров. Несмотря на то, что параметры, указывающие детали перевода, схожи с экспресс-платежом (те же назначения, другие имена, так веселее), этот метод требует информацию о банковской карте и адресе.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Если бы мы жили в идеальном мире, этой части бы не было. В реальности же вам придется обращаться к этой части или аналогичным разделам в других статьях достаточно часто. PayPal может отказать в проведении платежа по одной из целой кучи ошибок, причем исправление некоторых из них нам не подконтрольно.

В API PayPal можно найти гораздо больше методов и способов, больше, чем на один топик. Как только вы научитесь работать с двумя самыми популярными способами, изучение остальных станет гораздо проще. Я надеюсь, что этот гайд даст вам хороший старт в использовании API.
paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Оригинал статьи: Getting Started With The PayPal API, Eran Galperin, 5 сентября 2011.

Я очень надеюсь, что этот перевод действительно будет полезен хабрасообществу. Другими словами, я все еще не теряю надежды на праздник 24 сентября. Поживем — увидим.
paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это
Этот текст распространяется на условиях лицензии «Creative Commons Attribution-NonCommercial-ShareAlike 3.0».
Вы можете копировать, редактировать и использовать не в коммерческих целях этот текст при обязательном указании авторства и сохранении оригинальной лицензии.

Источник

PayPal NVP API Basics

Note: The PayFlow API also uses name-value pairs to provide parameter-based association between request and response fields of a message and their values; however, the PayFlow API is not the same as the NVP API; for more information about the PayFlow API, see the Payflow Gateway Developer Guide and Reference.

PayPal API client-server architecture

The PayPal API uses a client-server model. Your website is a client of the PayPal server.

A page on your website initiates an action on a PayPal API server by sending a request to the server. The PayPal server responds with a confirmation that the requested action was taken or indicates that an error occurred. The response might also contain additional information related to the request. The following diagram shows the basic request-response mechanism.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

For example, you might want to get the customer’s shipping address from PayPal. You can initiate an API request to get customer details. The response from the PayPal API server contains information about whether the request was successful. If the operation succeeds, the response contains the requested information. In this case, the response contains the customer’s shipping address. If the operation fails, the response contains one or more error messages.

PayPal Name-Value Pair API requests and responses

To complete a PayPal NVP API operation, send an NVP-formatted request to a PayPal NVP server and interpret the response.

In this diagram, your website generates a request. The request runs on a PayPal server and the response is returned to your site.

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

The request identifies:

Note: After the METHOD parameter, you can specify the other parameters in any order.

A PayPal API server completes the operation and returns a response.

The response contains:

UTF-8 character encoding

The PayPal API assumes that all request data is in Universal Coded Character Set (UCS) Transformation Format – 8-bit encoding form (UTF-8).

The API always returns data in UTF-8.

Multiple API operations

Some features, such as Express Checkout, require that you to call multiple API operations.

Typically, these features require you to:

The following diagram shows the execution flow between your website and PayPal:

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

Token usage

Typically, the API operation that sets up a redirection to PayPal ( SetExpressCheckout ) returns a token. This token is passed as a parameter in the redirect to PayPal. The token also might be required in related API operations.

NVP format

NVP specifies names and values in a string. NVP is the informal name for the query in the URI specification. The NVP string is appended to the URL.

An NVP string conforms to these guidelines:

Create an NVP request

The Name-Value Pair request format specifies the API operation to perform, credentials that authorize PayPal to access your account, and fields containing additional information to be used in the request.

Specify the PayPal API operation

For the NVP version of the PayPal API, you must specify the name of the PayPal API operation to execute in each request along with the version of the API operation.

The following diagram shows the API operation part of an NVP request:

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

A method specifies the PayPal operation you want to execute, and each method is associated with a version. Together, the method and version define the exact behavior of the API operation. Typically, the behavior of an API operation does not change between versions; however, you should carefully retest your code whenever you change a version.

To specify a method and version number:

Use API signature credentials

You must specify API credentials in each request to execute a PayPal API operation. You can use either a signature or a certificate, but not both.

When you execute a PayPal API operation, you use credentials, such as a signature, to authenticate that you are requesting the API operation. The following diagram shows the API credentials part of an NVP request:

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

To enable PayPal to authenticate your request:

If you’re calling the API on behalf of a third-party merchant, you must specify the email address on file with PayPal of the third-party merchant or the merchant’s account ID (sometimes called Payer ID). SUBJECT= Authorizing-Merchant-Email Or Authorizing-Merchant-Account-ID

Note: Third-party merchants can look up their merchant ID by logging into https://www.paypal.com, clicking the profile icon ( ) on the top right side of the page and then selecting Profile and settings in the Business Profile menu. (If you do not see a profile icon at the top of the page, click Profile, which appears in the top menu when the My Account tab is selected.) Click My business info on the left, and the Merchant account ID is displayed in the list of profile items on the right.

Typically, a merchant grants third-party permissions to a shopping cart, so the shopping cart can call the API on the merchant’s behalf. The merchant must have previously granted you permission to execute the API operation.

Specify credentials with cURL

The following example shows one way to specify a signature using cURL:

Note: Because this example does not establish a secure connection, do not use it in the live environment.

URL encoding

You must URL-encode all HTTP requests to execute PayPal API operations. The encoding ensures that you can transmit:

The PayPal NVP API uses the HTTP protocol to send requests to and receive responses from a PayPal API server.

You must encode all data sent using the HTTP protocol because data that is not encoded can be misinterpreted as part of the HTTP protocol instead of part of the request.

Most programming languages provide a way to encode strings in this way. You should consistently URL-encode the complete API request. Otherwise, you might find that unanticipated data causes an error.

Note: Most browsers automatically URL-encode HTTP forms.

For example, this NVP string:

Is encoded, as follows:

Encode and decode methods for URLs

Use these methods to URL-encode or URL-decode your NVP strings:

LanguageEncode or decodeMethod
ASP.NETEncodeSystem.Web.HttpUtility.UrlEncode(buffer, Encoding.Default)
DecodeSystem.Web.HttpUtility.UrlDecode(buffer, Encoding.Default)
JavaEncodejava.net.URLEncoder.encode
Decodejava.net.URLDecoder.decode
PHPEncodeurlencode()
Decodeurldecode()
ColdFusionEncodeURLEncodedFormatstring [, charset]
DecodeURLDecodeurlEncodedString[, charset])

List syntax for name-value pairs

The PayPal API uses a special syntax for NVP fields defined as lists.

Note: Not all lists follow the L_ prefix convention. However, all lists begin at 0 for the first element.

Additionally, you can pass lists within lists, which also use an offset that starts with 0 as the first element. For example, L_PAYMENTREQUEST_0_DESC0 is the description of the first item in the first payment.

Execute NVP API operations

You execute a PayPal NVP API operation by submitting an HTTPS POST request to a PayPal API server, or by using cURL or another mechanism to provide secure access between the buyer’s browser and the PayPal API server. For example, you might implement a system in which the buyer’s browser remains a client of your server and your server becomes a client of the PayPal API server.

Specify a PayPal server

You execute a PayPal API operation by submitting the request to a PayPal API server.

To execute a PayPal NVP API operation, submit the request to one of the following endpoints:

Server endpointDescription
https://api-3t.sandbox.paypal.com/nvpThe sandbox, or test, server for use with API signature credentials.
https://api-3t.paypal.com/nvpThe PayPal live production server for use with API signature credentials.
https://api.sandbox.paypal.com/nvpThe sandbox, or test, server for use with API certificate credentials.
https://api.paypal.com/nvpThe PayPal live production server for use with API certificate credentials.

Note: You must use different API credentials for each server endpoint. Typically, you obtain API credentials when you test in the sandbox and then obtain another set of credentials for the production server. You must change each API request to use the new credentials when you go live.

Log API operations

You must log basic information from the request and response messages of each PayPal API operation you execute. You must log the CorrelationID returned in the response message, which identifies the PayPal application that processed the request and must be provided to Merchant Technical Support if you need their assistance with a specific transaction.

All responses to PayPal API operations contain information that may be useful for debugging purposes. In addition to logging the Correlation ID from the response message, you can log other information, such as the transaction ID and timestamp, to enable you to review a transaction on the PayPal website or through the API. You could implement a scheme that logs the entire request and response in a «verbose» mode; however, you should never log the password from a request.

Respond to an NVP response

The Name-Value Pair response consists of the answer to the request as well as common fields that identify the API operation and how it was executed.

The following diagram shows fields in the response to a PayPal NVP API operation:

paypal api signature что это. Смотреть фото paypal api signature что это. Смотреть картинку paypal api signature что это. Картинка про paypal api signature что это. Фото paypal api signature что это

Common response fields

The PayPal API always returns common fields in addition to fields that are specific to the requested PayPal API operation.

A PayPal API response includes the following fields:

Error responses

The value of the ACK response is:

Error response format

An error response has this format:

Multiple errors can be returned. Each set of errors has a different numeric suffix in the field name, starting with 0 and incremented by one for each error.

Additional pass-through information can appear in the L_ERRORPARAMID n and L_ERRORPARAMVALUE n fields.

In this error response:

The value contains the processor-specific error.

PayPal does not set these values. Instead, these values are passed through from the source.

Note: PayPal only passes selected values in the L_ERRORPARAMID n and L_ERRORPARAMVALUE n fields.

URL decoding

You must URL-decode all responses to HTTP POST operations from the PayPal NVP API

The PayPal NVP API uses the HTTP protocol to send requests and receive responses from a PayPal API server. You must decode all data returned through the HTTP protocol so that it can be displayed properly. Most programming languages provide a way to URL-decode strings.

Источник

Create and Manage NVP/SOAP API Credentials

When you call PayPal NVP/SOAP APIs, you must authenticate each request through a set of API credentials. PayPal associates these credentials with a PayPal account. You can generate credentials for any PayPal Business or Premier account.

Types of credentials

All PayPal API certificate credentials are 2048-bit, SHA-256 certificates that expire every three years.

The NVP/SOAP APIs support:

Contain the API user name and password and the certificate.

PayPal recommends that you use certificate credentials for security reasons. See API certificates.

Contain the API user name and password and the signature. See API signatures.

Note: All Adaptive platform APIs require that you supply an appID with your signature or certificate credentials. The Adaptive APIs include Adaptive Payments, Adaptive Accounts, Permissions Service, and Invoicing Service.

API certificates

Learn how to create and manage certificate API credentials.

Create API certificates

Note: If your API certificate is expiring, proceed to Renew an API certificate.

For live credentials, log in to your PayPal business account at www.paypal.com.

For test credentials, log in to the PayPal sandbox at www.sandbox.paypal.com with a sandbox merchant account.

Click the settings icon at the top of your PayPal account page and then click Account Settings.

Click Manage API Credentials in the NVP/SOAP API Integration (Classic) section.

Note: If you have already generated an API certificate, clicking Manage API Credentials displays the certificate information. If you must generate an API certificate, click Remove Certification to delete the existing certificate.

On the Request API certificate page, select Request API certificate.

Then, click Agree and Submit.

The Manage API certificate page appears.

The cert_key_pem.txt file contains the certificate. Save the file to a secure location.

PayPal formats the API certificate file in PEM format. The file contains both your public certificate and the associated private key. Although the PEM certificate is not human readable, the file is not encrypted. For details, see Encrypt your certificate.

Renew API certificates

To prevent an interruption in API services, you must renew and replace your certificate before it expires.

For live credentials, log in to your PayPal business account at www.paypal.com.

For test credentials, log in to the PayPal sandbox at www.sandbox.paypal.com with a sandbox business account.

Click the settings icon at the top of your PayPal account page and then click Account Settings.

If the status is Expires soon, click Renew Certificate.

This action generates an additional certificate with the Active status. The Manage API certificate page shows both certificates.

After you import the new API certificate, test your integration to ensure it works with the certificate. Distribute your certificate to all affected partners. After the old certificate expires, click Remove Certificate to remove the certificate.

Encrypt API certificates

The PayPal SDKs for Java and ASP.NET require that you encrypt the certificate into PKCS12 format before you can use it with the SDKs.

Note: The PayPal SDK for PHP does not require SSL encryption.

Tip: If you use encryption, ensure that you encrypt both your sandbox and live API certificates.

The steps to encrypt your certificate require the OpenSSL encryption tool. While UNIX users likely have this tool installed with their operating system, Windows users must download OpenSSL. To install OpenSSL, accept the defaults.

Change directories to the location of the certificate to encrypt ( cert_key_pem.txt ) and run:

Note: When you encrypt a certificate, you are prompted for a password to use to decrypt the file. At the Enter Export password prompt, enter a password. Store it in a secure location.

The paypal_cert.p12 file contains your encrypted API certificate.

Install API certificates for ASP.NET

If you are developing with the PayPal SDK for ASP.NET, Windows requires that you:

Import the certificate into the Windows certificate store.

For more information, see the Microsoft Import or export certificates and private keys support article.

For more information, see the PayPal How do I import my certificate into the Windows key store? knowledge base article.

API signatures

To create an API signature:

For live credentials, log in to your PayPal business account at www.paypal.com.

For test credentials, log in to the PayPal sandbox at www.sandbox.paypal.com with a sandbox business account.

Click the settings icon at the top of your PayPal account page and then click Account Settings.

Click Manage API Credentials in the NVP/SOAP API Integration (Classic) section.

Note: If you have already generated an API signature, clicking Manage API Credentials displays the signature information. If you must generate an API signature, click Remove to delete the existing API signature.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Response fields on error