Merge branch 'PayDriver_cio' into WebGUI8

This commit is contained in:
Colin Kuskie 2010-10-08 14:22:24 -07:00
commit 3af80377e6
15 changed files with 709 additions and 1238 deletions

View file

@ -0,0 +1,65 @@
package WebGUI::Definition::Meta::Shop;
=head1 LEGAL
-------------------------------------------------------------------
WebGUI is Copyright 2001-2009 Plain Black Corporation.
-------------------------------------------------------------------
Please read the legal notices (docs/legal.txt) and the license
(docs/license.txt) that came with this distribution before using
this software.
-------------------------------------------------------------------
http://www.plainblack.com info@plainblack.com
-------------------------------------------------------------------
=cut
use 5.010;
use Moose::Role;
use namespace::autoclean;
use WebGUI::Definition::Meta::Property;
use WebGUI::Definition::Meta::Property::Asset;
no warnings qw(uninitialized);
with 'WebGUI::Definition::Meta::Class';
our $VERSION = '0.0.1';
=head1 NAME
Package WebGUI::Definition::Meta::Shop
=head1 DESCRIPTION
Extends 'WebGUI::Definition::Meta::Class' to provide attributes specific to Assets.
=head1 METHODS
These methods are available from this class:
=cut
#-------------------------------------------------------------------
has [ qw{tableName pluginName} ] => (
is => 'rw',
);
#-------------------------------------------------------------------
=head2 tableName ( )
The table that this plugin stores its properties in.
=cut
#-------------------------------------------------------------------
=head2 pluginName ( )
An array reference containing two items. The first is the i18n key for the plugin's name.
The second is the i18n namespace to find the plugin's name.
=cut
1;

View file

@ -0,0 +1,118 @@
package WebGUI::Definition::Shop;
=head1 LEGAL
-------------------------------------------------------------------
WebGUI is Copyright 2001-2009 Plain Black Corporation.
-------------------------------------------------------------------
Please read the legal notices (docs/legal.txt) and the license
(docs/license.txt) that came with this distribution before using
this software.
-------------------------------------------------------------------
http://www.plainblack.com info@plainblack.com
-------------------------------------------------------------------
=cut
use 5.010;
use feature ();
use Moose::Exporter;
use WebGUI::Definition ();
use WebGUI::Definition::Meta::Shop;
use Moose::Util;
use Moose::Util::MetaRole;
use namespace::autoclean;
no warnings qw(uninitialized);
our $VERSION = '0.0.1';
=head1 NAME
Package WebGUI::Definition::Shop
=head1 DESCRIPTION
Moose-based meta class for all Shop definitions in WebGUI. Shop plugins have a name, pluginName, and
the table where their data is stored as JSON blobs, tableName.
=head1 SYNOPSIS
A definition contains all the information needed to build an object.
Information required to build forms are added as optional roles and
sub metaclasses. Database persistance is handled similarly.
=head1 METHODS
These methods are available from this class:
=cut
my ($import, $unimport, $init_meta) = Moose::Exporter->build_import_methods(
install => [ 'unimport' ],
also => 'WebGUI::Definition',
);
#-------------------------------------------------------------------
=head2 import ( )
A custom import method is provided so that uninitialized properties do not
generate warnings.
=cut
sub import {
my $class = shift;
my $caller = caller;
$class->$import({ into_level => 1 });
warnings->unimport('uninitialized');
feature->import(':5.10');
namespace::autoclean->import( -cleanee => $caller );
return 1;
}
#-------------------------------------------------------------------
=head2 init_meta ( )
A custom init_meta, so that if inported into a class, it applies the roles
to the class, and applies the meta-role to the meta-class.
But, if it is applied to a Role, then only the meta-role is applied, since we want
the final application to be in the end user of the Role.
This permits using this to compose Roles with their own database tables.
=cut
sub init_meta {
my $class = shift;
my %args = @_;
my $for_class = $args{for_class};
if ($for_class->meta->isa('Moose::Meta::Class')) {
Moose::Util::MetaRole::apply_metaroles(
for => $for_class,
class_metaroles => {
class => ['WebGUI::Definition::Meta::Shop'],
},
);
Moose::Util::apply_all_roles(
$for_class,
'WebGUI::Definition::Role::Object',
);
}
else {
Moose::Util::MetaRole::apply_metaroles(
for => $for_class,
role_metaroles => {
role => ['WebGUI::Definition::Meta'],
},
);
}
return $for_class->meta;
}
1;

View file

@ -96,7 +96,8 @@ sub addPaymentGateway {
unless exists $self->getDrivers->{$requestedClass}; unless exists $self->getDrivers->{$requestedClass};
WebGUI::Error::InvalidParam->throw(error => q{You must pass a hashref of options to create a new PayDriver object}) WebGUI::Error::InvalidParam->throw(error => q{You must pass a hashref of options to create a new PayDriver object})
unless defined($options) and ref $options eq 'HASH' and scalar keys %{ $options }; unless defined($options) and ref $options eq 'HASH' and scalar keys %{ $options };
my $driver = eval { WebGUI::Pluggable::instanciate($requestedClass, 'create', [ $self->session, $options ]) }; my $driver = eval { WebGUI::Pluggable::instanciate($requestedClass, 'new', [ $self->session, $options ]) };
$driver->write;
return $driver; return $driver;
} }

View file

