paypal api signature что это
Знакомимся с PayPal API
На данный момент, PayPal — это самая популярная платформа электронных платежей. Именно то, насколько легко можно открыть счет и начать получать на него средства, по сравнению с традиционными способами получения платежей, и является причиной #1 его запредельной популярности. Второй причиной, многие со мной согласятся, является мощный API, предоставляемый PayPal. В этом топике я по порядку разложу все способы и трюки, связанные с работой PayPal API, чтобы вы избежали проблем с его интеграцией.
Предупреждение: PayPal API является одним из самых отвратительных, что я когда либо видел. Несоответствующая действительности, кое-где неполная или несогласованная документация, непредсказумые отказы и существенная разница между работой API в реальных условиях и в песочнице, все это по сути боль в заднице, с которой приходится сталкиваться.
PayPal предлагает целый спектр способов платежей, что не может не запутать человека, малознакомого с PP:
Экспресс-платеж
Основной сервис из целого ряда аналогичных, предлагаемых PayPal. Экспресс-платеж позволит вам получать средства, не имея аккаунта продавца, и в общем-то каких бы то ни было особых требований, окромя банального подтверждения аккаунта (либо через банковский аккаунт, либо через кредитную\дебетовую карту), нет. Раньше, пользователи могли принимать экспресс-платежи только от других пользователей PayPal, но с тех пор, как в систему ввели возможность оплаты прямо с банковской карты для тех, у кого нет аккаунта, получать платежи можно практически от всех, у кого есть карта. Прошу заметить, что экспресс-платежи целиком и полностью выполняются на платформе PayPal, таким образом данный метод невозможно в полной мере интегрировать на ваш веб-сайт.
Прямой платеж
Этот метод позволит вам получать платежи с банковских карт через простейший вызов API. Это позволит вам полностью интегрировать весь процесс перевода на ваш веб-сайт, что, в некоторых случаях, сделает покупки для ваших пользователей более удобными. Есть еще одна вариация прямого платежа, которая позволит вам авторизовать перевод и выполнить его только через некоторый промежуток времени. Метод с откладыванием платежа доступен только пользователям из США, Канады и Соединенного Королевства.
Повторяющийся платеж
Этот метод позволит вам повторно снимать средства со счета пользователя (к примеру, он используется в ежемесячной оплате за какую-нибудь подписку).
Массовый платеж
Массовый платеж позволит разделить полученные средства между несколькими аккаунтами.
Адаптивные платежи
Этот вариант в принципе выполняет ту же функцию, что и предыдущий, но с некоторыми отличиями (я вроде бы уже упомянул о том, что PayPal API запутанный и полный излишеств).
Этот список нельзя назвать полным, но в нем перечислены самые популярные способы получения средств (Хотите больше — добро пожаловать в документацию).
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 в случае, если запрос провалился.
Запрос может быть отклонен по множеству причин, причем для каждого метода платежа есть свои причины, которые детально рассматриваются в документации. Чуть позже мы рассмотрим некоторые из них и научимся их устранять. Кстати, обратите внимание на то, что все параметры в запросе чувствительны к регистру, зачастую именно это является причиной сбоя.
Одним из самых популярных способов перевода средств является экспресс-платеж, который позволяет получать средства без открытия специального аккаунта (Website Payments Pro), который доступен только гражданам США, причем платеж проводится на стороне PayPal, что не требует никакой защиты.
Запуск процесса экспресс-оплаты происходит путем отправки данных о платеже в PayPal API, после чего мы получаем токен, который идентифицирует нашу транзакцию. Этот токен пригодится на следующем шаге, когда мы направим пользователя на платформу PayPal.
Переменная m идентифицирует конкретный товар (используйте один и тот же индекс переменной для параметров, применимых к одному и тому же товару).
Существует еще целое множество необязательных параметров, которые вы с легкостью можете найти в документации.
Мы используем функцию, написанную нами ранее в ч. 2, чтобы сформировать запрос SetExpressCheckout :
Если запрос был успешным, мы получим токен в параметре TOKEN в ответе от PayPal.
Теперь пользователь отправляется на платформу PayPal, где будет обрабатываться весь процесс перевода. Когда пользователь успешно проведет или отменит платеж, его отправит на одну из соответствующих страниц, которые мы указали в запросе.
Прямой платеж позволяет полностью контролировать весь процесс перевода средств прямо на вашем сайте. По какой-то непонятной причине, в этом случае покупатели без PayPal-аккаунта не смогут оплачивать услуги и товары на вашем сайте, но зато можно будет сделать весь процесс максимально простым, что положительно скажется на мнении пользователей. Полный контроль над процессом фактически позволяет нам оптимизировать и увеличивать продажи.
Прямой платеж, как и было сказано ранее, требует указания совершенно иных параметров. Несмотря на то, что параметры, указывающие детали перевода, схожи с экспресс-платежом (те же назначения, другие имена, так веселее), этот метод требует информацию о банковской карте и адресе.
Если бы мы жили в идеальном мире, этой части бы не было. В реальности же вам придется обращаться к этой части или аналогичным разделам в других статьях достаточно часто. PayPal может отказать в проведении платежа по одной из целой кучи ошибок, причем исправление некоторых из них нам не подконтрольно.
В API PayPal можно найти гораздо больше методов и способов, больше, чем на один топик. Как только вы научитесь работать с двумя самыми популярными способами, изучение остальных станет гораздо проще. Я надеюсь, что этот гайд даст вам хороший старт в использовании API.
Оригинал статьи: Getting Started With The PayPal API, Eran Galperin, 5 сентября 2011.
Я очень надеюсь, что этот перевод действительно будет полезен хабрасообществу. Другими словами, я все еще не теряю надежды на праздник 24 сентября. Поживем — увидим.
Этот текст распространяется на условиях лицензии «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.
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.
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:
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:
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:
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:
Language | Encode or decode | Method |
---|---|---|
ASP.NET | Encode | System.Web.HttpUtility.UrlEncode(buffer, Encoding.Default) |
Decode | System.Web.HttpUtility.UrlDecode(buffer, Encoding.Default) | |
Java | Encode | java.net.URLEncoder.encode |
Decode | java.net.URLDecoder.decode | |
PHP | Encode | urlencode() |
Decode | urldecode() | |
ColdFusion | Encode | URLEncodedFormatstring [, charset] |
Decode | URLDecodeurlEncodedString[, 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 endpoint | Description |
---|---|
https://api-3t.sandbox.paypal.com/nvp | The sandbox, or test, server for use with API signature credentials. |
https://api-3t.paypal.com/nvp | The PayPal live production server for use with API signature credentials. |
https://api.sandbox.paypal.com/nvp | The sandbox, or test, server for use with API certificate credentials. |
https://api.paypal.com/nvp | The 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:
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:
Response fields on error |