academe/sagepaymsg

一个用于处理 Sage Pay 集成服务消息内容和结构的库

2.1.1 2023-09-20 17:35 UTC

This package is auto-updated.

Last update: 2024-08-30 00:10:27 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

注意

此包已弃用。请现在使用 academe/opayo-pi

Sage Pay 集成 PSR-7 消息 REST API 库

此包为 Sage Pay 集成 支付网关提供数据模型,也称为 Sage Pay PiREST API。它不提供传输机制,因此您可以自由选择使用 Guzzle、curl 或其他 PSR-7 库。

您可以使用此库作为 PSR-7 消息生成/消费者,或者深入一层,通过数组处理所有数据 - 都支持。

包开发

Sage Pay 集成支付网关是由 Sage Pay 运行的 RESTful API。您可以在 此处申请账户(我的合作伙伴链接)。

与之前的 PSR7 分支相比,此 master 分支包含许多类别的重组和重命名。新的类名应更紧密地与 API 的 RESTful 特性相联系。现在的 PSR7 分支仅处于维护模式,不会有任何重大更改 - 只在有报告的 bugfix。目标是尽快在 master 分支上发布,一旦演示(和一些单元测试)运行起来。

目标是让此包支持网关支持的 ALL 功能,并快速跟上更改。

想帮忙吗?

欢迎提出问题、评论、建议和 PR。据我所知,这是第一个 Sage Pay 集成 REST API 的 API,所以请积极参与,因为还有很多工作要做。

需要编写测试。我可以扩展测试,但还没有达到从头开始设置测试框架的阶段。

还需要更多关于如何处理错误的示例。可以在许多地方引发异常。一些异常是远程端的问题,一些是致命的认证错误,还有一些只是与支付表单上的验证错误相关,需要用户修正他们的详细信息。临时令牌在一定期限内过期,并且在少量使用后,因此所有这些都需要捕获,并将用户带回到协议中的相关位置,而不会丢失他们之前输入的内容(尚未过期)。

概述;如何使用

请注意,此示例代码仅处理从后端使用网关。还有一个 JavaScript 前端,具有处理过期会话密钥和卡令牌的挂钩。尽管如此,此库也提供对前端的支持,并在相关位置进行了说明。

安装

获取最新版本

composer.phar require academe/sagepaymsg

在此库发布到 packagist 之前,请在 composer.json 中包含 VCS

"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/academe/SagePay-Integration.git"
    }
]

创建会话密钥

CreateSessionKey 消息添加了 PSR-7 支持,并可以使用如下方式使用

// composer require guzzlehttp/guzzle
// This will bring in guzzle/psr7 too, which is what we will use.

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException; // Or your favourite PSR-18 client
use Academe\SagePay\Psr7\Model\Auth;
use Academe\SagePay\Psr7\Model\Endpoint;
use Academe\SagePay\Psr7\Request\CreateSessionKey;
use Academe\SagePay\Psr7\Factory;
use Academe\SagePay\Psr7\Request\CreateCardIdentifier;
use Academe\SagePay\Psr7\Factory\ResponseFactory;

// Set up authentication details object.

$auth = new Auth('vendor-name', 'your-key', 'your-password');

// Also the endpoint.
// This one is set as the test API endpoint.

$endpoint = new Endpoint(Endpoint::MODE_TEST); // or Endpoint::MODE_LIVE

// Request object to construct the session key message.

$keyRequest = new CreateSessionKey($endpoint, $auth);

// PSR-7 HTTP client to send this message.

$client = new Client();

// You should turn HTTP error exceptions off so that this package can handle all HTTP return codes.

$client = new Client();

// Send the PSR-7 message. Note *everything* needed is in this message.
// The message will be generated by guzzle/psr7 or zendframework/zend-diactoros, with discovery
// on which is installed. You can explictly create the PSR-7 factory instead and pass that in
// as a third parameter when creating Request\CreateSessionKey.

$keyResponse = $client->sendRequest($keyRequest->message());

// Capture the result in our local response model.
// Use the ResponseFactory to automatically choose the correct message class.

$sessionKey = ResponseFactory::fromHttpResponse($keyResponse);

// If an error is indicated, then you will be returned an ErrorCollection instead
// of the session key. Look into that to diagnose the problem.

