Business-GoCardless

 view release on metacpan or  search on metacpan

lib/Business/GoCardless/Pro.pm  view on Meta::CPAN

package Business::GoCardless::Pro;

=head1 NAME

Business::GoCardless::Pro - Perl library for interacting with the GoCardless Pro v2 API
(https://gocardless.com)

=head1 DESCRIPTION

Module for interacting with the GoCardless Pro (v2) API.

B<You should refer to the official gocardless API documentation in conjunction>
B<with this perldoc>, as the official API documentation explains in more depth
some of the functionality including required / optional parameters for certain
methods. L<https://developer.gocardless.com>, specifically the docs for the
v2 GoCardless API at L<https://developer.gocardless.com/api-reference>.

This module supports the resources of the GoCardless API (see
L</RESOURCE METHODS>), as well as being a back compatibility wrapper to allow
migration from the v1 (Basic) API (see L</BACK COMPATIBILITY METHODS>). Note
that new integrations should use Billing Requests rather than Redirect Flows
(which the back compatibility methods use), see
L</Setting up a mandate with a Billing Request>.

Also note this class also currently inherits from L<Business::GoCardless>
so has all attributes and methods available on that class (some of which may not
make sense from the context of the Pro API).

=head1 SYNOPSIS

The following examples show instantiating the object and getting a resource
(Payment in this case) to manipulate. For more examples see the t/004_end_to_end_pro.t
script, which can be run against the gocardless sandbox (or even live) endpoint
when given the necessary ENV variables.

    my $GoCardless = Business::GoCardless::Pro->new(
        token           => $your_gocardless_token
        client_details  => {
            base_url       => $gocardless_url, # defaults to https://api.gocardless.com
            webhook_secret => $secret,
        },
    );

    # create URL for a one off payment
    my $new_bill_url = $GoCardless->new_bill_url(
        session_token        => 'foo',
        description          => "Test Payment",
        success_redirect_url => "http://example.com/rflow/confirm?jwt=$jwt",
    );

    # having sent the user to the $new_bill_url and them having complete it,
    # we need to confirm the resource using the details sent by gocardless to
    # the redirect_uri (https://developer.gocardless.com/api-reference/#redirect-flows-complete-a-redirect-flow)
    my $Payment = $GoCardless->confirm_resource(
        redirect_flow_id => $id,
        session_token    => 'foo', # the one passed to new_bill_url
        type             => 'payment', # bill / payment / pre_auth / subscription
        amount           => 0,
        currency         => 'GBP',
    );

    # get a specfic Payment
    $Payment = $GoCardless->payment( $id );

    # cancel the Payment
    $Payment->cancel;

    # too late? maybe we should refund instead (note: needs to be enabled on GoCardless end)
    $Payment->refund;

    # or maybe it failed?
    $Payment->retry if $Payment->failed;

    # get a list of Payment objects (filter optional: https://developer.gocardless.com/#filtering)
    my @payments = $GoCardless->payments( %filter );

    # on any resource object:
    my %data = $Payment->to_hash;
    my $json = $Payment->to_json;

=head1 PAGINATION

Any methods marked as B<pager> have a dual interface, when called in list context
they will return the first page of resource objects (50 by default, you can pass
a C<limit> filter of up to 500), when called in scalar context they will return a
L<Business::GoCardless::Paginator> object allowing you to iterate through all the
objects using the API's cursor based pagination:

    # get a list of L<Business::GoCardless::Payment> objects
    # (filter optional: https://developer.gocardless.com/#filtering)
    my @payments = $GoCardless->payments( %filter );

    # or using the Business::GoCardless::Paginator object:

lib/Business/GoCardless/Pro.pm  view on Meta::CPAN

        ...
    } else {
        # process webhook using new style code
        ...
    }

=cut

sub webhook {
    my ( $self,$data,$signature ) = @_;

    my $webhook = Business::GoCardless::Webhook::V2->new(
        client     => $self->client,
        json       => $data,
        # load ordering handled by setting _signature rather than signature
        # signature will be set in the json trigger
        _signature => $signature,
    );

    return $webhook->has_legacy_data
        ? $webhook->legacy_webhook
        : $webhook;
}