@ -16,7 +16,6 @@ package WebGUI::Shop::PayDriver;
use strict; use strict;
use Class::InsideOut qw{ :std };
use Carp qw(croak); use Carp qw(croak);
use Tie::IxHash; use Tie::IxHash;
use WebGUI::Exception::Shop; use WebGUI::Exception::Shop;
@ -30,6 +29,9 @@ use JSON;
use Clone qw/clone/; use Clone qw/clone/;
use Scalar::Util qw/blessed/; use Scalar::Util qw/blessed/;
use Moose;
use WebGUI::Definition::Shop;
=head1 NAME =head1 NAME
Package WebGUI::Shop::PayDriver Package WebGUI::Shop::PayDriver
@ -50,35 +52,78 @@ These subroutines are available from this package:
=cut =cut
readonly session => my %session; define tableName => 'paymentGateway';
readonly className => my %className; define pluginName => ['Payment Driver', 'PayDriver'];
readonly paymentGatewayId => my %paymentGatewayId;
readonly options => my %options;
#------------------------------------------------------------------- property label => (
fieldType => 'text',
label => ['label', 'PayDriver'],
hoverHelp => ['label help', 'PayDriver'],
default => "Credit Card",
);
around label => sub {
my $orig = shift;
my $self = shift;
if (@_ > 0) {
my $label = shift;
$label = $self->getName($self->session) if $label eq '' || lc($label) eq 'untitled';
unshift @_, $label;
}
$self->$orig(@_);
};
property enabled => (
fieldType => 'yesNo',
label => ['enabled', 'PayDriver'],
hoverHelp => ['enabled help', 'PayDriver'],
default => 1,
);
property groupToUse => (
fieldType => 'group',
label => ['who can use', 'PayDriver'],
hoverHelp => ['who can use help', 'PayDriver'],
default => 7,
);
=head2 _buildObj ( ) has [ qw/session paymentGatewayId/ ] => (
is => 'ro',
required => 1,
);
Private method used to build objects, shared by new and create. around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
if(ref $_[0] eq 'HASH') {
##Standard Moose invocation for creating a new object
return $class->$orig(@_);
}
my $session = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable})
unless blessed $session && $session->isa('WebGUI::Session');
if (ref $_[0] eq 'HASH') {
##Create an object from a hashref of options
my $options = shift;
$options->{session} = $session;
$options->{paymentGatewayId} = $session->id->generate;
return $class->$orig($options);
}
##Must be a paymentGatewayId, look it up in the database
my $paymentGatewayId = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a paymentGatewayId})
unless defined $paymentGatewayId;
my $properties = $session->db->quickHashRef('select * from paymentGateway where paymentGatewayId=?', [
$paymentGatewayId,
]);
WebGUI::Error::ObjectNotFound->throw(error => q{paymentGatewayId not found in db}, id => $paymentGatewayId)
unless scalar keys %{ $properties };
=cut croak "Somehow, the options property of this object, $paymentGatewayId, got broken in the db"
unless exists $properties->{options} and $properties->{options};
sub _buildObj {
my ($class, $session, $requestedClass, $paymentGatewayId, $options) = @_;
my $self = {};
bless $self, $requestedClass;
register $self;
my $id = id $self;
$session{ $id } = $session;
$options{ $id } = $options;
$className{ $id } = $requestedClass;
$paymentGatewayId{ $id } = $paymentGatewayId;
return $self;
}
my $options = from_json($properties->{options});
$options->{session} = $session;
$options->{paymentGatewayId} = $paymentGatewayId;
return $class->$orig($options);
};
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -151,7 +196,7 @@ A user object that will be used directly.
sub canUse { sub canUse {
my $self = shift; my $self = shift;
return 0 unless $self->get('enabled'); return 0 unless $self->enabled;
my $user = shift; my $user = shift;
my $userObject; my $userObject;
if (!defined $user or ref($user) ne 'HASH') { if (!defined $user or ref($user) ne 'HASH') {
@ -168,7 +213,7 @@ sub canUse {
WebGUI::Error::InvalidParam->throw(error => q{Must provide user information}) WebGUI::Error::InvalidParam->throw(error => q{Must provide user information})
} }
} }
return $userObject->isInGroup($self->get('groupToUse')); return $userObject->isInGroup($self->groupToUse);
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -180,99 +225,8 @@ to do calculations.
=cut =cut
#------------------------------------------------------------------- sub className {
return ref $_[0];
=head2 create ( $session, $options )
Constructor for new WebGUI::Shop::PayDriver objects. Returns a WebGUI::Shop::PayDriver object.
To access driver objects that have already been configured, use C<new>.
=head3 $session
A WebGUI::Session object.
=head4 $options
A list of properties to assign to this PayDriver. See C<definition> for details.
=cut
sub create {
my $class = shift;
my $session = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable})
unless ref $session eq 'WebGUI::Session';
my $options = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a hashref of options})
unless ref $options eq 'HASH' and scalar keys %{ $options };
WebGUI::Error::InvalidParam->throw(error => q{Must provide a human readable label in the hashref of options})
unless exists $options->{label} && $options->{label};
# Generate a unique id for this payment
my $paymentGatewayId = $session->id->generate;
# Build object
my $self = WebGUI::Shop::PayDriver->_buildObj($session, $class, $paymentGatewayId, $options);
# and persist this instance in the db
$session->db->write('insert into paymentGateway (paymentGatewayId, className) VALUES (?,?)', [
$paymentGatewayId,
$class,
]);
# Set the options via the update method because update() will automatically serialize the options hash
$self->update($options);
return $self;
}
#-------------------------------------------------------------------
=head2 definition ( $session )
This subroutine returns an arrayref of hashrefs, used to validate data put into
the object by the user, and to automatically generate the edit form to show
the user.
=cut
sub definition {
my $class = shift;
my $session = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable})
unless ref $session eq 'WebGUI::Session';
my $definition = shift || [];
my $i18n = WebGUI::International->new($session, 'PayDriver');
tie my %fields, 'Tie::IxHash';
%fields = (
label => {
fieldType => 'text',
label => $i18n->get('label'),
hoverHelp => $i18n->get('label help'),
defaultValue => "Credit Card",
},
enabled => {
fieldType => 'yesNo',
label => $i18n->get('enabled'),
hoverHelp => $i18n->get('enabled help'),
defaultValue => 1,
},
groupToUse => {
fieldType => 'group',
label => $i18n->get('who can use'),
hoverHelp => $i18n->get('who can use help'),
defaultValue => 7,
},
);
my %properties = (
name => 'Payment Driver',
properties => \%fields,
);
push @{ $definition }, \%properties;
return $definition;
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -314,34 +268,6 @@ sub displayPaymentError {
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 get ( [ $param ] )
This is an enhanced accessor for the options property. By default,
it returns all the options as a hashref. If the name of a key
in the hash is passed, it will only return that value from the
options hash.
=head3 $param
An optional parameter. If it matches the key of a hash, it will
return the value from the options hash.
=cut
sub get {
my $self = shift;
my $param = shift;
my $options = $self->options;
if (defined $param) {
return $options->{ $param };
}
else {
return { %{ $options } };
}
}
#-------------------------------------------------------------------
=head2 getAddress ( addressId ) =head2 getAddress ( addressId )
Returns an instantiated WebGUI::Shop::Address object for the passed address id. Returns an instantiated WebGUI::Shop::Address object for the passed address id.
@ -437,7 +363,6 @@ Returns the configuration form for the options of this plugin.
sub getEditForm { sub getEditForm {
my $self = shift; my $self = shift;
my $definition = $self->definition($self->session);
my $form = WebGUI::HTMLForm->new($self->session); my $form = WebGUI::HTMLForm->new($self->session);
$form->submit; $form->submit;
@ -446,6 +371,15 @@ sub getEditForm {
name => 'className', name => 'className',
value => $self->className, value => $self->className,
); );
tie my %form_options, 'Tie::IxHash';
foreach my $property_name ($self->getProperties) {
my $property = $self->meta->find_attribute_by_name($property_name);
$form_options{$property_name} = {
value => $self->$property_name,
%{ $self->getFormProperties($property_name)},
};
}
my $definition = [ { properties => \%form_options }, ];
$form->dynamicForm($definition, 'properties', $self); $form->dynamicForm($definition, 'properties', $self);
return $form; return $form;
@ -470,7 +404,7 @@ sub getId {
=head2 getName ( ) =head2 getName ( )
Return a human readable name for this driver. Never overridden in the Return a human readable name for this driver. Never overridden in the
subclass, instead specified in definition with the name "name". subclass, instead specified via WebGUI::Definition::Shop with the name "pluginName".
This is a class method. This is a class method.
@ -482,9 +416,7 @@ sub getName {
WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable}) WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable})
unless ref $session eq 'WebGUI::Session'; unless ref $session eq 'WebGUI::Session';
my $definition = $class->definition($session); return WebGUI::International->new($session)->get(@{ $class->meta->pluginName });
return $definition->[0]->{name};
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -509,42 +441,6 @@ that object.
=cut =cut
sub new {
my $class = shift;
my $session = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable})
unless ref $session eq 'WebGUI::Session';
my $paymentGatewayId = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a paymentGatewayId})
unless defined $paymentGatewayId;
# Fetch the instance data from the db
my $properties = $session->db->quickHashRef('select * from paymentGateway where paymentGatewayId=?', [
$paymentGatewayId,
]);
WebGUI::Error::ObjectNotFound->throw(error => q{paymentGatewayId not found in db}, id => $paymentGatewayId)
unless scalar keys %{ $properties };
croak "Somehow, the options property of this object, $paymentGatewayId, got broken in the db"
unless exists $properties->{options} and $properties->{options};
my $options = from_json($properties->{options});
my $self = WebGUI::Shop::PayDriver->_buildObj($session, $class, $paymentGatewayId, $options);
return $self;
}
#-------------------------------------------------------------------
=head2 options ( )
Accessor for the driver properties. This returns a hashref
any driver specific properties. To set the properties, use
the C<update> method.
=cut
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 processPayment () =head2 processPayment ()
@ -560,9 +456,9 @@ sub processPayment {
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 processPropertiesFromFormPost ( ) =head2 processTemplate ( )
Updates pay driver with data from Form. Common code for processing a template and doing exception handling.
=cut =cut
@ -597,20 +493,18 @@ Updates ship driver with data from Form.
sub processPropertiesFromFormPost { sub processPropertiesFromFormPost {
my $self = shift; my $self = shift;
my %properties;
my $fullDefinition = $self->definition($self->session);
foreach my $definition (@{$fullDefinition}) { my $form = $self->session->form;
foreach my $property (keys %{$definition->{properties}}) { foreach my $property_name ($self->getProperties) {
$properties{$property} = $self->session->form->process( my $property = $self->meta->find_attribute_by_name($property_name);
$property, my $value = $form->process(
$definition->{properties}{$property}{fieldType}, $property_name,
$definition->{properties}{$property}{defaultValue} $property->form->{fieldType},
); $self->$property_name,
} );
$self->$property_name($value);
} }
$properties{label} = $fullDefinition->[0]{name} if ($properties{label} eq "" || lc($properties{label}) eq "untitled"); $self->write;
$self->update(\%properties);
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -680,31 +574,29 @@ Accessor for the session object. Returns the session object.
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 update ( $options ) =head2 write ( $options )
Setter for user configurable options in the payment objects. Setter for user configurable options in the payment objects.
=head4 $options =head4 $options
A list of properties to assign to this PayDriver. See C<definition> for details. The options are A list of properties to assign to this PayDriver. See C<new> for details. The options are
flattened into JSON and stored in the database as text. There is no content checking performed. flattened into JSON and stored in the database as text. There is no content checking performed.
=cut =cut
sub update { sub write {
my $self = shift; my $self = shift;
my $properties = shift;
WebGUI::Error::InvalidParam->throw(error => 'update was not sent a hashref of options to store in the database')
unless ref $properties eq 'HASH' and scalar keys %{ $properties };
my $properties = $self->get();
delete $properties->{session};
delete $properties->{paymentGatewayId};
my $jsonOptions = to_json($properties); my $jsonOptions = to_json($properties);
$self->session->db->write('update paymentGateway set options=? where paymentGatewayId=?', [ $self->session->db->setRow($self->tableName, 'paymentGatewayId', {
$jsonOptions, paymentGatewayId => $self->paymentGatewayId,
$self->paymentGatewayId className => $self->className,
]); options => $jsonOptions,
my $storedProperties = clone $properties; });
$options{ id $self } = $storedProperties;
return; return;
} }
@ -738,7 +630,7 @@ sub www_getCredentials {
}; };
$self->appendCartVariables($var); $self->appendCartVariables($var);
my $output = $self->processTemplate($self->get("summaryTemplateId"), $var); my $output = $self->processTemplate($self->summaryTemplateId, $var);
return $session->style->userStyle($output); return $session->style->userStyle($output);
} }
@ -785,6 +677,12 @@ sub www_editSave {
=head2 CHANGES ( ) =head2 CHANGES ( )
=head3 8.0.0
In 8.0.0, the base PayDriver class was modified so that it uses WebGUI::Definition::Shop as its base,
rather than Class::InsideOut. All PayDriver subclasses from 7.x will need to do the same.
The current PayDriver subclasses, like Cash and ITransact, can be used as examples on what to do.
=head3 7.9.4 =head3 7.9.4
In 7.9.4, the base PayDriver class was changed to accomodate the new Cart. The Cart is now in In 7.9.4, the base PayDriver class was changed to accomodate the new Cart. The Cart is now in

View file

@ -20,7 +20,18 @@ use WebGUI::Shop::PayDriver;
use WebGUI::Exception; use WebGUI::Exception;
use Tie::IxHash; use Tie::IxHash;
use base qw/WebGUI::Shop::PayDriver/; use Moose;
use WebGUI::Definition::Shop;
extends 'WebGUI::Shop::PayDriver';
define pluginName => [qw/label PayDriver_Cash/];
property summaryTemplateId => (
fieldType => 'template',
label => ['summary template', 'PayDriver_Cash'],
hoverHelp => ['summary template help', 'PayDriver_Cash'],
namespace => 'Shop/Credentials',
default => '30h5rHxzE_Q0CyI3Gg7EJw',
);
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -42,40 +53,6 @@ sub canCheckoutCart {
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 definition ( session, definition )
See WebGUI::Shop::PayDriver->definition.
=cut
sub definition {
my $class = shift;
my $session = shift;
my $definition = shift;
my $i18n = WebGUI::International->new($session, 'PayDriver_Cash');
tie my %fields, 'Tie::IxHash';
%fields = (
summaryTemplateId => {
fieldType => 'template',
label => $i18n->get('summary template'),
hoverHelp => $i18n->get('summary template help'),
namespace => 'Shop/Credentials',
defaultValue => '30h5rHxzE_Q0CyI3Gg7EJw',
},
);
push @{ $definition }, {
name => $i18n->get('label'),
properties => \%fields,
};
return $class->SUPER::definition($session, $definition);
}
#-------------------------------------------------------------------
=head2 getButton ( ) =head2 getButton ( )
Return a form with button to finalize checkout from the Shop. Return a form with button to finalize checkout from the Shop.

View file

@ -21,7 +21,37 @@ use Tie::IxHash;
use LWP::UserAgent; use LWP::UserAgent;
use HTTP::Request; use HTTP::Request;
use base qw/WebGUI::Shop::PayDriver/; use Moose;
use WebGUI::Definition::Shop;
extends 'WebGUI::Shop::PayDriver';
define pluginName => [qw/Itransact PayDriver_ITransact/];
property vendorId => (
fieldType => 'text',
label => ['vendorId', 'PayDriver_ITransact'],
hoverHelp => ['vendorId help', 'PayDriver_ITransact'],
);
property password => (
fieldType => 'password',
label => ['password', 'PayDriver_ITransact'],
hoverHelp => ['password help', 'PayDriver_ITransact'],
);
property useCVV2 => (
fieldType => 'yesNo',
label => ['use cvv2', 'PayDriver_ITransact'],
hoverHelp => ['use cvv2 help', 'PayDriver_ITransact'],
);
property credentialsTemplateId => (
fieldType => 'template',
label => ['credentials template', 'PayDriver_ITransact'],
hoverHelp => ['credentials template help', 'PayDriver_ITransact'],
namespace => 'Shop/Credentials',
default => 'itransact_credentials1',
);
property emailMessage => (
fieldType => 'textarea',
label => ['emailMessage', 'PayDriver_ITransact'],
hoverHelp => ['emailMessage help', 'PayDriver_ITransact'],
);
#------------------------------------------------------------------- #-------------------------------------------------------------------
sub _generateCancelRecurXml { sub _generateCancelRecurXml {
@ -30,8 +60,8 @@ sub _generateCancelRecurXml {
# Construct xml # Construct xml
my $vendorIdentification; my $vendorIdentification;
$vendorIdentification->{ VendorId } = $self->get('vendorId'); $vendorIdentification->{ VendorId } = $self->vendorId;
$vendorIdentification->{ VendorPassword } = $self->get('password'); $vendorIdentification->{ VendorPassword } = $self->password;
$vendorIdentification->{ HomePage } = $self->session->setting->get("companyURL"); $vendorIdentification->{ HomePage } = $self->session->setting->get("companyURL");
my $recurUpdate; my $recurUpdate;
@ -82,7 +112,7 @@ sub _generatePaymentRequestXML {
$cardInfo->{ CCNum } = $cardData->{ acct }; $cardInfo->{ CCNum } = $cardData->{ acct };
$cardInfo->{ CCMo } = $cardData->{ expMonth }; $cardInfo->{ CCMo } = $cardData->{ expMonth };
$cardInfo->{ CCYr } = $cardData->{ expYear }; $cardInfo->{ CCYr } = $cardData->{ expYear };
$cardInfo->{ CVV2Number } = $cardData->{ cvv2 } if $self->get('useCVV2'); $cardInfo->{ CVV2Number } = $cardData->{ cvv2 } if $self->useCVV2;
my $customerData; my $customerData;
$customerData->{ Email } = $paymentAddress->{ email }; $customerData->{ Email } = $paymentAddress->{ email };
@ -92,7 +122,7 @@ sub _generatePaymentRequestXML {
# --- Transaction data part --- # --- Transaction data part ---
my $emailText; my $emailText;
$emailText->{ EmailTextItem } = [ $emailText->{ EmailTextItem } = [
$self->get('emailMessage'), $self->emailMessage,
'ID: '. $transaction->getId, 'ID: '. $transaction->getId,
]; ];
@ -155,8 +185,8 @@ sub _generatePaymentRequestXML {
$vendorData->{ Element }->{ Value } = $transaction->getId; $vendorData->{ Element }->{ Value } = $transaction->getId;
my $transactionData; my $transactionData;
$transactionData->{ VendorId } = $self->get('vendorId'); $transactionData->{ VendorId } = $self->vendorId;
$transactionData->{ VendorPassword } = $self->get('password'); $transactionData->{ VendorPassword } = $self->password;
$transactionData->{ VendorData } = $vendorData; $transactionData->{ VendorData } = $vendorData;
$transactionData->{ HomePage } = $self->session->setting->get("companyURL"); $transactionData->{ HomePage } = $self->session->setting->get("companyURL");
$transactionData->{ RecurringData } = $recurringData if $recurringData; $transactionData->{ RecurringData } = $recurringData if $recurringData;
@ -320,8 +350,8 @@ sub checkRecurringTransaction {
my $xmlStructure = { my $xmlStructure = {
GatewayInterface => { GatewayInterface => {
VendorIdentification => { VendorIdentification => {
VendorId => $self->get('vendorId'), VendorId => $self->vendorId,
VendorPassword => $self->get('password'), VendorPassword => $self->password,
HomePage => , HomePage => ,
}, },
RecurDetails => { RecurDetails => {
@ -377,56 +407,6 @@ sub checkRecurringTransaction {
} }
} }
#-------------------------------------------------------------------
sub definition {
my $class = shift;
my $session = shift;
WebGUI::Error::InvalidParam->throw(error => q{Must provide a session variable})
unless ref $session eq 'WebGUI::Session';
my $definition = shift;
my $i18n = WebGUI::International->new($session, 'PayDriver_ITransact');
tie my %fields, 'Tie::IxHash';
%fields = (
vendorId => {
fieldType => 'text',
label => $i18n->get('vendorId'),
hoverHelp => $i18n->get('vendorId help'),
},
password => {
fieldType => 'password',
label => $i18n->get('password'),
hoverHelp => $i18n->get('password help'),
},
useCVV2 => {
fieldType => 'yesNo',
label => $i18n->get('use cvv2'),
hoverHelp => $i18n->get('use cvv2 help'),
},
credentialsTemplateId => {
fieldType => 'template',
label => $i18n->get('credentials template'),
hoverHelp => $i18n->get('credentials template help'),
namespace => 'Shop/Credentials',
defaultValue => 'itransact_credentials1',
},
emailMessage => {
fieldType => 'textarea',
label => $i18n->get('emailMessage'),
hoverHelp => $i18n->get('emailMessage help'),
},
# readonly stuff from old plugin here?
);
push @{ $definition }, {
name => $i18n->get('Itransact'),
properties => \%fields,
};
return $class->SUPER::definition($session, $definition);
}
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 doXmlRequest ( xml, [ isGatewayInterface ] ) =head2 doXmlRequest ( xml, [ isGatewayInterface ] )
@ -599,16 +579,17 @@ sub www_edit {
my $form = $self->getEditForm; my $form = $self->getEditForm;
$form->submit; $form->submit;
##Form to let the user log into their ITransact account from here.
my $terminal = WebGUI::HTMLForm->new($session, action=>"https://secure.paymentclearing.com/cgi-bin/rc/sess.cgi", extras=>'target="_blank"'); my $terminal = WebGUI::HTMLForm->new($session, action=>"https://secure.paymentclearing.com/cgi-bin/rc/sess.cgi", extras=>'target="_blank"');
$terminal->hidden(name=>"ret_addr", value=>"/cgi-bin/rc/sure/sure.cgi?sure_template_code=session_check&sure_use_session_mid=1"); $terminal->hidden(name=>"ret_addr", value=>"/cgi-bin/rc/sure/sure.cgi?sure_template_code=session_check&sure_use_session_mid=1");
$terminal->hidden(name=>"override", value=>1); $terminal->hidden(name=>"override", value=>1);
$terminal->hidden(name=>"cookie_precheck", value=>0); $terminal->hidden(name=>"cookie_precheck", value=>0);
$terminal->hidden(name=>"mid", value=>$self->get('vendorId')); $terminal->hidden(name=>"mid", value=>$self->vendorId);
$terminal->hidden(name=>"pwd", value=>$self->get('password')); $terminal->hidden(name=>"pwd", value=>$self->password);
$terminal->submit(value=>$i18n->get('show terminal')); $terminal->submit(value=>$i18n->get('show terminal'));
my $output = '<br />'; my $output = '<br />';
if ($self->get('vendorId')) { if ($self->vendorId) {
$output .= $terminal->print.'<br />'; $output .= $terminal->print.'<br />';
} }
$output .= $i18n->get('extra info').'<br />' $output .= $i18n->get('extra info').'<br />'
@ -664,7 +645,7 @@ sub www_getCredentials {
$var->{cvv2Field} = WebGUI::Form::integer($session, { $var->{cvv2Field} = WebGUI::Form::integer($session, {
name => 'cvv2', name => 'cvv2',
value => $self->session->form->process("cvv2"), value => $self->session->form->process("cvv2"),
}) if $self->get('useCVV2'); }) if $self->useCVV2;
$var->{checkoutButton} = WebGUI::Form::submit($session, { $var->{checkoutButton} = WebGUI::Form::submit($session, {
value => $i18n->get('checkout button', 'Shop'), value => $i18n->get('checkout button', 'Shop'),
@ -672,7 +653,7 @@ sub www_getCredentials {
}); });
$self->appendCartVariables($var); $self->appendCartVariables($var);
my $output = $self->processTemplate($self->get("credentialsTemplateId"), $var); my $output = $self->processTemplate($self->credentialsTemplateId, $var);
return $session->style->userStyle($output); return $session->style->userStyle($output);
} }

View file

@ -21,9 +21,56 @@ use WebGUI::Exception;
use Digest::SHA qw{ sha1_hex }; use Digest::SHA qw{ sha1_hex };
use WebGUI::International; use WebGUI::International;
use Data::Dumper; use Data::Dumper;
use Tie::IxHash;
use base qw{ WebGUI::Shop::PayDriver }; use Moose;
use WebGUI::Definition::Shop;
extends 'WebGUI::Shop::PayDriver';
define pluginName => [qw/Ogone PayDriver_Ogone/];
property pspid => (
fieldType => 'text',
label => ['psp id', 'PayDriver_Ogone'],
hoverHelp => ['psp id help', 'PayDriver_Ogone'],
default => '',
);
property shaSecret => (
fieldType => 'password',
label => ['sha secret', 'PayDriver_Ogone'],
hoverHelp => ['sha secret help', 'PayDriver_Ogone'],
);
property postbackSecret => (
fieldType => 'password',
label => ['postback secret', 'PayDriver_Ogone'],
hoverHelp => ['postback secret help', 'PayDriver_Ogone'],
);
property locale => (
fieldType => 'text',
label => ['locale', 'PayDriver_Ogone'],
hoverHelp => ['locale help', 'PayDriver_Ogone'],
default => 'en_US',
maxlength => 5,
size => 5,
);
property currency => (
fieldType => 'text',
label => ['currency', 'PayDriver_Ogone'],
hoverHelp => ['currency help', 'PayDriver_Ogone'],
default => 'EUR',
maxlength => 3,
size => 3,
);
property useTestMode => (
fieldType => 'yesNo',
label => ['use test mode', 'PayDriver_Ogone'],
hoverHelp => ['use test mode help', 'PayDriver_Ogone'],
default => 1,
);
property summaryTemplateId => (
fieldType => 'template',
label => ['summary template', 'PayDriver_Ogone'],
hoverHelp => ['summary template help', 'PayDriver_Ogone'],
namespace => 'Shop/Credentials',
default => 'jysVZeUR0Bx2NfrKs5sulg',
);
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -45,89 +92,13 @@ sub canCheckoutCart {
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 definition ( session, definition )
See WebGUI::Shop::PayDriver->definition.
=cut
sub definition {
my $class = shift;
my $session = shift;
my $definition = shift;
WebGUI::Error::InvalidParam->throw( error => q{Must provide a session variable} )
unless $session && ref $session eq 'WebGUI::Session';
my $i18n = WebGUI::International->new($session, 'PayDriver_Ogone');
tie my %fields, 'Tie::IxHash';
%fields = (
pspid => {
fieldType => 'text',
label => $i18n->get('psp id'),
hoverHelp => $i18n->get('psp id help'),
defaultValue => '',
},
shaSecret => {
fieldType => 'password',
label => $i18n->get('sha secret'),
hoverHelp => $i18n->get('sha secret help'),
},
postbackSecret => {
fieldType => 'password',
label => $i18n->get('postback secret'),
hoverHelp => $i18n->get('postback secret help'),
},
locale => {
fieldType => 'text',
label => $i18n->get('locale'),
hoverHelp => $i18n->get('locale help'),
defaultValue => 'en_US',
maxlength => 5,
size => 5,
},
currency => {
fieldType => 'text',
label => $i18n->get('currency'),
hoverHelp => $i18n->get('currency help'),
defaultValue => 'EUR',
maxlength => 3,
size => 3,
},
useTestMode => {
fieldType => 'yesNo',
label => $i18n->get('use test mode'),
hoverHelp => $i18n->get('use test mode help'),
defaultValue => 1,
},
summaryTemplateId => {
fieldType => 'template',
label => $i18n->get('summary template'),
hoverHelp => $i18n->get('summary template help'),
namespace => 'Shop/Credentials',
defaultValue => 'jysVZeUR0Bx2NfrKs5sulg',
},
);
push @{ $definition }, {
name => $i18n->get('Ogone'),
properties => \%fields,
};
return $class->SUPER::definition($session, $definition);
}
#-------------------------------------------------------------------
=head2 getCart =head2 getCart
Returns the cart for either the current user or the transaction passed back by Ogone. Overrides the base method to use the locally cached cardId.
=cut =cut
sub getCart { override getCart => sub {
my $self = shift; my $self = shift;
my $cart; my $cart;
@ -135,8 +106,8 @@ sub getCart {
$cart = WebGUI::Shop::Cart->new( $self->session, $self->{_cartId} ); $cart = WebGUI::Shop::Cart->new( $self->session, $self->{_cartId} );
} }
return $cart || $self->SUPER::getCart; return $cart || super();
} };
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -193,14 +164,14 @@ sub ogoneCheckoutButton {
my $orderId = $transaction->getId; my $orderId = $transaction->getId;
my $description = "Transaction ID: $orderId"; my $description = "Transaction ID: $orderId";
my $pspId = $self->get('pspid'); my $pspId = $self->pspid;
my $name = join " ", $address->get( 'firstName' ), $address->get( 'lastName' ); my $name = join " ", $address->get( 'firstName' ), $address->get( 'lastName' );
my $email = $address->get('email'); my $email = $address->get('email');
my $currency = $self->get('currency'); my $currency = $self->currency;
# Generate sha signature the payment data # Generate sha signature the payment data
my $passphrase = join '', $orderId, $amount, $currency, $pspId, $self->get('shaSecret'); my $passphrase = join '', $orderId, $amount, $currency, $pspId, $self->shaSecret;
my $shaSignature = uc sha1_hex( $passphrase ); my $shaSignature = uc sha1_hex( $passphrase );
# Define the data to be sent to ogone # Define the data to be sent to ogone
@ -209,7 +180,7 @@ sub ogoneCheckoutButton {
orderID => $orderId, orderID => $orderId,
amount => $amount, amount => $amount,
currency => $currency, currency => $currency,
language => $self->get('locale'), language => $self->locale,
CN => join( " ", $address->get('firstName'), $address->get('lastName') ), CN => join( " ", $address->get('firstName'), $address->get('lastName') ),
EMAIL => $email, EMAIL => $email,
ownerZIP => $address->get( 'code' ), ownerZIP => $address->get( 'code' ),
@ -238,7 +209,7 @@ sub ogoneCheckoutButton {
# Construct actual checkout form # Construct actual checkout form
my $action = $self->get('useTestMode') my $action = $self->useTestMode
? 'https://secure.ogone.com/ncol/test/orderstandard.asp' ? 'https://secure.ogone.com/ncol/test/orderstandard.asp'
: 'https://secure.ogone.com/ncol/prod/orderstandard.asp' : 'https://secure.ogone.com/ncol/prod/orderstandard.asp'
; ;
@ -281,13 +252,13 @@ sub checkPostbackSHA {
# Fetch and format amount from transaction # Fetch and format amount from transaction
my $amount = $transaction->get('amount'); my $amount = $transaction->get('amount');
$amount =~ s/\.00$//; # remove trailing .00 $amount =~ s/\.00$//; # remove trailing .00
my $currency = $self->get('currency'); my $currency = $self->currency;
# Construct the passphrase... # Construct the passphrase...
my $passphrase = join '', my $passphrase = join '',
$transactionId, $currency, $amount, $transactionId, $currency, $amount,
map( { $url->unescape( $form->process( $_ ) ) } qw{ PM ACCEPTANCE STATUS CARDNO PAYID NCERROR BRAND } ), map( { $url->unescape( $form->process( $_ ) ) } qw{ PM ACCEPTANCE STATUS CARDNO PAYID NCERROR BRAND } ),
$self->get('postbackSecret'); $self->postbackSecret;
# and obtain its sha-1 hash in uppercase # and obtain its sha-1 hash in uppercase
my $shaSignature = uc sha1_hex( $passphrase ); my $shaSignature = uc sha1_hex( $passphrase );
@ -486,7 +457,7 @@ sub www_getCredentials {
}; };
$self->appendCartVariables($var); $self->appendCartVariables($var);
my $output = $self->processTemplate($self->get("summaryTemplateId"), $var); my $output = $self->processTemplate($self->summaryTemplateId, $var);
return $session->style->userStyle($output); return $session->style->userStyle($output);
} }

View file

@ -16,7 +16,9 @@ package WebGUI::Shop::PayDriver::PayPal;
## this holds some shared functionality, and MUST be overridden for a full payment driver ## this holds some shared functionality, and MUST be overridden for a full payment driver
use strict; use strict;
use base qw/WebGUI::Shop::PayDriver/; use Moose;
use WebGUI::Definition::Shop;
extends qw/WebGUI::Shop::PayDriver/;
=head1 NAME =head1 NAME

View file

@ -15,7 +15,6 @@ package WebGUI::Shop::PayDriver::PayPal::ExpressCheckout;
=cut =cut
use strict; use strict;
use base qw/WebGUI::Shop::PayDriver/;
use LWP::UserAgent; use LWP::UserAgent;
use Tie::IxHash; use Tie::IxHash;
@ -27,6 +26,80 @@ use URI;
use Readonly; use Readonly;
use Data::Dumper; use Data::Dumper;
Readonly my $I18N => 'PayDriver_ExpressCheckout';
use Moose;
use WebGUI::Definition::Shop;
extends qw/WebGUI::Shop::PayDriver::PayPal/;
define pluginName => [qw/name PayDriver_ExpressCheckout/];
property paypal => (
fieldType => 'text',
label => ['paypal', 'PayDriver_ExpressCheckout'],
hoverHelp => ['paypal help', 'PayDriver_ExpressCheckout'],
default => 'https://www.paypal.com/webscr',
);
property sandbox => (
fieldType => 'text',
label => ['sandbox', 'PayDriver_ExpressCheckout'],
hoverHelp => ['sandbox help', 'PayDriver_ExpressCheckout'],
default => 'https://www.sandbox.paypal.com/webscr',
);
property api => (
fieldType => 'text',
label => ['api', 'PayDriver_ExpressCheckout'],
hoverHelp => ['api help', 'PayDriver_ExpressCheckout'],
default => 'https://api-3t.payPal.com/nvp',
);
property apiSandbox => (
fieldType => 'text',
label => ['apiSandbox', 'PayDriver_ExpressCheckout'],
hoverHelp => ['apiSandbox help', 'PayDriver_ExpressCheckout'],
default => 'https://api-3t.sandbox.payPal.com/nvp',
);
property user => (
fieldType => 'text',
label => ['user', 'PayDriver_ExpressCheckout'],
hoverHelp => ['user help', 'PayDriver_ExpressCheckout'],
);
property password => (
fieldType => 'text',
label => ['password', 'PayDriver_ExpressCheckout'],
hoverHelp => ['password help', 'PayDriver_ExpressCheckout'],
);
property currency => (
fieldType => 'text',
label => ['currency', 'PayDriver_ExpressCheckout'],
hoverHelp => ['currency help', 'PayDriver_ExpressCheckout'],
default => 'USD',
);
property testMode => (
fieldType => 'yesNo',
label => ['testMode', 'PayDriver_ExpressCheckout'],
hoverHelp => ['testMode help', 'PayDriver_ExpressCheckout'],
);
property signature => (
fieldType => 'text',
label => ['signature', 'PayDriver_ExpressCheckout'],
hoverHelp => ['signature help', 'PayDriver_ExpressCheckout'],
);
property summaryTemplateId => (
fieldType => 'template',
label => ['summary template', 'PayDriver_ExpressCheckout'],
hoverHelp => ['summary template help', 'PayDriver_ExpressCheckout'],
namespace => 'Shop/Credentials',
default => 'GqnZPB0gLoZmqQzYFaq7bg',
);
=head1 NAME =head1 NAME
WebGUI::Shop::PayDriver::PayPal WebGUI::Shop::PayDriver::PayPal
@ -51,8 +124,6 @@ The following methods are available from this class:
=cut =cut
Readonly my $I18N => 'PayDriver_ExpressCheckout';
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 apiUrl =head2 apiUrl
@ -64,66 +135,11 @@ use the sandbox)
sub apiUrl { sub apiUrl {
my $self = shift; my $self = shift;
return $self->get( $self->get('testMode') ? 'apiSandbox' : 'api' ); return $self->get( $self->testMode ? 'apiSandbox' : 'api' );
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 definition
Standard definition method.
=cut
sub definition {
my ( $class, $session, $definition ) = @_;
my $i18n = WebGUI::International->new( $session, $I18N );
tie my %fields, 'Tie::IxHash';
my @fieldNames = qw(
paypal sandbox
api apiSandbox
user password
currency testMode
signature
);
foreach my $f (@fieldNames) {
$fields{$f} = {
fieldType => 'text',
label => $i18n->get($f),
hoverHelp => $i18n->get("$f help"),
};
}
$fields{currency}{defaultValue} = 'USD';
$fields{testMode}{fieldType} = 'YesNo';
$fields{sandbox}{defaultValue} = 'https://www.sandbox.paypal.com/webscr';
$fields{apiSandbox}{defaultValue} = 'https://api-3t.sandbox.payPal.com/nvp';
$fields{paypal}{defaultValue} = 'https://www.paypal.com/webscr';
$fields{api}{defaultValue} = 'https://api-3t.payPal.com/nvp';
$fields{summaryTemplateId} = {
fieldType => 'template',
label => $i18n->get('summary template'),
hoverHelp => $i18n->get('summary template help'),
namespace => 'Shop/Credentials',
defaultValue => 'GqnZPB0gLoZmqQzYFaq7bg',
},
push @{$definition}, {
name => $i18n->get('name'),
properties => \%fields,
};
return $class->SUPER::definition( $session, $definition );
} ## end sub definition
#-------------------------------------------------------------------
=head2 getButton =head2 getButton
Overridden, submits to www_sendToPaypal with the proper parameters. Overridden, submits to www_sendToPaypal with the proper parameters.
@ -137,7 +153,7 @@ sub getButton {
my $payForm my $payForm
= WebGUI::Form::formHeader($session) = WebGUI::Form::formHeader($session)
. $self->getDoFormTags('sendToPayPal') . $self->getDoFormTags('sendToPayPal')
. WebGUI::Form::submit( $session, { value => $self->get('name') } ) . WebGUI::Form::submit( $session, { value => $self->pluginName } )
. WebGUI::Form::formFooter($session); . WebGUI::Form::formFooter($session);
return $payForm; return $payForm;
@ -157,9 +173,9 @@ sub payPalForm {
my $self = shift; my $self = shift;
my $args = ref $_[0] eq 'HASH' ? shift : {@_}; my $args = ref $_[0] eq 'HASH' ? shift : {@_};
$args->{VERSION} = '58.0'; $args->{VERSION} = '58.0';
$args->{USER} = $self->get('user'); $args->{USER} = $self->user;
$args->{PWD} = $self->get('password'); $args->{PWD} = $self->password;
$args->{SIGNATURE} = $self->get('signature'); $args->{SIGNATURE} = $self->signature;
return $args; return $args;
} }
@ -175,7 +191,7 @@ use the sandbox)
sub payPalUrl { sub payPalUrl {
my $self = shift; my $self = shift;
return $self->get( $self->get('testMode') ? 'sandbox' : 'paypal' ); return $self->get( $self->testMode ? 'sandbox' : 'paypal' );
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -197,7 +213,7 @@ sub processPayment {
PAYERID => $self->session->form->process('PayerId'), PAYERID => $self->session->form->process('PayerId'),
TOKEN => $self->session->form->process('token'), TOKEN => $self->session->form->process('token'),
AMT => $self->getCart->calculateTotal, AMT => $self->getCart->calculateTotal,
CURRENCYCODE => $self->get('currency'), CURRENCYCODE => $self->currency,
PAYMENTACTION => 'SALE', PAYMENTACTION => 'SALE',
); );
my $response = LWP::UserAgent->new->post( $self->apiUrl, $form ); my $response = LWP::UserAgent->new->post( $self->apiUrl, $form );
@ -286,13 +302,13 @@ sub www_sendToPayPal {
my $form = $self->payPalForm( my $form = $self->payPalForm(
METHOD => 'SetExpressCheckout', METHOD => 'SetExpressCheckout',
AMT => $self->getCart->calculateTotal, AMT => $self->getCart->calculateTotal,
CURRENCYCODE => $self->get('currency'), CURRENCYCODE => $self->currency,
RETURNURL => $returnUrl->as_string, RETURNURL => $returnUrl->as_string,
CANCELURL => $cancelUrl->as_string, CANCELURL => $cancelUrl->as_string,
PAYMENTACTION => 'SALE', PAYMENTACTION => 'SALE',
); );
my $testMode = $self->get('testMode'); my $testMode = $self->testMode;
my $response = LWP::UserAgent->new->post( $self->apiUrl, $form ); my $response = LWP::UserAgent->new->post( $self->apiUrl, $form );
my $params = $self->responseHash($response); my $params = $self->responseHash($response);
my $i18n = WebGUI::International->new( $self->session, $I18N ); my $i18n = WebGUI::International->new( $self->session, $I18N );

View file

@ -16,16 +16,75 @@ package WebGUI::Shop::PayDriver::PayPal::PayPalStd;
use strict; use strict;
use base qw/WebGUI::Shop::PayDriver::PayPal/;
use URI; use URI;
use URI::Escape; use URI::Escape;
use LWP::UserAgent; use LWP::UserAgent;
use Readonly; use Readonly;
use Tie::IxHash;
Readonly my $I18N => 'PayDriver_PayPalStd'; Readonly my $I18N => 'PayDriver_PayPalStd';
use Moose;
use WebGUI::Definition::Shop;
extends qw/WebGUI::Shop::PayDriver::PayPal/;
define pluginName => [qw/PayPal PayDriver_PayPalStd/];
property vendorId => (
fieldType => 'text',
label => ['vendorId', 'PayDriver_PayPalStd'],
hoverHelp => ['vendorId help', 'PayDriver_PayPalStd'],
);
property signature => (
fieldType => 'textarea',
label => ['signature', 'PayDriver_PayPalStd'],
hoverHelp => ['signature help', 'PayDriver_PayPalStd'],
);
property identityToken => (
fieldType => 'text',
label => ['identity token', 'PayDriver_PayPalStd'],
hoverHelp => ['identity token help', 'PayDriver_PayPalStd'],
);
property currency => (
fieldType => 'selectBox',
label => ['currency', 'PayDriver_PayPalStd'],
hoverHelp => ['currency help', 'PayDriver_PayPalStd'],
default => 'USD',
options => \&_currency_options,
);
sub _currency_options {
my $self = shift;
return $self->getPaymentCurrencies();
}
property useSandbox => (
fieldType => 'yesNo',
label => ['use sandbox', 'PayDriver_PayPalStd'],
hoverHelp => ['use sandbox help', 'PayDriver_PayPalStd'],
default => 1,
);
property sandboxUrl => (
fieldType => 'text',
label => ['sandbox url', 'PayDriver_PayPalStd'],
hoverHelp => ['sandbox url help', 'PayDriver_PayPalStd'],
default => 'https://www.sandbox.paypal.com/cgi-bin/webscr',
);
property liveUrl => (
fieldType => 'text',
label => ['live url', 'PayDriver_PayPalStd'],
hoverHelp => ['live url help', 'PayDriver_PayPalStd'],
default => 'https://www.paypal.com/cgi-bin/webscr',
);
property buttonImage => (
fieldType => 'text',
label => ['button image', 'PayDriver_PayPalStd'],
hoverHelp => ['button image help', 'PayDriver_PayPalStd'],
default => '',
);
property summaryTemplateId => (
fieldType => 'template',
label => ['summary template', 'PayDriver_PayPalStd'],
hoverHelp => ['summary template help', 'PayDriver_PayPalStd'],
namespace => 'Shop/Credentials',
default => '',
);
=head1 NAME =head1 NAME
PayPal Website payments standard PayPal Website payments standard
@ -65,82 +124,6 @@ sub handlesRecurring { 0 }
# Recurring TX stuff removed, for now. # Recurring TX stuff removed, for now.
#-------------------------------------------------------------------
sub definition {
my $class = shift;
my $session = shift;
WebGUI::Error::InvalidParam->throw( error => q{Must provide a session variable} )
unless ref $session eq 'WebGUI::Session';
my $definition = shift;
my $i18n = WebGUI::International->new( $session, $I18N );
tie my %fields, 'Tie::IxHash';
%fields = (
vendorId => {
fieldType => 'text',
label => $i18n->get('vendorId'),
hoverHelp => $i18n->get('vendorId help'),
},
signature => {
fieldType => 'textarea',
label => $i18n->get('signature'),
hoverHelp => $i18n->get('signature help'),
},
identityToken => {
fieldType => 'text',
label => $i18n->get('identity token'),
hoverHelp => $i18n->get('identity token help'),
},
currency => {
fieldType => 'selectBox',
label => $i18n->get('currency'),
hoverHelp => $i18n->get('currency help'),
defaultValue => 'USD',
options => $class->getPaymentCurrencies(),
},
useSandbox => {
fieldType => 'yesNo',
label => $i18n->get('use sandbox'),
hoverHelp => $i18n->get('use sandbox help'),
defaultValue => 1,
},
sandboxUrl => {
fieldType => 'text',
label => $i18n->get('sandbox url'),
hoverHelp => $i18n->get('sandbox url help'),
defaultValue => 'https://www.sandbox.paypal.com/cgi-bin/webscr',
},
liveUrl => {
fieldType => 'text',
label => $i18n->get('live url'),
hoverHelp => $i18n->get('live url help'),
defaultValue => 'https://www.paypal.com/cgi-bin/webscr',
},
buttonImage => {
fieldType => 'text',
label => $i18n->get('button image'),
hoverHelp => $i18n->get('button image help'),
defaultValue => '',
},
summaryTemplateId => {
fieldType => 'template',
label => $i18n->get('summary template'),
hoverHelp => $i18n->get('summary template help'),
namespace => 'Shop/Credentials',
defaultValue => '',
},
);
push @{$definition},
{
name => $i18n->get('PayPal'),
properties => \%fields,
};
return $class->SUPER::definition( $session, $definition );
}
#------------------------------------------------------------------- #-------------------------------------------------------------------
=head2 getButton =head2 getButton
@ -173,8 +156,8 @@ sub getButton {
my $button; my $button;
my $i18n = WebGUI::International->new( $session, 'PayDriver_PayPalStd' ); my $i18n = WebGUI::International->new( $session, 'PayDriver_PayPalStd' );
my $text = $i18n->get('PayPal'); my $text = $i18n->get('PayPal');
if ( $self->get('buttonImage') ) { if ( $self->buttonImage ) {
my $raw = $self->get('buttonImage'); my $raw = $self->buttonImage;
WebGUI::Macro::process( $session, \$raw ); WebGUI::Macro::process( $session, \$raw );
$button = qq{ $button = qq{
<input type='image' <input type='image'
@ -222,8 +205,8 @@ sub paymentVariables {
my %params = ( my %params = (
cmd => '_cart', cmd => '_cart',
upload => 1, upload => 1,
business => $self->get('vendorId'), business => $self->vendorId,
currency_code => $self->get('currency'), currency_code => $self->currency,
no_shipping => 1, no_shipping => 1,
return => $return->as_string, return => $return->as_string,
@ -260,8 +243,8 @@ Returns the url of the paypal gateway, taking into account useSandbox.
sub payPalUrl { sub payPalUrl {
my $self = shift; my $self = shift;
my $field = $self->get('useSandbox') ? 'sandboxUrl' : 'liveUrl'; my $field = $self->useSandbox ? 'sandboxUrl' : 'liveUrl';
return $self->get($field); return $self->$field;
} }
#------------------------------------------------------------------- #-------------------------------------------------------------------
@ -285,7 +268,7 @@ sub processPayment {
my %form = ( my %form = (
cmd => '_notify-synch', cmd => '_notify-synch',
tx => $tx, tx => $tx,
at => $self->get('identityToken'), at => $self->identityToken,
); );
my $response = LWP::UserAgent->new->post($self->payPalUrl, \%form); my $response = LWP::UserAgent->new->post($self->payPalUrl, \%form);
my ($status, @lines) = split("\n", uri_unescape($response->content)); my ($status, @lines) = split("\n", uri_unescape($response->content));

View file

@ -118,6 +118,12 @@ our $I18N = {
context => q|Status message|, context => q|Status message|,
}, },
'Payment Driver' => {
message => q|Payment Driver|,
lastUpdated => 0,
context => q|Name of the base Payment Driver|,
},
}; };
1; 1;

View file

@ -23,90 +23,14 @@ use HTML::Form;
use WebGUI::Test; # Must use this before any other WebGUI modules use WebGUI::Test; # Must use this before any other WebGUI modules
use WebGUI::Session; use WebGUI::Session;
use WebGUI::Shop::PayDriver; use WebGUI::Shop::PayDriver;
use Clone;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Init # Init
my $session = WebGUI::Test->session; my $session = WebGUI::Test->session;
#----------------------------------------------------------------------------
# Tests
plan tests => 55;
#----------------------------------------------------------------------------
# figure out if the test can actually run
my $e; my $e;
#######################################################################
#
# definition
#
#######################################################################
my $definition;
eval { $definition = WebGUI::Shop::PayDriver->definition(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'definition takes an exception to not giving it a session variable');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'definition: requires a session variable',
);
$definition = WebGUI::Shop::PayDriver->definition($session);
use Data::Dumper;
cmp_deeply (
$definition,
[ {
name => 'Payment Driver',
properties => {
label => {
fieldType => 'text',
label => ignore(),
hoverHelp => ignore(),
defaultValue => "Credit Card",
},
enabled => {
fieldType => 'yesNo',
label => ignore(),
hoverHelp => ignore(),
defaultValue => 1,
},
groupToUse => {
fieldType => 'group',
label => ignore(),
hoverHelp => ignore(),
defaultValue => 7,
},
}
} ],
,
'Definition returns an array of hashrefs',
);
$definition = WebGUI::Shop::PayDriver->definition($session, [ { name => 'Red' }]);
cmp_deeply (
$definition,
[
{
name => 'Red',
},
{
name => 'Payment Driver',
properties => ignore(),
}
],
,
'New data is appended correctly',
);
####################################################################### #######################################################################
# #
# create # create
@ -117,26 +41,15 @@ my $driver;
# Test incorrect for parameters # Test incorrect for parameters
eval { $driver = WebGUI::Shop::PayDriver->create(); }; eval { $driver = WebGUI::Shop::PayDriver->new(); };
$e = Exception::Class->caught(); $e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'create takes exception to not giving it a session object'); isa_ok ($e, 'WebGUI::Error::InvalidParam', 'new takes exception to not giving it a session object');
cmp_deeply ( cmp_deeply (
$e, $e,
methods( methods(
error => 'Must provide a session variable', error => 'Must provide a session variable',
), ),
'create takes exception to not giving it a session object', 'new takes exception to not giving it a session object',
);
eval { $driver = WebGUI::Shop::PayDriver->create($session, {}); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'create takes exception to giving it an empty hashref of options');
cmp_deeply (
$e,
methods(
error => 'Must provide a hashref of options',
),
'create takes exception to not giving it an empty hashref of options',
); );
# Test functionality # Test functionality
@ -144,15 +57,15 @@ cmp_deeply (
my $options = { my $options = {
label => 'Fast and harmless', label => 'Fast and harmless',
enabled => 1, enabled => 1,
group => 3, groupToUse => 3,
receiptMessage => 'Pannenkoeken zijn nog lekkerder met spek',
}; };
$driver = WebGUI::Shop::PayDriver->create( $session, $options ); $driver = WebGUI::Shop::PayDriver->new( $session, Clone::clone($options) );
isa_ok ($driver, 'WebGUI::Shop::PayDriver', 'create creates WebGUI::Shop::PayDriver object'); isa_ok ($driver, 'WebGUI::Shop::PayDriver', 'new creates WebGUI::Shop::PayDriver object');
like($driver->getId, $session->id->getValidator, 'driver id is a valid GUID'); like($driver->getId, $session->id->getValidator, 'driver id is a valid GUID');
$driver->write;
my $dbData = $session->db->quickHashRef('select * from paymentGateway where paymentGatewayId=?', [ $driver->getId ]); my $dbData = $session->db->quickHashRef('select * from paymentGateway where paymentGatewayId=?', [ $driver->getId ]);
cmp_deeply ( cmp_deeply (
@ -160,7 +73,7 @@ cmp_deeply (
{ {
paymentGatewayId => $driver->getId, paymentGatewayId => $driver->getId,
className => ref $driver, className => ref $driver,
options => q|{"group":3,"receiptMessage":"Pannenkoeken zijn nog lekkerder met spek","label":"Fast and harmless","enabled":1}|, options => q|{"groupToUse":3,"label":"Fast and harmless","enabled":1}|,
}, },
'Correct data written to the db', 'Correct data written to the db',
); );
@ -193,14 +106,6 @@ is ($driver->getId, $driver->paymentGatewayId, 'getId retur
is ($driver->className, ref $driver, 'className property set correctly'); is ($driver->className, ref $driver, 'className property set correctly');
#######################################################################
#
# options
#
#######################################################################
cmp_deeply ($driver->options, $options, 'options accessor works');
####################################################################### #######################################################################
# #
# getName # getName
@ -218,7 +123,29 @@ cmp_deeply (
'getName requires a session object passed to it', 'getName requires a session object passed to it',
); );
is (WebGUI::Shop::PayDriver->getName($session), 'Payment Driver', 'getName returns the human readable name of this driver'); is (WebGUI::Shop::PayDriver->getName($session), 'Payment Driver', 'getName returns the human readable name of this driver');
#######################################################################
#
# method checks
#
#######################################################################
can_ok $driver, qw/get set update write getName className label enabled paymentGatewayId groupToUse/;
#######################################################################
#
# default label
#
#######################################################################
$driver->label('');
is $driver->label, $driver->getName($session), 'empty label replaced with plugin name';
$driver->label('untitled');
is $driver->label, $driver->getName($session), 'label=untitled replaced with plugin name';
$driver->label('uNtItLeD');
is $driver->label, $driver->getName($session), '...regardless of case';
$driver->label('Fast and harmless');
####################################################################### #######################################################################
# #
@ -226,9 +153,17 @@ is (WebGUI::Shop::PayDriver->getName($session), 'Payment Driver', 'getN
# #
####################################################################### #######################################################################
cmp_deeply ($driver->get, $driver->options, 'get works like the options method with no param passed'); use Data::Dumper;
is ($driver->get('enabled'), 1, 'get the enabled entry from the options');
is ($driver->get('label'), 'Fast and harmless', 'get the label entry from the options'); cmp_deeply(
$driver->get,
{
%{ $options },
paymentGatewayId => ignore(),
},
'get works like the options method with no param passed'
);
is ($driver->get('label'), 'Fast and harmless', 'get the label entry from the options');
my $optionsCopy = $driver->get; my $optionsCopy = $driver->get;
$optionsCopy->{label} = 'And now for something completely different'; $optionsCopy->{label} = 'And now for something completely different';
@ -247,7 +182,6 @@ isnt(
my $cart = $driver->getCart; my $cart = $driver->getCart;
WebGUI::Test->addToCleanup($cart); WebGUI::Test->addToCleanup($cart);
isa_ok ($cart, 'WebGUI::Shop::Cart', 'getCart returns an instantiated WebGUI::Shop::Cart object'); isa_ok ($cart, 'WebGUI::Shop::Cart', 'getCart returns an instantiated WebGUI::Shop::Cart object');
WebGUI::Test->addToCleanup($cart);
####################################################################### #######################################################################
# #
@ -374,7 +308,7 @@ my $driverCopy = WebGUI::Shop::PayDriver->new($session, $driver->getId);
is ($driver->getId, $driverCopy->getId, 'same id'); is ($driver->getId, $driverCopy->getId, 'same id');
is ($driver->className, $driverCopy->className, 'same className'); is ($driver->className, $driverCopy->className, 'same className');
cmp_deeply ($driver->options, $driverCopy->options, 'same options'); cmp_deeply ($driver->get, $driverCopy->get, 'same properties');
TODO: { TODO: {
local $TODO = 'tests for new'; local $TODO = 'tests for new';
@ -387,22 +321,10 @@ TODO: {
# #
####################################################################### #######################################################################
eval { $driver->update(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'update takes exception to not giving it a hashref of options');
cmp_deeply (
$e,
methods(
error => 'update was not sent a hashref of options to store in the database',
),
'update takes exception to not giving it a hashref of options',
);
my $newOptions = { my $newOptions = {
label => 'Yet another label', label => 'Yet another label',
enabled => 0, enabled => 0,
group => 4, groupToUse => 4,
receiptMessage => 'Dropjes!',
}; };
$driver->update($newOptions); $driver->update($newOptions);
@ -412,12 +334,10 @@ my $storedJson = $session->db->quickScalar('select options from paymentGateway w
cmp_deeply( cmp_deeply(
$newOptions, $newOptions,
from_json($storedJson), from_json($storedJson),
,
'update() actually stores data', 'update() actually stores data',
); );
is( $driver->get('receiptMessage'), 'Dropjes!', '... updates object, receiptMessage'); is( $driver->get('groupToUse'), 4, '... updates object, group');
is( $driver->get('group'), 4, '... updates object, group');
is( $driver->get('enabled'), 0, '... updates object, enabled'); is( $driver->get('enabled'), 0, '... updates object, enabled');
is( $driver->get('label'), 'Yet another label', '... updates object, label'); is( $driver->get('label'), 'Yet another label', '... updates object, label');
@ -528,4 +448,32 @@ is ($count, 0, 'delete deleted the object');
undef $driver; undef $driver;
#######################################################################
#
# processPropertiesFromFormPost
#
#######################################################################
$session->request->setup_body({
label => 'form processed driver',
enabled => 1,
groupToUse => 7,
});
my $form_driver = WebGUI::Shop::PayDriver->new($session, {});
WebGUI::Test->addToCleanup($form_driver);
$form_driver->processPropertiesFromFormPost;
cmp_deeply(
$form_driver->get(),
{
label => 'form processed driver',
enabled => 1,
groupToUse => 7,
paymentGatewayId => $form_driver->paymentGatewayId,
},
'form contents processed. Missing form properties inherit defaults'
);
done_testing;

View file

@ -25,6 +25,7 @@ use WebGUI::Shop::PayDriver::ITransact;
use JSON; use JSON;
use HTML::Form; use HTML::Form;
use WebGUI::Shop::PayDriver::ITransact; use WebGUI::Shop::PayDriver::ITransact;
use XML::Simple;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Init # Init
@ -35,8 +36,6 @@ $session->user({userId => 3});
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Tests # Tests
plan tests => 28;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# figure out if the test can actually run # figure out if the test can actually run
@ -90,6 +89,7 @@ my $foreignHammer = $rockHammer->setCollateral('variantsJSON', 'variantId', 'new
$versionTag->commit; $versionTag->commit;
WebGUI::Test->addToCleanup($versionTag); WebGUI::Test->addToCleanup($versionTag);
$rockHammer = $rockHammer->cloneFromDb; $rockHammer = $rockHammer->cloneFromDb;
my $hammerItem = $rockHammer->addToCart($rockHammer->getCollateral('variantsJSON', 'variantId', $smallHammer));
my $ship = WebGUI::Shop::Ship->new($session); my $ship = WebGUI::Shop::Ship->new($session);
my $cart = WebGUI::Shop::Cart->newBySession($session); my $cart = WebGUI::Shop::Cart->newBySession($session);
@ -101,58 +101,6 @@ $cart->update({
shipperId => $shipper->getId, shipperId => $shipper->getId,
}); });
#######################################################################
#
# definition
#
#######################################################################
note('Testing definition');
my $definition;
eval { $definition = WebGUI::Shop::PayDriver::ITransact->definition(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'definition takes an exception to not giving it a session variable');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'definition: requires a session variable',
);
#######################################################################
#
# create
#
#######################################################################
my $driver;
# Test incorrect for parameters
eval { $driver = WebGUI::Shop::PayDriver::ITransact->create(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'create takes exception to not giving it a session object');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'create takes exception to not giving it a session object',
);
eval { $driver = WebGUI::Shop::PayDriver::ITransact->create($session, {}); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'create takes exception to giving it an empty hashref of options');
cmp_deeply (
$e,
methods(
error => 'Must provide a hashref of options',
),
'create takes exception to not giving it an empty hashref of options',
);
my $vendorId = $session->config->get("testing/ITransact/vendorId"); my $vendorId = $session->config->get("testing/ITransact/vendorId");
my $password = $session->config->get("testing/ITransact/password"); my $password = $session->config->get("testing/ITransact/password");
my $hasTestAccount = $vendorId && $password; my $hasTestAccount = $vendorId && $password;
@ -164,6 +112,20 @@ if (!$password) {
$password = "joePass"; $password = "joePass";
} }
#######################################################################
#
# getName
#
#######################################################################
ok(WebGUI::Shop::PayDriver::ITransact->getName($session), 'getName returns a name');
#######################################################################
#
# _generatePaymentRequestXML
#
#######################################################################
my $options = { my $options = {
label => 'Fast and harmless', label => 'Fast and harmless',
enabled => 1, enabled => 1,
@ -172,92 +134,9 @@ my $options = {
password => $password, password => $password,
useCVV2 => 1, useCVV2 => 1,
}; };
my $driver = WebGUI::Shop::PayDriver::ITransact->new( $session, $options );
$driver = WebGUI::Shop::PayDriver::ITransact->create( $session, $options ); $driver->write;
WebGUI::Test->addToCleanup($driver);
isa_ok ($driver, 'WebGUI::Shop::PayDriver::ITransact', 'create creates WebGUI::Shop::PayDriver object');
like($driver->getId, $session->id->getValidator, 'driver id is a valid GUID');
#######################################################################
#
# session
#
#######################################################################
isa_ok ($driver->session, 'WebGUI::Session', 'session method returns a session object');
is ($session->getId, $driver->session->getId, 'session method returns OUR session object');
#######################################################################
#
# paymentGatewayId, getId
#
#######################################################################
like ($driver->paymentGatewayId, $session->id->getValidator, 'got a valid GUID for paymentGatewayId');
is ($driver->getId, $driver->paymentGatewayId, 'getId returns the same thing as paymentGatewayId');
#######################################################################
#
# className
#
#######################################################################
is ($driver->className, ref $driver, 'className property set correctly');
#######################################################################
#
# options
#
#######################################################################
cmp_deeply(
$driver->options,
superhashof( $options ),
'options accessor works'
);
#######################################################################
#
# getName
#
#######################################################################
eval { WebGUI::Shop::PayDriver::ITransact->getName(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'getName requires a session object passed to it');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'getName requires a session object passed to it',
);
is(WebGUI::Shop::PayDriver::ITransact->getName($session), 'Credit Card (ITransact)', 'getName returns the human readable name of this driver');
#######################################################################
#
# get
#
#######################################################################
cmp_deeply ($driver->get, $driver->options, 'get works like the options method with no param passed');
is ($driver->get('enabled'), 1, 'get the enabled entry from the options');
is ($driver->get('label'), 'Fast and harmless', 'get the label entry from the options');
my $optionsCopy = $driver->get;
$optionsCopy->{label} = 'And now for something completely different';
isnt(
$driver->get('label'),
'And now for something completely different',
'hashref returned by get() is a copy of the internal hashref'
);
#######################################################################
#
# _generatePaymentRequestXML
#
#######################################################################
my $dt = WebGUI::DateTime->new($session, time()); my $dt = WebGUI::DateTime->new($session, time());
$dt->add({ years => 1, }); $dt->add({ years => 1, });
@ -297,7 +176,10 @@ SKIP: {
my $ok_response = isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object'); my $ok_response = isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object');
SKIP: { SKIP: {
skip "Skipping response check since we did not get a response", 1 unless $ok_response; skip "Skipping response check since we did not get a response", 1 unless $ok_response;
ok( $response->is_success, '... was successful'); ok( $response->is_success, '... response was successful');
my $transactionResult = XMLin( $response->content, SuppressEmpty => '' );
ok defined($transactionResult->{TransactionData}), '... transaction was successful'
or diag $xml.$response->content;
} }
} }
@ -313,24 +195,17 @@ TODO: {
SKIP: { SKIP: {
skip "Skipping XML requests to ITransact due to lack of userId and password", 2 unless $hasTestAccount; skip "Skipping XML requests to ITransact due to lack of userId and password", 2 unless $hasTestAccount;
my $response = eval { $driver->doXmlRequest($xml) }; my $response = eval { $driver->doXmlRequest($xml) };
isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object'); my $ok_response = isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object');
ok( $response->is_success, '... was successful'); ok( $response->is_success, '... was successful for two item transaction');
SKIP: {
skip "Skipping response check since we did not get a response", 1 unless $ok_response;
ok( $response->is_success, '... response was successful for a two item transaction');
my $transactionResult = XMLin( $response->content, SuppressEmpty => '' );
ok defined($transactionResult->{TransactionData}), '... transaction was successful'
or diag $xml.$response->content;
}
} }
####################################################################### done_testing;
#
# delete
#
#######################################################################
$driver->delete;
my $count = $session->db->quickScalar('select count(*) from paymentGateway where paymentGatewayId=?', [
$driver->paymentGatewayId
]);
is ($count, 0, 'delete deleted the object');
undef $driver;
#vim:ft=perl #vim:ft=perl

View file

@ -9,10 +9,6 @@
# http://www.plainblack.com info@plainblack.com # http://www.plainblack.com info@plainblack.com
#------------------------------------------------------------------ #------------------------------------------------------------------
# Write a little about what this script tests.
#
#
use strict; use strict;
use Test::More; use Test::More;
use Test::Deep; use Test::Deep;
@ -30,7 +26,7 @@ my $session = WebGUI::Test->session;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Tests # Tests
plan tests => 45; plan tests => 12;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# figure out if the test can actually run # figure out if the test can actually run
@ -39,104 +35,7 @@ my $e;
####################################################################### #######################################################################
# #
# definition # new
#
#######################################################################
note('Testing definition');
my $definition;
eval { $definition = WebGUI::Shop::PayDriver::Ogone->definition(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'definition takes an exception to not giving it a session variable');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'definition: requires a session variable',
);
$definition = WebGUI::Shop::PayDriver::Ogone->definition($session);
use Data::Dumper;
my $expectDefinition = {
name => 'Ogone',
properties => {
pspid => {
fieldType => 'text',
label => ignore(),
hoverHelp => ignore(),
defaultValue => q{}
},
shaSecret => {
fieldType => 'password',
label => ignore(),
hoverHelp => ignore(),
},
postbackSecret => {
fieldType => 'password',
label => ignore(),
hoverHelp => ignore(),
},
locale => {
fieldType => 'text',
label => ignore(),
hoverHelp => ignore(),
defaultValue => 'en_US',
maxlength => 5,
size => 5,
},
currency => {
fieldType => 'text',
label => ignore(),
hoverHelp => ignore(),
defaultValue => 'EUR',
maxlength => 3,
size => 3,
},
useTestMode => {
fieldType => 'yesNo',
label => ignore(),
hoverHelp => ignore(),
defaultValue => 1,
},
summaryTemplateId => {
fieldType => 'template',
label => ignore(),
hoverHelp => ignore(),
defaultValue => ignore(),
namespace => 'Shop/Credentials',
},
},
};
cmp_deeply ( $definition->[0], $expectDefinition, 'Definition returns an array of hashrefs' );
$definition = WebGUI::Shop::PayDriver::Ogone->definition($session, [ { name => 'Ogone First' }]);
cmp_deeply (
$definition,
[
{
name => 'Ogone First',
},
{
name => 'Ogone',
properties => ignore(),
},
{
name => 'Payment Driver',
properties => ignore(),
}
],
,
'New data is appended correctly',
);
#######################################################################
#
# create
# #
####################################################################### #######################################################################
@ -144,104 +43,18 @@ my $driver;
# Test incorrect for parameters # Test incorrect for parameters
eval { $driver = WebGUI::Shop::PayDriver::Ogone->create(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'create takes exception to not giving it a session object');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'create takes exception to not giving it a session object',
);
eval { $driver = WebGUI::Shop::PayDriver::Ogone->create($session, {}); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'create takes exception to giving it an empty hashref of options');
cmp_deeply (
$e,
methods(
error => 'Must provide a hashref of options',
),
'create takes exception to not giving it an empty hashref of options',
);
# Test functionality
my $signature = '-----BEGIN PKCS7-----
MIIHPwYJKoZIhvcNAQcEoIIHMDCCBywCAQExggE0MIIB
MAIBADCBmDCBkjELMAkGA1UEBhMCVVMxCzAJBgNVBAgT
AkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYD
VQQKEwtQYXlQYWwgSW5jLjEVMBMGA1UECxQMc3RhZ2Ux
X2NlcnRzMRMwEQYDVQQDFApzdGFnZTFfYXBpMRwwGgYJ
KoZIhvcNAQkBFg1yZUBwYXlwYWwuY29tAgEAMA0GCSqG
SIb3DQEBAQUABIGAiJLqJ8905lNbvKoa715KsOJtSOGy
4d6fEKV7+S8KU8E/RK0SFmMgGPRpmXdzx9MXCU43/tXj
lyuyOeZQUBaAIaWoNpfZmBUYIvJVh4W+bDH6JUkugelp
CaTjxXOx/F1qj79D9z06AK+N3yW1fM41fM7X9Q1Bc12g
THjJUKXcIIcxCzAJBgUrDgMCGgUAMIGkBgkqhkiG9w0B
BwEwFAYIKoZIhvcNAwcECOsHG9QOvcJFgIGAwmbN5Acd
cnCH0ZTnsSOq5GtXeQf0j2jCBCg6y7b4ZXQwgdqUC/7x
eb0yicuiRVuRB9WLr/0rGFuSYENpKVUqWYjnlg3TsxLP
IxDCp6lfFqsrclppyZ9CP+xim7y0qKqZZufJG8HgCHxk
3BPD6LqByjQjDVpqKKmCNJ1HlwXGN+SgggOWMIIDkjCC
AvugAwIBAgIBADANBgkqhkiG9w0BAQQFADCBkzELMAkG
A1UEBhMCVVMxCzAJBgNVBAgTAkNBMREwDwYDVQQHEwhT
YW4gSm9zZTEPMA0GA1UEChMGUGF5UGFsMRwwGgYDVQQL
ExNTeXN0ZW1zIEVuZ2luZWVyaW5nMRMwEQYDVQQDEwpT
b3V2aWsgRGFzMSAwHgYJKoZIhvcNAQkBFhFzb3VkYXNA
cGF5cGFsLmNvbTAeFw0wNDA1MjExODE4NTBaFw0wNDA2
MjAxODE4NTBaMIGTMQswCQYDVQQGEwJVUzELMAkGA1UE
CBMCQ0ExETAPBgNVBAcTCFNhbiBKb3NlMQ8wDQYDVQQK
EwZQYXlQYWwxHDAaBgNVBAsTE1N5c3RlbXMgRW5naW5l
ZXJpbmcxEzARBgNVBAMTClNvdXZpayBEYXMxIDAeBgkq
hkiG9w0BCQEWEXNvdWRhc0BwYXlwYWwuY29tMIGfMA0G
CSqGSIb3DQEBAQUAA4GNADCBiQKBgQDatyhVzmVe+kCN
tOSNS+c7p9pNHlFGbGtIWgIAKSOVlaTk4JD/UAvQzYnn
eWPUk+Xb5ShTx8YRDEtRtecy/PwSIIrtS2sC8RrmjZxU
uNRqPB6y1ahGwGcNd/wOIy3FekGE/ctX7oG6/Voz/E2Z
EyJaPm7KwYiDQYz7kWJ6eB+kDwIDAQABo4HzMIHwMB0G
A1UdDgQWBBQx23WZRMmnADSXDr+P7uxORBdDuzCBwAYD
VR0jBIG4MIG1gBQx23WZRMmnADSXDr+P7uxORBdDu6GB
maSBljCBkzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNB
MREwDwYDVQQHEwhTYW4gSm9zZTEPMA0GA1UEChMGUGF5
UGFsMRwwGgYDVQQLExNTeXN0ZW1zIEVuZ2luZWVyaW5n
MRMwEQYDVQQDEwpTb3V2aWsgRGFzMSAwHgYJKoZIhvcN
AQkBFhFzb3VkYXNAcGF5cGFsLmNvbYIBADAMBgNVHRME
BTADAQH/MA0GCSqGSIb3DQEBBAUAA4GBAIBlMsXVnxYe
ZtVTG3rsVYePdkMs+0WdRd+prTK4ZBcAkCyNk9jCq5dy
VziCi4ZCleMqR5Y0NH1+BQAf8vxxcb4Z7p0rryXGb96f
ZfkSYd99a4qGKW3aSIsc2kpaC/ezQg8vuD6JSo6VhJIb
Zn0oWajvkHNMENOwN/Ym5stvAxtnMYIBnzCCAZsCAQEw
gZkwgZMxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTER
MA8GA1UEBxMIU2FuIEpvc2UxDzANBgNVBAoTBlBheVBh
bDEcMBoGA1UECxMTU3lzdGVtcyBFbmdpbmVlcmluZzET
MBEGA1UEAxMKU291dmlrIERhczEgMB4GCSqGSIb3DQEJ
ARYRc291ZGFzQHBheXBhbC5jb20CAQAwCQYFKw4DAhoF
AKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJ
KoZIhvcNAQkFMQ8XDTA0MDUyNjE5MTgxNFowIwYJKoZI
hvcNAQkEMRYEFI2w1oe5qvHYB0w9Z/ntkRcDqLlhMA0G
CSqGSIb3DQEBAQUABIGAimA3r6ZXmyynFGF5cOj6E1Hq
Ebtelq2tg4HroAHZLWoQ3kc/7IM0LCuWZmgtD5739NSS
0+tOFSdH68sxKsdooR3MFTbdzWhtej5fPKRa6BfHGPjI
9R9NoAQBmaeUuOiPSeVTzXDOKDbZB0sJtmWNeueTD9D0
BOu+vkC1g+HRToc=
-----END PKCS7-----';
my $options = { my $options = {
label => 'Fast and harmless', label => 'Fast and harmless',
enabled => 1, enabled => 1,
group => 3, groupToUse => 3,
receiptMessage => 'Pannenkoeken zijn nog lekkerder met kaas',
vendorId => 'oqapi',
signature => $signature,
currency => 'EUR', currency => 'EUR',
useSandbox => '0',
emailMessage => 'Thank you very very much'
}; };
$driver = WebGUI::Shop::PayDriver::Ogone->create( $session, $options ); $driver = WebGUI::Shop::PayDriver::Ogone->new( $session, $options );
WebGUI::Test->addToCleanup($driver);
$driver->write;
isa_ok ($driver, 'WebGUI::Shop::PayDriver::Ogone', 'create creates WebGUI::Shop::PayDriver object'); isa_ok ($driver, 'WebGUI::Shop::PayDriver::Ogone', 'new creates WebGUI::Shop::PayDriver object');
like($driver->getId, $session->id->getValidator, 'driver id is a valid GUID'); like($driver->getId, $session->id->getValidator, 'driver id is a valid GUID');
my $dbData = $session->db->quickHashRef('select * from paymentGateway where paymentGatewayId=?', [ $driver->getId ]); my $dbData = $session->db->quickHashRef('select * from paymentGateway where paymentGatewayId=?', [ $driver->getId ]);
@ -259,54 +72,21 @@ my $paymentGatewayOptions = from_json($dbData->{'options'});
cmp_deeply ( cmp_deeply (
$paymentGatewayOptions, $paymentGatewayOptions,
{ {
"group" => 3, groupToUse => 3,
"receiptMessage" => 'Pannenkoeken zijn nog lekkerder met kaas', label => 'Fast and harmless',
"label" => 'Fast and harmless', enabled => 1,
"enabled" => 1, currency => 'EUR',
"vendorId" => 'oqapi', pspid => '',
"signature" => $signature, summaryTemplateId => 'jysVZeUR0Bx2NfrKs5sulg',
"currency" => 'EUR', useTestMode => 1,
"useSandbox" => '0', locale => 'en_US',
"emailMessage" => 'Thank you very very much' shaSecret => undef,
postbackSecret => undef,
}, },
'Correct options are written to the db' 'Correct options are written to the db'
); );
#######################################################################
#
# session
#
#######################################################################
isa_ok ($driver->session, 'WebGUI::Session', 'session method returns a session object');
is ($session->getId, $driver->session->getId, 'session method returns OUR session object');
#######################################################################
#
# paymentGatewayId, getId
#
#######################################################################
like ($driver->paymentGatewayId, $session->id->getValidator, 'got a valid GUID for paymentGatewayId');
is ($driver->getId, $driver->paymentGatewayId, 'getId returns the same thing as paymentGatewayId');
#######################################################################
#
# className
#
#######################################################################
is ($driver->className, ref $driver, 'className property set correctly');
#######################################################################
#
# options
#
#######################################################################
cmp_deeply ($driver->options, $options, 'options accessor works');
####################################################################### #######################################################################
# #
# getName # getName
@ -326,24 +106,6 @@ cmp_deeply (
is (WebGUI::Shop::PayDriver::Ogone->getName($session), 'Ogone', 'getName returns the human readable name of this driver'); is (WebGUI::Shop::PayDriver::Ogone->getName($session), 'Ogone', 'getName returns the human readable name of this driver');
#######################################################################
#
# get
#
#######################################################################
cmp_deeply ($driver->get, $driver->options, 'get works like the options method with no param passed');
is ($driver->get('enabled'), 1, 'get the enabled entry from the options');
is ($driver->get('label'), 'Fast and harmless', 'get the label entry from the options');
my $optionsCopy = $driver->get;
$optionsCopy->{label} = 'And now for something completely different';
isnt(
$driver->get('label'),
'And now for something completely different',
'hashref returned by get() is a copy of the internal hashref'
);
####################################################################### #######################################################################
# #
# getCart # getCart
@ -353,7 +115,6 @@ isnt(
my $cart = $driver->getCart; my $cart = $driver->getCart;
WebGUI::Test->addToCleanup($cart); WebGUI::Test->addToCleanup($cart);
isa_ok ($cart, 'WebGUI::Shop::Cart', 'getCart returns an instantiated WebGUI::Shop::Cart object'); isa_ok ($cart, 'WebGUI::Shop::Cart', 'getCart returns an instantiated WebGUI::Shop::Cart object');
WebGUI::Test->addToCleanup($cart);
####################################################################### #######################################################################
# #
@ -461,123 +222,4 @@ cmp_deeply(
); );
#######################################################################
#
# new
#
#######################################################################
my $oldDriver;
eval { $oldDriver = WebGUI::Shop::PayDriver::Ogone->new(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'new takes exception to not giving it a session object');
cmp_deeply (
$e,
methods(
error => 'Must provide a session variable',
),
'new takes exception to not giving it a session object',
);
eval { $oldDriver = WebGUI::Shop::PayDriver::Ogone->new($session); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'new takes exception to not giving it a paymentGatewayId');
cmp_deeply (
$e,
methods(
error => 'Must provide a paymentGatewayId',
),
'new takes exception to not giving it a paymentGatewayId',
);
eval { $oldDriver = WebGUI::Shop::PayDriver::Ogone->new($session, 'notEverAnId'); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::ObjectNotFound', 'new croaks unless the requested paymentGatewayId object exists in the db');
cmp_deeply (
$e,
methods(
error => 'paymentGatewayId not found in db',
id => 'notEverAnId',
),
'new croaks unless the requested paymentGatewayId object exists in the db',
);
my $driverCopy = WebGUI::Shop::PayDriver::Ogone->new($session, $driver->getId);
is ($driver->getId, $driverCopy->getId, 'same id');
is ($driver->className, $driverCopy->className, 'same className');
cmp_deeply ($driver->options, $driverCopy->options, 'same options');
#######################################################################
#
# update
#
#######################################################################
eval { $driver->update(); };
$e = Exception::Class->caught();
isa_ok ($e, 'WebGUI::Error::InvalidParam', 'update takes exception to not giving it a hashref of options');
cmp_deeply (
$e,
methods(
error => 'update was not sent a hashref of options to store in the database',
),
'update takes exception to not giving it a hashref of options',
);
my $newOptions = {
label => 'Yet another label',
enabled => 0,
group => 4,
receiptMessage => 'Dropjes!',
};
$driver->update($newOptions);
my $storedOptions = $session->db->quickScalar('select options from paymentGateway where paymentGatewayId=?', [
$driver->getId,
]);
cmp_deeply(
$newOptions,
from_json($storedOptions),
,
'update() actually stores data',
);
#######################################################################
#
# canUse
#
#######################################################################
my $newOptions = {
label => 'Yet another label',
enabled => 1,
group => 4,
receiptMessage => 'Dropjes!',
};
$driver->update($newOptions);
$session->user({userId => 3});
ok($driver->canUse, 'canUse: session->user is used if no argument is passed');
ok(!$driver->canUse({userId => 1}), 'canUse: userId explicit works, visitor cannot use this driver');
#######################################################################
#
# delete
#
#######################################################################
$driver->delete;
my $count = $session->db->quickScalar('select count(*) from paymentGateway where paymentGatewayId=?', [
$driver->paymentGatewayId
]);
is ($count, 0, 'delete deleted the object');
undef $driver;
#vim:ft=perl #vim:ft=perl

View file

@ -21,6 +21,7 @@ use HTML::Form;
use WebGUI::Test; # Must use this before any other WebGUI modules use WebGUI::Test; # Must use this before any other WebGUI modules
use WebGUI::Session; use WebGUI::Session;
use WebGUI::Shop::PayDriver::PayPal::PayPalStd;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Init # Init
@ -29,16 +30,13 @@ my $session = WebGUI::Test->session;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# Tests # Tests
my $tests = 3; plan tests => 3;
plan tests => 1 + $tests;
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
# figure out if the test can actually run # figure out if the test can actually run
my $e; my $e;
my $loaded = use_ok('WebGUI::Shop::PayDriver::PayPal::PayPalStd');
####################################################################### #######################################################################
# #
# getName # getName
@ -48,25 +46,15 @@ my $driver;
my $options = { my $options = {
label => 'PayPal', label => 'PayPal',
enabled => 1, enabled => 1,
group => 3, groupToUse => 3,
receiptMessage => 'Pannenkoeken zijn nog lekkerder met spek',
}; };
$driver = WebGUI::Shop::PayDriver::PayPal::PayPalStd->create( $session, $options ); $driver = WebGUI::Shop::PayDriver::PayPal::PayPalStd->new( $session, $options );
WebGUI::Test->addToCleanup($driver);
isa_ok ($driver, 'WebGUI::Shop::PayDriver'); isa_ok ($driver, 'WebGUI::Shop::PayDriver');
isa_ok ($driver, 'WebGUI::Shop::PayDriver::PayPal::PayPalStd'); isa_ok ($driver, 'WebGUI::Shop::PayDriver::PayPal::PayPalStd');
is($driver->getName($session), 'PayPal', 'getName returns the human readable name of this driver'); is($driver->getName($session), 'PayPal', 'getName returns the human readable name of this driver');
#######################################################################
#
# delete
#
#######################################################################
$driver->delete;
undef $driver;
#vim:ft=perl #vim:ft=perl