if ($sessionKey->isError()) {
    // $session_key will be Response\ErrorCollection
    var_dump($sessionKey->first());
    exit; // (Obviously just a test script!)
}

// The result we want:

echo "Session key is: " . $sessionKey->getMerchantSessionKey();

获取卡标识符

可以使用临时会话密钥创建卡标识符(一个临时、令牌化的卡详情)。

通常情况下,这将在前端创建,使用来自浏览器的AJAX请求,因此卡片详情永远不会触及您的应用程序。对于测试和开发,可以从测试脚本中发送卡片详情,模拟前端。

use Academe\SagePay\Psr7\Request\CreateCardIdentifier;

// Create a card indentifier on the API.
// Note the MMYY order is most often used for GB gateways like Sage Pay. Many European
// gateways tend to go MSN first, i.e. YYMM, but not here.
// $endpoint, $auth and $session_key from before:

$cardIdentifierRequest = new CreateCardIdentifier(
    $endpoint, $auth, $sessionKey,
    'Fred', '4929000000006', '1220', '123' // name, card, MMYY, CVV
);

// Send the PSR-7 message.
// The same error handling as shown earlier can be used.

$cardIdentifierResponse = $client->sendRequest($cardIdentifierRequest->message());

// Grab the result as a local model.
// If all is well, we will have a Resposne\CardIdentifier that will be valid for use
// for the next 400 seconds.

$cardIdentifier = Factory\ResponseFactory::fromHttpResponse($cardIdentifierResponse);

// Again, an ErrorCollection will be returned in the event of an error:

if ($cardIdentifier->isError()) {
    // $session_key will be Response\ErrorCollection
    var_dump($cardIdentifier->first());
    exit; // Don't do this in production.
}

// When the card is stored at the front end browser only, the following three
// items will be posted back to your application.

echo "Card identifier = " . $cardIdentifier->getCardIdentifier();
echo "Card type = " . $cardIdentifier->getCardType(); // e.g. Visa

// This card identifier will expire at the given time. Do note that this
// will be the timestamp at the Sage Pay server, not locally. You may be
// better off just starting your own 400 second timer here.

var_dump($cardIdentifier->getExpiry()); // DateTime object.

此时,卡片详情是合理的,并且已经保存在远程API中。尚未与银行进行任何检查,所以我们目前还不知道这些详情是否会被认证。

对我来说是个谜的是,为什么需要卡片标识符。会话密钥只对一组卡片详情有效,因此会话密钥应该是Sage Pay在最终购买请求时访问这些卡片详情所需了解的所有信息。但不是这样,这个额外的“卡片标识符”也需要发送到网关。

merchantSessionKey标识网关中一个短暂的存储区域,用于在客户端和网关之间传递卡片详情。cardIdentifier然后标识存储区域中的一个卡片。

提交交易

可以使用卡片标识符启动交易。

use Academe\SagePay\Psr7\Money;
use Academe\SagePay\Psr7\PaymentMethod;
use Academe\SagePay\Psr7\Request\CreatePayment;
use Academe\SagePay\Psr7\Request\Model\SingleUseCard;
use Academe\SagePay\Psr7\Money\Amount;
use Academe\SagePay\Psr7\Request\Model\Person;
use Academe\SagePay\Psr7\Request\Model\Address;
use Academe\SagePay\Psr7\Money\MoneyAmount;
use Money\Money as MoneyPhp;

// We need a billing address.
// Sage Pay has many mandatory fields that many gateways leave as optional.
// Sage Pay also has strict validation on these fields, so at the front end
// they must be presented to the user so they can modify the details if
// submission fails validation.

$billingAddress = Address::fromData([
    'address1' => 'address one',
    'postalCode' => 'NE26',
    'city' => 'Whitley',
    'state' => 'AL',
    'country' => 'US',
]);

// We have a customer to bill.

$customer = new Person(
    'Bill Firstname',
    'Bill Lastname',
    'billing@example.com',
    '+44 191 12345678'
);

// We have an amount to bill.
// This example is £9.99 (999 pennies).

$amount = Amount::GBP()->withMinorUnit(999);

// Or better to use the moneyphp/money package:

$amount = new MoneyAmount(MoneyPhp::GBP(999));