# payout methods are in the SUPER class
=head1 Payout Methods

See L<Business::GoCardless::Payout> for more information on Payout operations.

=head2 payouts (B<pager>)

Get a list of L<Business::GoCardless::Payout> objects.

    my @payouts = $GoCardless->payouts

=head2 payout

Get an individual payout, returns a L<Business::GoCardless::Payout> object:

    my $Payout = $GoCardless->payout( $id );

=cut

=head1 RESOURCE METHODS

Methods for the resources of the Pro API follow the same pattern. For example
for billing requests:

    # get a single resource, returns a Business::GoCardless::BillingRequest
    my $BillingRequest = $GoCardless->billing_request( $id );

    # get a list of resources (pager), %filters are optional
    my @billing_requests = $GoCardless->billing_requests( %filters );

    # create a resource, returns a Business::GoCardless::BillingRequest
    my $BillingRequest = $GoCardless->create_billing_request( %params );

Operations on a resource (cancel, update, etc) are methods on the resource
objects, see the documentation of each resource class for these. The parameters
and filters are as documented in the GoCardless API reference. Note that some of
the endpoints are restricted, for example to GoCardless Embed customers or to
those with custom payment pages enabled, see the GoCardless API reference for
details.

=head2 Setting up a mandate with a Billing Request

Billing Requests have replaced Redirect Flows, for example to set up a mandate
using the GoCardless hosted payment pages:

    my $BillingRequest = $GoCardless->create_billing_request(
        mandate_request => { scheme => 'bacs' },
    );

    my $Flow = $BillingRequest->create_flow(
        redirect_uri => 'https://example.com/mandate/complete',
        exit_uri     => 'https://example.com/mandate/exit',
    );

    # send the customer to $Flow->authorisation_url, once they have completed
    # the flow GoCardless will send you a billing_requests fulfilled webhook
    # (or you can check the billing request):

    $BillingRequest = $GoCardless->billing_request( $BillingRequest->id );

    if ( $BillingRequest->fulfilled ) {
        my $Mandate = $GoCardless->mandate( $BillingRequest->mandate_id );
        ...
    }

=head1 IDEMPOTENCY KEYS

All of the create methods take an optional C<idempotency_key> parameter, which
is sent as the C<Idempotency-Key> header rather than in the request body. If you
don't pass one a random key is generated for the request. See
L<Business::GoCardless::Client/IDEMPOTENCY KEYS> for more details.

    my $Payment = $GoCardless->create_payment(
        %params,
        idempotency_key => $your_unique_key,
    );

=head2 Mandates

See L<Business::GoCardless::Mandate>

    my @mandates = $GoCardless->mandates( %filters );
    my $Mandate = $GoCardless->create_mandate( %params );

=head2 Subscriptions

See L<Business::GoCardless::Subscription>

    my $Subscription = $GoCardless->create_subscription( %params );

=head2 Customers

See L<Business::GoCardless::Customer>

    my $Customer = $GoCardless->create_customer( %params );

=head2 Refunds

lib/Business/GoCardless/Pro.pm  view on Meta::CPAN


=head2 Scheme Identifiers

See L<Business::GoCardless::SchemeIdentifier>

    my $SchemeIdentifier = $GoCardless->scheme_identifier( $id );
    my @scheme_identifiers = $GoCardless->scheme_identifiers( %filters );
    my $SchemeIdentifier = $GoCardless->create_scheme_identifier( %params );

=head2 Exports

See L<Business::GoCardless::Export>

    my $Export = $GoCardless->export( $id );
    my @exports = $GoCardless->exports( %filters );

=head2 Outbound Payments

See L<Business::GoCardless::OutboundPayment>

    my $OutboundPayment = $GoCardless->outbound_payment( $id );
    my @outbound_payments = $GoCardless->outbound_payments( %filters );
    my $OutboundPayment = $GoCardless->create_outbound_payment( %params );

=head2 Outbound Payment Imports

See L<Business::GoCardless::OutboundPaymentImport>

    my $OutboundPaymentImport = $GoCardless->outbound_payment_import( $id );
    my @outbound_payment_imports = $GoCardless->outbound_payment_imports( %filters );
    my $OutboundPaymentImport = $GoCardless->create_outbound_payment_import( %params );

