Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Swish API-wrapper for PHP and Laravel

License

NotificationsYou must be signed in to change notification settings

olssonm/swish-php

Repository files navigation

Supported PHP-versionsLatest Version on PackagistBuild StatusSoftware License

A simple and easy to use wrapper for the Swish-API in PHP. Also includes providers and facades for quick setup with Laravel.

Prerequisites

This package supports PHP ^8.1. Tested against Laravel 10 & 11. PHP needs to be compiled with the cURL and SSL extensions (in an absolute majority of cases, they should be available by default).

Using an older version of PHP or Laravel? Check out v1 and v2 of this package.

Installation

composer require olssonm/swish-php

Setup

You will need to have access to your Swish-certificates to use this package in production. You can however use their testing/Merchant Swish Similator-environment without being a Swish-customer during development.

Read more about testing in their MSS-environment in theirofficial documentation. A quick rundown on using/creating Swish-certificatesis published here (in Swedish).

When creating the client, you will have to set which environment you are working with (otherwise it defaults to the production environment,https://cpc.getswish.net/swish-cpcapi/api/), you may use any of the following options:

Client::TEST_ENDPOINT// https://mss.cpc.getswish.net/swish-cpcapi/api/Client::PRODUCTION_ENDPOINT// https://cpc.getswish.net/swish-cpcapi/api/Client::SANDBOX_ENDPOINT// https://staging.getswish.pub.tds.tieto.com/swish-cpcapi/api/
useOlssonm\Swish\Certificate;useOlssonm\Swish\Client;$certificate =newCertificate('/path/to/client.pem','client-passphrase','/path/to/root.pem',// Can also be omitted for "true" to verify peer'/path/to/signing.key',// Path to signing certificate, only used for payouts'signing-passphrase'// Only used for payouts);$client =new Client($certificate,$endpoint = Client::TEST_ENDPOINT)

Important

The paths to the certificates should be absolute. You can userealpath -s YOUR_CERT.pem for this.

Laravel

With the Laravel service provider and facades you can work with the package more eloquently. Just require the package and publish the configuration:

php artisan vendor:publish --provider="Olssonm\Swish\Providers\SwishServiceProvider"

In/config/swish.php, you can then set your details accordingly:

return ['certificates' => ['client' =>env('SWISH_CLIENT_CERTIFICATE_PATH'),'password' =>env('SWISH_CLIENT_CERTIFICATE_PASSWORD'),'root' =>env('SWISH_ROOT_CERTIFICATE_PATH',true),'signing' =>env('SWISH_SIGNING_CERTIFICATE_PATH',null),'signing_password' =>env('SWISH_CLIENT_SIGNING_PASSWORD',null),    ],'endpoint' =>env('SWISH_URL', \Olssonm\Swish\Client::PRODUCTION_ENDPOINT),];

This may also be a good place to keep you payee-alias, callback-url and such, which you can then access withconfig('swish.payee_alias) etc.

Usage

A typical case for creating a Swish-payment.

useOlssonm\Swish\Certificate;useOlssonm\Swish\Client;useOlssonm\Swish\Payment;$certificate =newCertificate('/path/to/client.pem','client-passphrase');$client =newClient($certificate);// Create a new payment-object$payment =newPayment(['callbackUrl' =>'https://callback.url','payeePaymentReference' =>'XVY77','payeeAlias' =>'123xxxxx','payerAlias' =>'321xxxxx','amount' =>'100','currency' =>'SEK','message' =>'A purchase of my product',]);// Perform the request$response =$client->create($payment);// $response->id = '11A86BE70EA346E4B1C39C874173F088'// $response->location = 'https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests/11A86BE70EA346E4B1C39C874173F088'// $response->paymentRequestToken = 'a-unique-token'

With Laravel you can also use the facade and save a few lines of code (in this exampleOlssonm\Swish\Facades\Swish has been aliased toSwish)

useSwish;useOlssonm\Swish\Payment;$response = Swish::create(newPayment(['callbackUrl' =>'https://callback-url.com','payeePaymentReference' =>'XVY77','payeeAlias' =>'123xxxxx','payerAlias' =>'321xxxxx','amount' =>'100','currency' =>'SEK','message' =>'My product',]));

Payments and Refunds

Tip

Read more aboutpayments andrefunds in the official documentation

Always when using the client, use the Payment and Refund-classes even if only the ID is needed for the action, i.e:

$payment =$client->get(Payment(['id' =>'5D59DA1B1632424E874DDB219AD54597']));

Payouts

Tip

Read more aboutpayouts in the official documentation

Payouts need to be hashed using SHA512 and signed with a signing certificate before being sent to Swish – don't worry though, this package will handle most of this automatically. Just make sure that the path to your signing certificate is set:

$certificate =newCertificate('/path/to/client.pem','client-passphrase',true,'/path/to/signing.key','signing-passphrase');$client =newClient($certificate);$payout =$client->create(newPayout([]));

Additionally your certificate's (note: your signing certificate, not your client certificate) serial needs to be supplied. You can either use theCertificate-class to handle on the fly:

$certificate =newCertificate(/**/);$payout =new Payout(['signingCertificateSerialNumber' =>$certificate->getSerial()])

Or assign it yourself (see gist for extracting serial):

$payout =newPayout(['signingCertificateSerialNumber' =>'4512B3EBDA6E3CE6BFB14ABA6274A02C'])

Important

Note that Payouts usespayoutInstructionUUID instead of anID, you shouldset this yourself to keep track of it. If it's missing, it will be set automatically upon creation.

Regarding IDs/UUIDs

This package uses the v2 of the Swish API where a UUID is set by the merchant. This package handles all these aspects automatically as needed, you may however choose to manually set the ID/instructionUUID (either in Swish's own format, or a default v4-format):

$id ='EBB5C73503084E3C9AEA8A270AEBFE15';// or$id ='ebb5c735-0308-4e3c-9aea-8a270aebfe15';$payment =newPayment(['id' =>$id]);

When generating the UUIDs on the fly, the package usesRamsey/Uuid to generate RFC4122 (v4) UUIDs. Swish accepts V1, 3, 4 and 5 UUIDs if you chose to set your own UUIDs.

If an invalid UUID is used, aOlssonm\Swish\Exceptions\InvalidUuidException will be thrown.

Note

No matter if you set your own UUID och let the package handle the generation, the UUID will always be formatted for Swish automatically (dashes removed and in uppercase).

Available methods

This package handles the most common Swish-related tasks; retrieve, make and cancel payments. Retrieve and create payouts, aswell as refunds can be created and retrieved. All of them are performed viaOlssonm\Swish\Client;

$client->get(Payment$payment | Refund$refund | Payout$payout);$client->create(Payment$payment | Refund$refund | Payout$payout);$client->cancel(Payment$payment);

Exception-handling

When encountering a validation-error anOlssonm\Swish\Exceptions\ValidationException will be thrown. The Object will contain both the request, response as well as thegetErrorCode() andgetErrorMessage()-helpers.

try {$response =$client->create($payment);}catch (ValidationException$exception) {$errors =$exception->getErrors();foreach ($errorsas$error) {$error->errorCode;// AM03$error->errorMessage;// Invalid or missing Currency.    }}

For4xx-error a\Olssonm\Swish\Exceptions\ClientException will be thrown, and for5xx-errors\Olssonm\Swish\Exceptions\ServerException. Both of these implements GuzzlesBadResponseException which makes the request- and response-objects available if needed.

Callbacks

Swish recommends to not use thepayments-endpoint to get the status of a payment or refund (even if they themselves use it in some of their examples...), but instead use callbacks.

This package includes a simple helper to retrieve aPayment,Refund orPayout object from a callback that will contain all data from Swish:

useOlssonm\Swish\Callback;$paymentOrRefund = Callback::parse();// get_class($paymentOrRefund) = \Olssonm\Swish\Payment::class, \Olssonm\Swish\Refund::class, \Olssonm\Swish\Payout::class

The helper automatically retrieve the current HTTP-request (viafile_get_contents('php://input')). You may however inject your own data if needed (or if you for example has a Laravel request-object ready):

class SwishController {publicfunctionCallback(Request$request)    {$data = Callback::parse($request->getContent());if(get_class($data) == \Olssonm\Swish\Payment::class) {// Handle payment callback        }elseif(get_class($data) == \Olssonm\Swish\Refund::class) {// Handle refund callback        }elseif(get_class($data) == \Olssonm\Swish\Payout::class) {// Handle payout callback        }    }}

In a real world scenario you probably want to use separate callback-urls for your refunds, payouts and payments to prevent unnecessary parsing as the example above.

Caution

Please note that the callback from Swish is not encrypted or encoded in any way , instead you should make sure that the callback is coming from avalid IP-range.

License

The MIT License (MIT). Please see theLICENSE for more information.

© 2022-2024Marcus Olsson.


[8]ページ先頭

©2009-2025 Movatter.jp