// We have a card to charge (we get the session key and captured the card identifier earlier).
// See below for details of the various card request objects.

$card = new SingleUseCard($session_key, $card_identifier);

// If you want the card to be reusable, then set its "save" flag:

$card = $card->withSave();

// Put it all together into a payment transaction.

$paymentRequest = new CreatePayment(
    $endpoint,
    $auth,
    $card,
    'MyVendorTxCode-' . rand(10000000, 99999999), // This will be your local unique transaction ID.
    $amount,
    'My Purchase Description',
    $billingAddress,
    $customer,
    null, // Optional shipping address
    null, // Optional shipping recipient
    [
        // Don't use 3DSecure this time.
        'Apply3DSecure' => CreatePayment::APPLY_3D_SECURE_DISABLE,
        // Or force 3D Secure.
        'Apply3DSecure' => CreatePayment::APPLY_3D_SECURE_FORCE,
        // There are other options available.
        'ApplyAvsCvcCheck' => CreatePayment::APPLY_AVS_CVC_CHECK_FORCE
    ]
);

// Send it to Sage Pay.

$paymentResponse = $client->sendRequest($paymentRequest->message());

// Assuming we got no exceptions, extract the response details.

$payment = ResponseFactory::fromHttpResponse($paymentResponse);

// Again, an ErrorCollection will be returned in the event of an error.
if ($payment->isError()) {
    // $payment_response will be Response\ErrorCollection
    var_dump($payment->first());
    exit;
}

if ($payment->isRedirect()) {
    // If the result is "3dAuth" then we will need to send the user off to do their 3D Secure
    // authorisation (more about that process in a bit).
    // A status of "Ok" means the transaction was successful.
    // A number of validation errors can be captured and linked to specific submitted
    // fields (more about that in a bit too).
    // In future gateway releases there may be other reasons to redirect, such as PayPal
    // authorisation.
    // ...
}

// Statuses are listed in `AbstractTransaction` and can be obtained as an array using the static
// helper method:
// AbstractTransaction::constantList('STATUS')

echo "Final status is " . $payment->getStatus();

if ($payment->isSuccess()) {
    // Payment is successfully authorised.
    // Store everything, then tell the user they have paid.
}

再次获取交易结果

给定交易ID,您可以获取交易详情。如果交易成功,则它将立即可用。如果需要3D Secure操作,则需要在获取交易之前将3D Secure结果发送到Sage Pay。无论如何,这是您这样做的方式

// Prepare the message.

$transaction_result = new Request\FetchTransaction(
    $endpoint,
    $auth,
    $transaction_response->getTransactionId() // From earlier
);

// Send it to Sage Pay.

$response = $client->sendRequest($transaction_result->message());

// Assuming no exceptions, this gives you the payment or repeat payment record.
// But do check for errors in the usual way (i.e. you could get an error collection here).

$fetched_transaction = ResponseFactory::fromHttpResponse($response);

重复支付

以前的交易可以用作重复支付的依据。您可以修改运输详情和金额(无限制),但不能修改收款人详情或地址。

use Academe\SagePay\Psr7\Request\CreateRepeatPayment;

$repeat_payment = new CreateRepeatPayment(
    $endpoint,
    $auth,
    $previous_transaction_id, // The previous payment to take card details from.
    'MyVendorTxCode-' . rand(10000000, 99999999), // This will be your local unique transaction ID.
    $amount, // Not limited by the original amount.
    'My Repeat Purchase Description',
    null, // Optional shipping address
    null // Optional shipping recipient
);

所有其他选项与原始交易相同(尽管现在API中似乎可以设置giftAid)。

使用 3D Secure

现在,如果您想使用3D Secure(您确实应该这样做),那么我们有一个回调来处理。

要启用3D Secure,请在发送付款时使用适当的选项

$payment = new CreatePayment(
    ...
    [
        // Also available: APPLY_3D_SECURE_USEMSPSETTING and APPLY_3D_SECURE_FORCEIGNORINGRULES
        'Apply3DSecure' => CreatePayment::APPLY_3D_SECURE_FORCE,
    ]
);

3D Secure 重定向

假设其他方面没有问题,交易的结果将是一个Secure3DRedirect对象。这个消息将为isRedirect()返回true。考虑到这一点,需要POST重定向。请注意,即使卡片详情无效,也可能返回3D Secure重定向。不清楚银行为什么要这样做,但您只能接受这一点。