=head2 Outbound Payment Import Entries

See L<Business::GoCardless::OutboundPaymentImportEntry>

    my @outbound_payment_import_entries = $GoCardless->outbound_payment_import_entries( %filters );

=head2 Bank Account Holder Verifications

See L<Business::GoCardless::BankAccountHolderVerification>

    my $BankAccountHolderVerification = $GoCardless->bank_account_holder_verification( $id );
    my $BankAccountHolderVerification = $GoCardless->create_bank_account_holder_verification( %params );

=head2 Payment Accounts

See L<Business::GoCardless::PaymentAccount>

    my $PaymentAccount = $GoCardless->payment_account( $id );
    my @payment_accounts = $GoCardless->payment_accounts( %filters );

=head2 Payment Account Transactions

See L<Business::GoCardless::PaymentAccountTransaction>

    my $PaymentAccountTransaction = $GoCardless->payment_account_transaction( $id );

=cut

# the class for each of the resources (keyed on the API endpoint), and the
# path for the resource if it isn't the same as the endpoint
my %RESOURCE_CLASS = (
    payments       => 'Payment',
    redirect_flows => 'RedirectFlow',
    customers      => 'Customer',
    subscriptions  => 'Subscription',
    webhooks       => 'Webhook::V2',
    payouts        => 'Payout',
);

my %RESOURCE_PATH;