这个简单的表单将演示如何进行重定向

// $transaction_response is the message we get back after sending the payment request.

if ($transactionResponse->isRedirect()) {
    // This is the bank URL that Sage Pay wants us to send the user to.

    $url = $transactionResponse->getAcsUrl();

    // This is where the bank will return the user when they are finished there.
    // It needs to be an SSL URL to avoid browser errors. That is a consequence of
    // the way the banks do the redirect back to the merchant siteusing POST and not GET,
    // and something we cannot control.

    $termUrl = 'https://example.com/your-3dsecure-result-handler-post-path/';

    // $md is optional and is usually a key to help find the transaction in storage.
    // For demo, we will just send the vendorTxCode here, but you should avoid exposing
    // that value in a real site. You could leave it unused and just store the vendorTxCode
    // in the session, since it will always only be used when the user session is available
    // (i.e. all callbacks are done through the user's browser).

    $md = $transactionResponse->getTransactionId();

    // Based on the 3D Secure redirect message, our callback URL and our optional MD,
    // we can now get all the POST fields to perform the redirect:

    $paRequestFields = $transactionResponse->getPaRequestFields($termUrl, $md);

    // All these fields will normally be hidden form items and the form would auto-submit
    // using JavaScript. In this example we display the fields and don't auto-submit, so
    // you can se what is happening:

    echo "<p>Do 3DSecure</p>";
    echo "<form method='post' action='$url'>";
    foreach($paRequestFields as $field_name => $field_value) {
        echo "<p>$field_name <input type='text' name='$field_name' value='$field_value' /></p>";
    }
    echo "<button type='submit'>Click here if not redirected in five seconds</button>";
    echo "</form>";

    // Exit in the appropriate way for your application or framework.
    exit;
}

上述示例没有考虑如何将3D Secure表单在iframe中显示而不是内联。这超出了这个简单描述的范围,至少现在是这样。使用iframe时需要考虑两个主要事项:1) 上面的表单必须通过名称target iframe;2) 在返回到$termUrl时,页面必须从iframe中退出。这是绝对的基本要求。

然后这个表单将引导用户到3D Secure密码页面。对于Sage Pay测试,当您到达测试3D Secure表单时,使用代码password获取成功的响应。

现在您需要处理银行的返回。使用Diactoros(现在还有Guzzle),您可以像这样捕获返回消息作为PSR-7 ServerRequest

use Academe\SagePay\Psr7\ServerRequest\Secure3DAcs;

$serverRequest = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
// or if using a framework that supplies a PSR-7 server request, just use that.

// isRequest() is just a sanity check before diving in with assumptions about the
// incoming request.

if (Secure3DAcs::isRequest($serverRequest->getBody()))
    // Yeah, we got a 3d Secure server request coming at us. Process it here.

    $secure3dServerRequest = new Secure3DAcs($serverRequest);
    ...
}

use Academe\SagePay\Psr7\ServerRequest\Secure3DAcs;

if (Secure3DAcs::isRequest($_POST)) {
    $secure3dServerRequest = Secure3DAcs::fromData($_POST);
    ...
}

两者都可以正常工作,但只是看哪个最适合您的框架和应用程序。

处理3D Secure结果涉及两个步骤

  1. 将结果传递给Sage Pay以获取3D Secure状态(注意:见下注解)。
  2. 从Sage Pay获取最终交易结果。
    use Academe\SagePay\Psr7\Request\CreateSecure3D;

    $request = new CreateSecure3D(
        $endpoint,
        $auth,
        $secure3dServerRequest,
        // Include the transaction ID.
        // For this demo we sent that as `MD` data rather than storing it in the session.
        // The transaction ID will generally be in the session; putting it in MD exposes it
        // to the end user, so don't do this unless use a nonce!
        $secure3dServerRequest->getMD()
    );

    // Send to Sage Pay and get the final 3D Secure result.

    $response = $client->send($request->message());
    $secure3dResponse = ResponseFactory::fromHttpResponse($response);

    // This will be the result. We are looking for `Authenticated` or similar.
    //
    // NOTE: the result of the 3D Secure verification here is NOT safe to act on.
    // I have found that on live, it is possible for the card to totally fail
    // authentication, while the 3D Secure result returns `Authenticated` here.
    // This is a decision the bank mnakes. They may skip the 3D Secure and mark
    // it as "Authenticated" at their own risk. Just log this information.
    // Instead, you MUST fetch the remote transaction from the gateway to find
    // the real state of both the 3D Secure check and the card authentication
    // checks.

    echo $secure3dResponse->getStatus();

3D Secure 之后的最终交易

无论3D Secure是否通过,都要获取交易信息。然而——不要过早获取。Sage Pay的测试实例在获取3D Secure结果和能够抓取交易之间存在轻微的延迟。此时最好暂停一秒钟,这是一个任意的间隔,但现在似乎有效。更好的方法是立即尝试,如果得到404错误,就短暂等待再尝试,如果必要可能再尝试一次。这应该在网关中多次修复,但偶尔仍被报告为问题。

    // Give the gateway some time to get its syncs in order.

    sleep(1);

    // Fetch the transaction with full details.

    $transactionResult = new FetchTransaction(
        $endpoint,
        $auth,
        // transaction ID would normally be in the session, as described above, but we put it
        // into the MD for this demo.
        $secure3dServerRequest->getMD()
    );

    // Send the request for the transaction to Sage Pay.

    $response = $client->sendRequest($transactionResult->message());

    // We should now have the payment, repeat payment, or an error collection.

    $transactionFetch = ResponseFactory::fromHttpResponse($response);

    // We should now have the final results.
    // The transaction data is all [described in the docs](https://test.sagepay.com/documentation/#transactions).

    echo json_encode($transactionFetch);

支付方式

目前,Sage Pay Pi仅支持card支付类型。然而,有三种不同类型的卡片对象

  1. SingleUseCard - 第一次使用卡片。它已被标记化,将在400秒后丢弃,在此期间将保留在商家会话密钥中。
  2. ReusableCard - 已保存并可以重复使用的卡片。在没有使用CVV的情况下用于非交互式支付。
  3. ReusableCvvCard - 已保存并可重复使用的卡片,并与CVV和商家会话相关联。用于交互式重复使用卡片,用户需要提供CVV以提供额外安全性,但不需要重新输入所有卡信息。CVV(通常)在客户端与卡片和商家会话相关联,因此将在有限时间内(400秒)保持活动状态。

ReusableCard不需要商家会话密钥。ReusableCvvCard需要商家会话密钥,并需要调用将会话密钥、卡片标识符和CVV关联起来(最好在客户端进行,但如果适当PCI认证或测试期间可以在服务器端进行)。

可以使用LinkSecurityCode消息将CVV链接到可重复使用的卡片

use Academe\SagePay\Psr7\Request\LinkSecurityCode;

$securityCode = new LinkSecurityCode(
    $endpoint,
    $auth,
    $sessionKey,
    $cardIdentifier,
    '123' // The CVV obtained from the user.
);

// Send the message to create the link.
// The result will be a `Response\NoContent` if all is well.

$securityCodeResponse = ResponseFactory::fromHttpResponse(
    $client->sendRequest($securityCode->message())
);

// Should check for errors here:

if ($securityCodeResponse->isError()) {...}

要保存可重复使用的卡片,从成功的支付中获取PaymentMethod。注意:目前无法在不进行支付的情况下设置可重复使用的卡片。这是网关的限制。一些网关允许您创建零金额支付以进行认证和设置可重复使用的卡片,但在这里不行。

...

// Get the transaction response.

$transactionResponse = ResponseFactory::fromHttpResponse($response);

// Get the card. Only cards are supported as Payment Method at this time,
// though that is likely to change when PayPal support is rolled out.

$card = $transactionResponse->getPaymentMethod();

// If it is reusable, then it can be serialised for storage:

if ($card->isReusable()) {
    // Also can use getData() if you want the data without being serialised.
    $serialisedCard = json_encode($card);
}

// In a later payment, the card can be reused:

$card = ReusableCard::fromData(json_decode($serialisedCard));

// Or more explicitly:

$card = new ReusableCard($cardIdentifier);

// Or if being linked to a freshly-entered CVV:

$card = new ReusableCard($merchantSessionKey, $cardIdentifier);