# most of the resources follow the same pattern in the API, so we generate the
# methods for them from the following. for each resource the operations are:
#
#   get    => $Pro->$singular( $id )
#   list   => $Pro->$endpoint( %filters ) (pager)
#   create => $Pro->create_$singular( %params )
#
my @RESOURCES = (
    # endpoint                         class                            singular                           operations
    [ mandates                          => 'Mandate'                       => mandate                          => qw/ list create / ],
    [ subscriptions                     => 'Subscription'                  => subscription                     => qw/ create / ],
    [ customers                         => 'Customer'                      => customer                         => qw/ create / ],
    [ refunds                           => 'Refund'                        => refund                           => qw/ get list create / ],
    [ events                            => 'Webhook::Event'                => event                            => qw/ get list / ],
    [ billing_requests                  => 'BillingRequest'                => billing_request                  => qw/ get list create / ],
    [ billing_request_flows             => 'BillingRequestFlow'            => billing_request_flow             => qw/ create / ],
    [ billing_request_templates         => 'BillingRequestTemplate'        => billing_request_template         => qw/ get list create / ],
    [ bank_authorisations               => 'BankAuthorisation'             => bank_authorisation               => qw/ get create / ],
    [ institutions                      => 'Institution'                   => institution                      => qw/ list / ],
    [ customer_bank_accounts            => 'CustomerBankAccount'           => customer_bank_account            => qw/ get list create / ],
    [ bank_details_lookups              => 'BankDetailsLookup'             => bank_details_lookup              => qw/ create / ],
    [ creditors                         => 'Creditor'                      => creditor                         => qw/ get list create / ],
    [ creditor_bank_accounts            => 'CreditorBankAccount'           => creditor_bank_account            => qw/ get list create / ],
    [ verification_details              => 'VerificationDetail'            => verification_detail              => qw/ list create / ],
    [ instalment_schedules              => 'InstalmentSchedule'            => instalment_schedule              => qw/ get list / ],
    [ tax_rates                         => 'TaxRate'                       => tax_rate                         => qw/ get list / ],
    [ mandate_imports                   => 'MandateImport'                 => mandate_import                   => qw/ get create / ],
    [ mandate_import_entries            => 'MandateImportEntry'            => mandate_import_entry             => qw/ list create / ],
    [ mandate_pdfs                      => 'MandatePdf'                    => mandate_pdf                      => qw// ],
    [ transferred_mandates              => 'TransferredMandate'            => transferred_mandate              => qw/ get / ],
    [ payout_items                      => 'PayoutItem'                    => payout_item                      => qw/ list / ],
    [ balances                          => 'Balance'                       => balance                          => qw/ list / ],
    [ negative_balance_limits           => 'NegativeBalanceLimit'          => negative_balance_limit           => qw/ list / ],
    [ currency_exchange_rates           => 'CurrencyExchangeRate'          => currency_exchange_rate           => qw/ list / ],
    [ blocks                            => 'Block'                         => block                            => qw/ get list create / ],
    [ logos                             => 'Logo'                          => logo                             => qw/ create / ],
    [ payer_themes                      => 'PayerTheme'                    => payer_theme                      => qw/ create / ],
    [ scheme_identifiers                => 'SchemeIdentifier'              => scheme_identifier                => qw/ get list create / ],
    [ exports                           => 'Export'                        => export                           => qw/ get list / ],
    [ outbound_payments                 => 'OutboundPayment'               => outbound_payment                 => qw/ get list create / ],
    [ outbound_payment_imports          => 'OutboundPaymentImport'         => outbound_payment_import          => qw/ get list create / ],
    [ outbound_payment_import_entries   => 'OutboundPaymentImportEntry'    => outbound_payment_import_entry    => qw/ list / ],
    [ bank_account_holder_verifications => 'BankAccountHolderVerification' => bank_account_holder_verification => qw/ get create / ],
    [ payment_accounts                  => 'PaymentAccount'                => payment_account                  => qw/ get list / ],
    [ payment_account_transactions      => 'PaymentAccountTransaction'     => payment_account_transaction      => qw/ get / ],
    [ bank_account_details              => 'BankAccountDetail'             => bank_account_detail              => qw// ],
    [ customer_notifications            => 'CustomerNotification'          => customer_notification            => qw// ],
);

$RESOURCE_PATH{logos}        = '/branding/logos';
$RESOURCE_PATH{payer_themes} = '/branding/payer_themes';

foreach my $resource ( @RESOURCES ) {

    my ( $endpoint,$class,$singular,@operations ) = @{ $resource };

    $RESOURCE_CLASS{$endpoint} = $class;

    my %methods = (
        get    => [ $singular => sub {
            my ( $self,$id ) = @_;
            return $self->_get( $endpoint,$id );
        } ],
        list   => [ $endpoint => sub {
            my ( $self,%filters ) = @_;
            return $self->_list( $endpoint,\%filters );
        } ],
        create => [ "create_$singular" => sub {
            my ( $self,%params ) = @_;
            return $self->_create( $endpoint,\%params );
        } ],
    );

    foreach my $operation ( @operations ) {

        my ( $method,$code ) = @{ $methods{$operation} };

        # make sure we don't clobber any explicitly defined methods
        confess( "$method is already defined" )
            if __PACKAGE__->can( $method );

        no strict 'refs';
        *{ __PACKAGE__ . "::$method" } = $code;
    }
}

# load all of the resource classes
eval "require Business::GoCardless::$_; 1" || die $@
    for sort values( %RESOURCE_CLASS );

sub _new_resource {
    my ( $self,$endpoint,$data ) = @_;

    my $class = "Business::GoCardless::$RESOURCE_CLASS{$endpoint}";

    return $endpoint eq 'webhooks'
        ? $class->_new_from_api( $self->client,$data )
        : $class->new( client => $self->client,%{ $data // {} } );
}

sub _get {
    my ( $self,$endpoint,$id,$headers ) = @_;

    my $path = $RESOURCE_PATH{$endpoint} // "/$endpoint";
    my $data = $self->client->api_get( "$path/$id",undef,$headers );

    return $self->_new_resource( $endpoint,$data->{$endpoint} );
}

sub _create {
    my ( $self,$endpoint,$params,%opts ) = @_;

    my $data = $self->_create_request( $endpoint,$params,%opts );
    return $self->_new_resource( $endpoint,$data->{$endpoint} );
}

sub _create_request {
    my ( $self,$endpoint,$params,%opts ) = @_;

    my %params  = %{ $params // {} };
    my %headers = %{ $opts{headers} // {} };

    # not part of the request body, see IDEMPOTENCY KEYS
    my $key = delete( $params{idempotency_key} );
    $headers{'Idempotency-Key'} = $key if defined $key;

    my $path = $opts{path} // $RESOURCE_PATH{$endpoint} // "/$endpoint";

    return $self->client->api_post(
        $path,{ $endpoint => \%params },\%headers
    );
}

sub _list {
    my ( $self,$endpoint,$filters,$path ) = @_;

    $filters //= {};
    $path    //= $RESOURCE_PATH{$endpoint} // "/$endpoint";

    my $class = "Business::GoCardless::$RESOURCE_CLASS{$endpoint}";

    my $uri_for = sub {
        my ( %cursor ) = @_;

        # cursor params replace any passed in the original filters
        my %params = ( %{ $filters },%cursor );
        delete( @params{ grep { ! defined $params{$_} } keys %params } );

        return keys( %params )
            ? "$path?" . $self->client->normalize_params( \%params )
            : $path;
    };

    # the v2 API uses cursor based pagination, so we construct the links for
    # next / previous / first from the meta data in each page of results
    my $page_loader = sub {
        my ( $uri ) = @_;

        my ( $data ) = $self->client->api_get( $uri );
        my $cursors  = $data->{meta}{cursors} // {};

        my @objects = map { $self->_new_resource( $endpoint,$_ ) }
            @{ $data->{$endpoint} // [] };

        my $links = {
            first => $uri_for->( before => undef,after => undef ),
            ( $cursors->{after}  ? ( next     => $uri_for->( after  => $cursors->{after},before => undef ) ) : () ),
            ( $cursors->{before} ? ( previous => $uri_for->( before => $cursors->{before},after => undef ) ) : () ),
        };

        return ( \@objects,$links,$data->{meta} // {} );
    };

    my ( $objects,$links,$info ) = $page_loader->( $uri_for->() );

    return wantarray ? ( @{ $objects } ) : Business::GoCardless::Paginator->new(
        class       => $class,
        client      => $self->client,
        links       => $links,
        info        => $info,
        objects     => $objects,
        page_loader => $page_loader,
    );
}

=head1 OTHER RESOURCE METHODS

The following methods are for API endpoints that don't follow the standard
pattern of the L</RESOURCE METHODS>.

=head2 create_billing_request_with_actions

Create a billing request and perform actions on it in a single request (this
is restricted to custom payment pages, and doesn't support ACH/PAD). Returns a
L<Business::GoCardless::BillingRequest> object, and in list context also the
L<Business::GoCardless::BankAuthorisation> if one was created:

    my ( $BillingRequest,$BankAuthorisation )
        = $GoCardless->create_billing_request_with_actions(
            payment_request => { amount => 1000,currency => 'GBP' },
            actions         => {
                collect_customer_details  => { ... },
                create_bank_authorisation => JSON::true,
            },
        );

=head2 create_instalment_schedule_with_dates

Create an L<Business::GoCardless::InstalmentSchedule> with the dates of each
instalment:

    my $Schedule = $GoCardless->create_instalment_schedule_with_dates(
        name         => 'Bike',
        currency     => 'GBP',
        total_amount => 3000,
        instalments  => [
            { charge_date => '2026-11-01',amount => 1500 },
            { charge_date => '2026-12-01',amount => 1500 },
        ],
        links => { mandate => $mandate_id },
    );

=head2 create_instalment_schedule_with_schedule

Create an L<Business::GoCardless::InstalmentSchedule> with a schedule from
which the instalment dates are calculated:

    my $Schedule = $GoCardless->create_instalment_schedule_with_schedule(
        name         => 'Bike',
        currency     => 'GBP',
        total_amount => 3000,
        instalments  => {
            start_date    => '2026-11-01',
            interval      => 1,
            interval_unit => 'monthly',
            amounts       => [ 1500,1500 ],
        },
        links => { mandate => $mandate_id },
    );

Instalment schedules are created asynchronously, so the status will be
C<pending> until it becomes C<active> (or C<creation_failed>).

=head2 create_mandate_pdf

Create a L<Business::GoCardless::MandatePdf>, the PDF can be in a language
other than English by passing C<accept_language>:



( run in 1.302 second using v1.01-cache-2.11-cpan-99fa8243a42 )