1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-20 00:11:35 +02:00
Received PHP-Payments directory from parent.
This commit is contained in:
blkmutt 2014-04-13 07:06:24 -04:00
commit a7e0ca0d60
196 changed files with 36265 additions and 133 deletions

View File

@ -72,3 +72,4 @@ Configure config/database.php and then initialize the database
* [josscrowcroft/accounting.js](https://github.com/josscrowcroft/accounting.js) - A lightweight JavaScript library for number, money and currency formatting
* [jashkenas/underscore](https://github.com/jashkenas/underscore) - JavaScript's utility _ belt
* [caouecs/Laravel4-long](https://github.com/caouecs/Laravel4-lang) - List of languages for Laravel4
* [calvinfroedge/PHP-Payments](https://github.com/calvinfroedge/PHP-Payments) - A uniform payments interface for PHP

View File

@ -55,121 +55,16 @@ class AccountController extends \BaseController {
public function enableProPlan()
{
if (Auth::user()->isPro())
$invoice = $this->accountRepo->enableProPlan();
if ($invoice)
{
return Redirect::to('/dashboard');
}
$account = Auth::user()->account;
$ninjaAccount = $this->getNinjaAccount();
$ninjaClient = $this->getNinjaClient($ninjaAccount);
$invoice = $this->createNinjaInvoice($ninjaAccount, $ninjaClient);
$this->contactMailer->sendInvoice($invoice);
}
return RESULT_SUCCESS;
}
private function createNinjaInvoice($account, $client)
{
$lastInvoice = Invoice::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first();
$publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1;
$invoice = new Invoice();
$invoice->account_id = $account->id;
$invoice->user_id = $account->users()->first()->id;
$invoice->public_id = $publicId;
$invoice->client_id = $client->id;
$invoice->invoice_number = $account->getNextInvoiceNumber();
$invoice->invoice_date = date_create()->format('Y-m-d');
$invoice->amount = PRO_PLAN_PRICE;
$invoice->balance = PRO_PLAN_PRICE;
$invoice->save();
$item = new InvoiceItem();
$item->account_id = $account->id;
$item->user_id = $account->users()->first()->id;
$item->public_id = $publicId;
$item->qty = 1;
$item->cost = PRO_PLAN_PRICE;
$item->notes = trans('texts.pro_plan_description');
$item->product_key = trans('texts.pro_plan_product');
$invoice->invoice_items()->save($item);
$invitation = new Invitation();
$invitation->account_id = $account->id;
$invitation->user_id = $account->users()->first()->id;
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $client->contacts()->first()->id;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
return $invoice;
}
private function getNinjaAccount()
{
$account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first();
if ($account)
{
return $account;
}
else
{
$account = new Account();
$account->name = 'Invoice Ninja';
$account->work_email = 'contact@invoiceninja.com';
$account->work_phone = '(800) 763-1948';
$account->account_key = NINJA_ACCOUNT_KEY;
$account->save();
$random = str_random(RANDOM_KEY_LENGTH);
$user = new User();
$user->registered = true;
$user->confirmed = true;
$user->email = 'contact@invoiceninja.com';
$user->password = $random;
$user->password_confirmation = $random;
$user->username = $random;
$user->notify_sent = false;
$user->notify_paid = false;
$account->users()->save($user);
}
return $account;
}
private function getNinjaClient($ninjaAccount)
{
$client = Client::whereAccountId($ninjaAccount->id)->wherePublicId(Auth::user()->account_id)->first();
if (!$client)
{
$client = new Client;
$client->public_id = Auth::user()->account_id;
$client->user_id = $ninjaAccount->users()->first()->id;
foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone'] as $field)
{
$client->$field = Auth::user()->account->$field;
}
$ninjaAccount->clients()->save($client);
$contact = new Contact;
$contact->user_id = $ninjaAccount->users()->first()->id;
$contact->is_primary = true;
foreach (['first_name', 'last_name', 'email', 'phone'] as $field)
{
$contact->$field = Auth::user()->$field;
}
$client->contacts()->save($contact);
}
return $client;
}
public function setTrashVisible($entityType, $visible)
{
Session::put('show_trash', $visible == 'true');
@ -769,6 +664,11 @@ class AccountController extends \BaseController {
$activity->save();
}
if (Input::get('go_pro') == 'true')
{
Session::set(REQUESTED_PRO_PLAN, true);
}
return "{$user->first_name} {$user->last_name}";
}
}

View File

@ -9,8 +9,22 @@
|
*/
use ninja\repositories\AccountRepository;
use ninja\mailers\ContactMailer;
class UserController extends BaseController {
protected $accountRepo;
protected $contactMailer;
public function __construct(AccountRepository $accountRepo, ContactMailer $contactMailer)
{
parent::__construct();
$this->accountRepo = $accountRepo;
$this->contactMailer = $contactMailer;
}
public function setTheme()
{
$user = User::find(Auth::user()->id);
@ -171,6 +185,18 @@ class UserController extends BaseController {
if ( Confide::confirm( $code ) )
{
$notice_msg = trans('texts.confide.confirmation');
if (Session::has(REQUESTED_PRO_PLAN))
{
Session::forget(REQUESTED_PRO_PLAN);
if ($invoice = $this->accountRepo->enableProPlan())
{
$this->contactMailer->sendInvoice($invoice);
$notice_msg = trans('texts.pro_plan_succes');
}
}
return Redirect::action('UserController@login')->with( 'message', $notice_msg );
}
else

View File

@ -5,6 +5,8 @@ class PaymentLibrariesSeeder extends Seeder
public function run()
{
Eloquent::unguard();
$gateways = [
array('name'=>'BeanStream', 'provider'=>'BeanStream', 'payment_library_id' => 2),
array('name'=>'Psigate', 'provider'=>'Psigate', 'payment_library_id' => 2)

View File

@ -308,6 +308,6 @@ return array(
'pro_plan_product' => 'Pro Plan',
'pro_plan_description' => 'One year enrollment in the Invoice Ninja Pro Plan',
'pro_plan_succes' => 'We\'ve sent you an invoice. Once paid the kfeatures will be enabled.',
'pro_plan_succes' => 'Thanks for joining! Once the invoice is paid your membership will begin.',
);

View File

@ -2,6 +2,11 @@
class Utils
{
public static function isRegistered()
{
return Auth::check() && Auth::user()->registered;
}
public static function isProd()
{
return App::environment() == ENV_PRODUCTION;

View File

@ -25,7 +25,7 @@ class Gateway extends Eloquent
}
else
{
$fields = Payment_Utility::load('config', 'drivers/'.$this->provider);
$fields = Payment_Utility::load('config', 'drivers/'.strtolower($this->provider));
}
if($fields == null)

View File

@ -7,6 +7,10 @@ use Request;
use Session;
use Language;
use User;
use Auth;
use Invitation;
use Invoice;
use InvoiceItem;
class AccountRepository
{
@ -90,4 +94,124 @@ class AccountRepository
return $data;
}
public function enableProPlan()
{
if (Auth::user()->isPro())
{
return false;
}
$account = Auth::user()->account;
$ninjaAccount = $this->getNinjaAccount();
$ninjaClient = $this->getNinjaClient($ninjaAccount);
$invoice = $this->createNinjaInvoice($ninjaAccount, $ninjaClient);
return $invoice;
}
private function createNinjaInvoice($account, $client)
{
$lastInvoice = Invoice::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first();
$publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1;
$invoice = new Invoice();
$invoice->account_id = $account->id;
$invoice->user_id = $account->users()->first()->id;
$invoice->public_id = $publicId;
$invoice->client_id = $client->id;
$invoice->invoice_number = $account->getNextInvoiceNumber();
$invoice->invoice_date = date_create()->format('Y-m-d');
$invoice->amount = PRO_PLAN_PRICE;
$invoice->balance = PRO_PLAN_PRICE;
$invoice->save();
$item = new InvoiceItem();
$item->account_id = $account->id;
$item->user_id = $account->users()->first()->id;
$item->public_id = $publicId;
$item->qty = 1;
$item->cost = PRO_PLAN_PRICE;
$item->notes = trans('texts.pro_plan_description');
$item->product_key = trans('texts.pro_plan_product');
$invoice->invoice_items()->save($item);
$invitation = new Invitation();
$invitation->account_id = $account->id;
$invitation->user_id = $account->users()->first()->id;
$invitation->public_id = $publicId;
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $client->contacts()->first()->id;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
return $invoice;
}
private function getNinjaAccount()
{
$account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first();
if ($account)
{
return $account;
}
else
{
$account = new Account();
$account->name = 'Invoice Ninja';
$account->work_email = 'contact@invoiceninja.com';
$account->work_phone = '(800) 763-1948';
$account->account_key = NINJA_ACCOUNT_KEY;
$account->save();
$random = str_random(RANDOM_KEY_LENGTH);
$user = new User();
$user->registered = true;
$user->confirmed = true;
$user->email = 'contact@invoiceninja.com';
$user->password = $random;
$user->password_confirmation = $random;
$user->username = $random;
$user->first_name = 'Invoice';
$user->last_name = 'Ninja';
$user->notify_sent = false;
$user->notify_paid = false;
$account->users()->save($user);
}
return $account;
}
private function getNinjaClient($ninjaAccount)
{
$client = Client::whereAccountId($ninjaAccount->id)->wherePublicId(Auth::user()->account_id)->first();
if (!$client)
{
$client = new Client;
$client->public_id = Auth::user()->account_id;
$client->user_id = $ninjaAccount->users()->first()->id;
foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone'] as $field)
{
$client->$field = Auth::user()->account->$field;
}
$ninjaAccount->clients()->save($client);
$contact = new Contact;
$contact->user_id = $ninjaAccount->users()->first()->id;
$contact->is_primary = true;
foreach (['first_name', 'last_name', 'email', 'phone'] as $field)
{
$contact->$field = Auth::user()->$field;
}
$client->contacts()->save($contact);
}
return $client;
}
}

View File

@ -11,6 +11,8 @@
|
*/
//apc_clear_cache();
//Cache::flush();
@ -237,7 +239,7 @@ define('RESULT_FAILURE', 'failure');
define('GATEWAY_PAYPAL_EXPRESS', 17);
define('NINJA_ACCOUNT_KEY', 'zg4ylmzDkdkPOT8yoKQw9LTWaoZJx79h');
define('PRO_PLAN_PRICE', 40);
define('REQUESTED_PRO_PLAN', 'REQUESTED_PRO_PLAN');
define('PAYMENT_LIBRARY_OMNIPAY', 1);
define('PAYMENT_LIBRARY_PHP_PAYMENTS', 2);
@ -304,3 +306,5 @@ if (Auth::check() && Auth::user()->id === 1)
Auth::loginUsingId(1);
}
*/
//dd(Session::has(REQUESTED_PRO_PLAN));

View File

@ -11,8 +11,6 @@
{{ Former::legend('Payment Gateway') }}
{{Former::label('Lorem Ipsum goes here.')}}
@if ($accountGateway)
{{ Former::populateField('gateway_id', $accountGateway->gateway_id) }}
{{ Former::populateField('recommendedGateway_id', $accountGateway->gateway_id) }}

View File

@ -256,7 +256,11 @@ Want something changed? We're {{ link_to('https://github.com/hillelcoren/invoice
{{ Former::populateField('new_email', Auth::user()->email); }}
@endif
{{ Former::hidden('path')->value(Request::path()) }}
<div style="display:none">
{{ Former::text('path')->value(Request::path()) }}
{{ Former::text('go_pro') }}
</div>
{{ Former::text('new_first_name')->label(trans('texts.first_name')) }}
{{ Former::text('new_last_name')->label(trans('texts.last_name')) }}
{{ Former::text('new_email')->label(trans('texts.email')) }}
@ -396,7 +400,8 @@ Want something changed? We're {{ link_to('https://github.com/hillelcoren/invoice
data: 'new_email=' + encodeURIComponent($('form.signUpForm #new_email').val()) +
'&new_password=' + encodeURIComponent($('form.signUpForm #new_password').val()) +
'&new_first_name=' + encodeURIComponent($('form.signUpForm #new_first_name').val()) +
'&new_last_name=' + encodeURIComponent($('form.signUpForm #new_last_name').val()),
'&new_last_name=' + encodeURIComponent($('form.signUpForm #new_last_name').val()) +
'&go_pro=' + $('#go_pro').val(),
success: function(result) {
if (result) {
localStorage.setItem('guest_key', '');

View File

@ -438,7 +438,7 @@
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="proPlanModalLabel">{{ trans('texts.sign_up') }}</h4>
<h4 class="modal-title" id="proPlanModalLabel">{{ trans('texts.pro_plan_product') }}</h4>
</div>
<div style="background-color: #fff; padding-left: 16px; padding-right: 16px" id="proPlanDiv">
@ -455,16 +455,15 @@
</div>
</div>
<div style="background-color: #fff; padding-right:20px;padding-left:20px; display:none" id="proPlanSuccessDiv">
<div style="background-color: #fff; padding-right:20px;padding-left:20px; display:none" id="proPlanSuccess">
<br/>
<h3>{{ trans('texts.success') }}</h3>
{{ trans('texts.pro_plan_succes') }}<br/>&nbsp;
</div>
<div class="modal-footer" style="margin-top: 0px" id="proPlanFooter">
<button type="button" class="btn btn-default" data-dismiss="modal">{{ trans('texts.close') }}</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" id="proPlanButton" onclick="submitProPlan()">{{ trans('texts.sign_up') }}</button>
<button type="button" class="btn btn-primary" id="proPlanButton" onclick="submitProPlan()">{{ trans('texts.sign_up') }}</button>
</div>
</div>
</div>
@ -488,6 +487,7 @@
function submitProPlan() {
if ({{ Utils::isRegistered() ? 'true' : 'false' }}) {
$('#proPlanDiv, #proPlanFooter').hide();
$('#proPlanWorking').show();
@ -495,11 +495,15 @@
type: 'POST',
url: '{{ URL::to('account/go_pro') }}',
success: function(result) {
$('#proPlanSuccessDiv, #proPlanFooter').show();
$('#proPlanSuccess, #proPlanFooter').show();
$('#proPlanWorking, #proPlanButton').hide();
}
});
} else {
$('#proPlanModal').modal('hide');
$('#go_pro').val('true');
showSignUp();
}
}
$(function() {

80
vendor/php-payments/README.md vendored Executable file
View File

@ -0,0 +1,80 @@
## This code has taken tons of work. Donations highly appreciated. [Make a Donation](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=TJMWX5E9GXS7S "Make a Donation to Codeigniter Payments")
# PHP Payments
## NOTICE - USING PHP-PAYMENTS ALONE DOES NOT MAKE YOU PCI COMPLIANT
It is highly recommended that you attempt to architect your application to achieve some level of PCI compliance. Without this, the applications you create can be vulnerable to fines for PCI compliance violations. Using PHP-Payments does not circumvent the need for you to do this. You can check out the PCI compliance self assessment form here: https://www.pcisecuritystandards.org/merchants/self_assessment_form.php
## Installing
There are config files for each gateway in the /config folder of the package. You need to enter your own API usernames and passwords (the ones in there are mine, used only for testing purposes) in the config of each gateway you would like to use.
## Testing
1. If you want to test locally (and you should), you need to set "force_secure_connection" to FALSE in config/payments.php
2. By default, test api endpoints will be used. To enable production endpoints, change the mode in /config/payments.php from 'test' to 'production' or pass a 'mode' parameter in the config param when you instantiate PHP payments (ie $p = new PHP-Payments(array('mode' => 'test'));. Note that if you are a Psigate customer, you must obtain your production endpoint from Psigate support.
3. It's highly advised that you run tests before trying to go live. The automated testing utility in the tests folder can help you do this. To use tests:
- To run all tests, cd into tests and type test.php
- To test all payment drivers, cd into tests and type test.php drivers
- To test a specific payment driver, cd into tests and type test.php drivers driver (Where 'driver' is a driver name, such as stripe, beanstream or paypal_payments_pro)
Alternatively, you could visit test.php in a web browser to run all tests. We may introduce enhanced browser based testing in the future - but for not the preferred usage is from command line.
## Documentation
To avoid constantly updating documentation to match code, we've opted for automating as much documentation as possible. To view the current documentation, cd into the documentation folder, then cd into dox and type doxgen.php in the command line. You can alternatively open this file in a web browser.
When you run doxgen, documentation will appear in documentation/HTML which you can load in your web browser.
## Gateway, Method and Parameter Support
As this is constantly changing, please run doxgen.php in the dox folder to generate up to date documentation. At time of writing the README, PHP-Payments supports a dozen gateways. However it should be mentioned the PHP-Payments currently supports two types of gateways - "Button" gateways and regular "Server to Server" gateways. Button gateways may have server to server operations, but for things like payment methods (such as oneoff_payment_button) generate HTML code for a button. This HTML code is retrieved from the detail property of a PHP-Payments response object.
## Responses
There are two types of responses returned, local responses and gateway responses. If a method is not supported, required params are missing, a gateway does not exist, etc., a local response will be returned. This prevents the transaction from being sent to the gateway and the gateway telling you 3 seconds later there is something wrong with your request.:
```php
'type' => 'local_response', //Indicates failure was local
'status' => $status, //Either success or failure
'response_code' => $this->_response_codes[$response],
'response_message' => $this->_response_messages[$response],
'details' => $response_details
```
Access response properties by naming your call something like this:
```php
$response = $payments->payment_action('gateway_name', $params);
```
Then you can do:
```php
$status = $response->status;
```
Gateway responses will usually have a full response from the gateway, and on failure a 'reason' property in the details object:
```php
'type' => 'gateway_response',
'status' => $status,
'response_code' => $this->_response_codes[$response],
'response_message' => $this->_response_messages[$response],
'details' => $details
```
You can access this like $response->details->reason. You may want to save the full gateway response (it's an array) in a database table, you can access it at $response->details->gateway_response
## LICENSE
Copyright (c) 2011-2012 Calvin Froedge
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,14 @@
<?php
$config = array(
'access_key' => 'test',
'secret_key' => 'test',
'abandon_url' => 'http://yourwebsite.com/cancel', //Where user goes if they cancel the order
'return_url' => 'http://yourwebsite.com/continue', //Where user goes after payment is finished
'immediate_return' => '0', //Set to 1 if you want to skip the final status screen on amazon
'process_immediate' => '0', //1 if you want to settle immediately. Else it's simply an authorization and you must capture later.
'ipn_url' => 'http://yourwebsite.com/ipn', //Where to send the ipn notification
'collect_shipping_address' => '1', //1 tells amazon to collect buyer's shipping information
);
return $config;

View File

@ -0,0 +1,8 @@
<?php
$config['api_username'] = "25xTC7vJp";
$config['api_password'] = "3zF64K5BA9a3y6rG";
//Note: you can sign into the test interface at test.authorize.net
$config['email_customer'] = TRUE;
return $config;

View File

@ -0,0 +1,26 @@
<?php
$config['merchant_id'] = "237380000";
$config['username'] = "testuser";
$config['password'] = "testpass11";
$config['passCode'] = "72b7bdbCaac44AAa9b94ec9ca790E6AB";
//Recurring billing settings. Important!
$config['delay_charge'] = FALSE; //set this to 0 if you want to charge customers as soon as they elect to begin recurring billing, or 1 if you want to wait until their profile start date to bill them.
$config['bill_outstanding'] = TRUE; /* By default, new recurring billing accounts are flagged
to automatically process back payments if the account
is disabled and then re-activated. This setting may be
modified at any time through the Beanstream member
area or via API. This is done separately for each
individual recurring billing customer account. When
re-activating an account via API, back payments will be
processed or ignored according to the value set for the
individual customer in the Beanstream member area
unless this variable is passed.
Specify processBackPayments=1 to process back
payments and charge the customer for any missed
invoices when an account is re-activated. Specify
processBackPayments=0 to re-activate the account
without charging back payments.*/
return $config;

View File

@ -0,0 +1,15 @@
<?php
/*
|-------------------------------------------------------------------------
| Payment Gateway Credentials
|--------------------------------------------------------------------------
|
| Fill out the following information with those provided
| to you by your gateway.
|
*/
$config['api_secret_key'] = "XXXXXXXXXXX"; // Bluepay Secret Key (NEVER sent directly over the wire)
$config['api_account_id'] = "00000000000"; // Bluepay 12 Digit ACCOUNT_ID
$config['api_user_id'] = "00000000000"; // Bluepay 12 Digit USER_ID (optional but helpful)
return $config;

View File

@ -0,0 +1,7 @@
<?php
$config['merchantId'] = '232324234';
$config['publicKey'] = 'asdfasdfa232f';
$config['privateKey'] = 'dafsdf23';
return $config;

4
vendor/php-payments/config/drivers/eway.php vendored Executable file
View File

@ -0,0 +1,4 @@
<?php
$config['api_cid'] = "87654321";
return $config;

View File

@ -0,0 +1,10 @@
<?php
$config = array(
'app_identifier' => 'mCeiwZDpJ6Qt_ktvePBvFQPCqoVTPE6nCbaG17IWl6UPqxZtda967ezzyXjI_wwm',
'app_secret' => 'nAdkW9Geud8lOXguS_qUYNM2C96J5DFRA0nmbpKFheJUzxj85SQI2qm1gyrE1aFf',
'access_token' => 'HckEz6jLMRxSfWSHqxHrRMJlQF3VGFQo1UGts46X1veyBIejzZ3emeb0sLYA7LqY',
'id' => '01FCVJW4YC'
);
return $config;

View File

@ -0,0 +1,10 @@
<?php
$config = array(
'merchant_id' => 'test',
'merchant_key' => 'test',
'request_buyer_phone' => true,
'button_size' => 'SMALL'
);
return $config;

View File

@ -0,0 +1,7 @@
<?php
$config['api_username'] = "iambrs_1298074268_biz_api1.gmail.com";
$config['api_password'] = "1298074286";
$config['api_signature'] = "Awe05O9DgD-XyAL3-HsFoqNs..1VAOncRYkwEN.LCh-94svEO5c0i0Ar ";
return $config;

View File

@ -0,0 +1,15 @@
<?php
$config['api_cid'] = "1000001";
$config['api_username'] = "teststore";
$config['api_password'] = "psigate1234";
$config['api_recurring_password'] = "testpass";
$config['api_endpoint_test'] = "https://dev.psigate.com:7989/Messenger/XMLMessenger";
$config['api_endpoint_production'] = ""; //YOU SHOULD RECEIVE THIS FROM PSIGATE AFTER SIGNING UP
/*
@TODO Recurring Billing Implementation
$config['api_recurring_endpoint_test'] = "https://dev.psigate.com:8645/Messenger/AMMessenger";
$config['api_recurring_endpoint_production'] = ""; //YOU SHOULD RECEIVE THIS FROM PSIGATE AFTER SIGNING UP
*/
return $config;

View File

@ -0,0 +1,9 @@
<?php
$config['api_application_login'] = "cfpayments.codeigniter.local";
$config['api_connection_ticket'] = "TGT-172-3nhcl7svhgXazfMDkaC_QQ";
$config['api_endpoint_test'] = "https://merchantaccount.ptc.quickbooks.com/j/AppGateway";
$config['api_endpoint_production'] = "https://merchantaccount.quickbooks.com/j/AppGateway";
$config['api_qbxml'] = 'qbmsxml version="4.5"';
return $config;

View File

@ -0,0 +1,5 @@
<?php
$config['api_key'] = 'hbsNLQGp21CVK4Cs1dOLXZQ38BbB37rR';
return $config;

102
vendor/php-payments/config/payments.php vendored Executable file
View File

@ -0,0 +1,102 @@
<?php
/**
* Set mode to test or production. This determines which endpoints are used.
*
* DEFAULT: test
*/
$config['mode'] = 'test';
/**
* Force Secure Connection. Should only be turned to FALSE if testing.
*
* DEFAULT: TRUE
*/
$config['force_secure_connection'] = FALSE;
/**
* Sets the language to be used
*/
$config['language'] = 'english';
/**
* Response Codes
* 000 - Local Failure
* 011 - Failure at Payment Gateway
* 100 - Success!
*/
$config['response_codes'] = array (
'not_a_module' => '000',
'invalid_input' => '000',
'not_a_method' => '000',
'required_params_missing' => '000',
'invalid_xml' => '000',
'authentication_failure' => '011',
//Payment Methods
'authorize_payment_success' => '100',
'authorize_payment_local_failure' => '000',
'authorize_payment_gateway_failure' => '011',
'oneoff_payment_success' => '100',
'oneoff_payment_local_failure' => '000',
'oneoff_payment_gateway_failure' => '011',
'oneoff_payment_button_success' => '100',
'oneoff_payment_button_local_failure' => '000',
'oneoff_payment_button_gateway_failure' => '011',
'reference_payment_success' => '100',
'reference_payment_local_failure' => '000',
'reference_payment_gateway_failure' => '011',
'capture_payment_success' => '100',
'capture_payment_local_failure' => '000',
'capture_payment_gateway_failure' => '011',
'void_payment_success' => '100',
'void_payment_local_failure' => '000',
'void_payment_gateway_failure' => '011',
'void_refund_success' => '100',
'void_refund_local_failure' => '000',
'void_refund_gateway_failure' => '011',
'get_transaction_details_success' => '100',
'get_transaction_details_local_failure' => '000',
'get_transaction_details_gateway_failure' => '011',
'change_transaction_status_success' => '100',
'change_transaction_status_local_failure' => '000',
'change_transaction_status_gateway_failure' => '011',
'refund_payment_success' => '100',
'refund_payment_local_failure' => '000',
'refund_payment_gateway_failure' => '011',
'search_transactions_success' => '100',
'search_transactions_local_failure' => '000',
'search_transactions_gateway_failure' => '011',
'recurring_payment_success' => '100',
'recurring_payment_local_failure' => '000',
'recurring_payment_gateway_failure' => '011',
'get_recurring_profile_success' => '100',
'get_recurring_profile_local_failure' => '000',
'get_recurring_profile_gateway_failure' => '011',
'suspend_recurring_profile_success' => '100',
'suspend_recurring_profile_local_failure' => '000',
'suspend_recurring_profile_gateway_failure' => '011',
'activate_recurring_profile_success' => '100',
'activate_recurring_profile_local_failure' => '000',
'activate_recurring_profile_gateway_failure' => '011',
'cancel_recurring_profile_success' => '100',
'cancel_recurring_profile_local_failure' => '000',
'cancel_recurring_profile_gateway_failure' => '011',
'recurring_bill_outstanding_success' => '100',
'recurring_bill_outstanding_local_failure' => '000',
'recurring_bill_outstanding_gateway_failure' => '011',
'update_recurring_profile_success' => '100',
'update_recurring_profile_local_failure' => '000',
'update_recurring_profile_gateway_failure' => '011',
'token_create_success' => '100',
'token_create_local_failure' => '000',
'token_create_gateway_failure' => '011',
'customer_create_success' => '100',
'customer_create_local_failure' => '000',
'customer_create_gateway_failure' => '011',
'customer_charge_success' => '100',
'customer_charge_local_failure' => '000',
'customer_create_gateway_failure' => '011'
);
return $config;

4
vendor/php-payments/documentation/README.md vendored Executable file
View File

@ -0,0 +1,4 @@
# Generating Documentation
Generating documentation is easy. Simply cd into the documentation/dox folder and type doxgen.php. Current HTML documentation will be generated in documentation/html

View File

@ -0,0 +1,20 @@
<div class="page-header">
<h1>Easily add your own driver to PHP-Payments</h1>
</div>
<div class="row-fluid">
<div class="span8">
<h3>Video - Creating Drivers</h3>
<p>Being uploaded!</p>
<h3>Why create your own driver?</h3>
<p>Because you think the idea of an open source PHP project supporting many payment gateways with one API is sexy as hell. Because you're not a douche. Because you like writing code and want to sharpen your teeth with payment APIs. These, and many others, are all excellent reasons to contribute to PHP-Payments.</p>
<h3>Successfully integrating a new driver into PHP-Payments is all about preparation. You'll need to complete the following pre-requisites:</h3>
<ul>
<li>Have a testing account available for the gateway you want to integrate.</li>
<li>Have a github profile and create your own fork of the project.</li>
<li>Carefully examine which methods are supported by your gateway and what format they expect interaction to be in.</li>
<li>Find out if your gateway has an SDK. If it's any good, you may be able to just drop it into the vendor folder and write an interface for it.</li>
</ul>
<h3>Next, make sure you understand how PHP-Payments works.</h3>
<p>PHP-Payments relies heavily on __call magic methods and matching methods and keys via arrays. Taking this approach allowed us to eliminate duplicate code and keep an extremely clear detail of what methods and parameters were supported by each method within each gateway, within the driver itself. When you instantiate PHP-Payments, the library first autoloads some helper classes such as a utility class, a response class, a request class, the payment driver abstract class. When you call a method, PHP-Payments make sure the driver and method you're using exists, and via the method_map() function which is implemented in each driver, ensures you've submitted the required keys for that method. If all checks out, the request can be made.</p>
<h3>Hopefully you have a good feel for how PHP-Payments works. If you need any help, you can always create an issue on Github or add Calvin on Skype. His handle is halcyon-sky.</h3>
</div>

View File

@ -0,0 +1,28 @@
<div class="page-header">
<h1>Thank you to all the following who have made significant contributions to PHP-Payments</h1>
</div>
<div class="row-fluid">
<div class="span8">
<div class="row-fluid">
<div class="span3">
<h3>Calvin Froedge</h3>
<p>Calvin started writing code for a freelance project in February of 2012 that needed an integration with PayPal Payments Pro. Finding that the PayPal SDK was not that great, and thinking "payment gateway implementations should be an abstraction - not an involved integration project", Calvin started writing code for a CodeIgniter package. When the package was released, it only supported PayPal Payments Pro and was very simple.</p>
<p>Follow Calvin on Twitter: <a href="http://twitter.com/calvinfroedge">@calvinfroedge</a></p>
</div>
<div class="span3">
<h3>Phil Sturgeon</h3>
<p>Phil provided early support, encouraging Calvin (who was new to PHP) to continue developing the code and to package the code as a CodeIgniter spark. When Phil made the call for speakers for the first CodeIgniter on tour conference, Calvin asked to speak and promised to radically improve his payments class (which by then supported 3 gateways). Amazingly, and probably against his better judgement, Phil obliged. PHP-Payments would not exist had Phil not taken a chance on an unproven developer.</p>
<p>Follow Phil on Twitter: <a href="http://twitter.com/philsturgeon">@philsturgeon</a></p>
</div>
<div class="span3">
<h3>Joel Kallman</h3>
<p>Joel was the first person to fork the spark CodeIgniter payments and contribute a gateway to the codebase. He is responsible for the BluePay payments support. He has also contributed extremely valuable ideas on how to improve the code and has made great feature suggestions.</p>
<p>Follow Joel on Twitter: <a href="http://twitter.com/eclarian">@eclarian</a></p>
</div>
<div class="span3">
<h3>James Riordon</h3>
<p>James made the first donation to CodeIgniter payments. He needed a payment integration for his own project and CodeIgniter payments met his need. His gift was a huge confidence booster and was most appreciated.</p>
<p>Follow James on Twitter: <a href="http://twitter.com/outofcontrol">@outofcontrol</a></p>
</div>
</div>
</div>

View File

@ -0,0 +1,7 @@
<div class="page-header">
<h1>PHP-Payments supports x gateways and x methods</h1>
</div>
<div class="row-fluid">
<div class="span8">
</div>

View File

@ -0,0 +1,87 @@
<div class="page-header">
<h1>Gateway specific method support in PHP-Payments</h1>
</div>
<div class="row-fluid">
<div class="span8">
<?php
$dir = dirname(dirname(dirname(__DIR__))).'/lib/';
$ddir = $dir.'payment_drivers/';
include $dir.'payment_driver.php';
include $dir.'payment_utility.php';
?>
<ul>
<?php
$classes = array();
foreach(scandir($ddir) as $k=>$v)
{
if($v[0] != '.')
{
include $ddir.$v;
$class = str_replace('.php', '', $v);
$ex = explode('_', $class);
foreach($ex as $k=>$v)
{
$ex[$k] = ucfirst($v);
}
$class_name = implode("_", $ex);
$classes[$class] = $class_name;
?>
<li><a href="#<?php echo $class;?>"><?php echo $class_name;?></a></li>
<?php
}
}
?>
</ul>
<?php
foreach($classes as $class_key=>$class_name)
{
?>
<div id="<?php echo $class_key;?>">
<h2><?php echo $class_name;?></h2>
<?php
$i = @new $class_name(array());
$methods = @$i->method_map();
foreach($methods as $method=>$p)
{
?>
<h3><?php echo $method;?></h3>
<h4>Requred Params:</h4>
<ul>
<?php
foreach($p['required'] as $k=>$v)
{
?>
<li><?php echo $v;?></li>
<?php
}
?>
</ul>
<?php
if(isset($p['keymatch']))
{
?>
<h4>Available Params:</h4>
<ul>
<?php
foreach($p['keymatch'] as $k=>$v)
{
?>
<li><?php echo $k;?></li>
<?php
}
?>
</ul>
<?php
}
}
?>
</div>
<?php
}
?>
</div>

View File

@ -0,0 +1,14 @@
<div class="page-header">
<h1>PHP-Payments is coming to a framework near you!</h1>
</div>
<div class="row-fluid">
<div class="span8">
<div class="row-fluid">
<!--<h2>CodeIgniter</h2>
<p>CodeIgniter is where it all began! The original CodeIgniter spark supported 8 gateways and was installed more than 500 times before being converted to PHP-Payments. The spark now sits on top of the PHP-Payments codebase, and you can <a href="http://getsparks.org/packages/codeigniter-payments/versions/HEAD/show" target="_blank">install via sparks.</a></p>
<h2>FuelPHP</h2>
<p>Download the <a href="https://github.com/calvinfroedge/FuelPay" target="_blank">FuelPHP Payments package (FuelPay) from Github</a></p>-->
<h2>Coming Soon!</h2>
</div>
</div>

View File

@ -0,0 +1,31 @@
<div class="page-header">
<h1>PHP-Payments was built to allow you to use one API for handling many payment integrations.</h1>
</div>
<div class="row-fluid">
<div class="span8">
<h2>Five Lines of Code to Integrate</h2>
<pre>
&lt;?php
include('/path/to/payments/payments.php');
$p = new PHP_Payments;
$config = Payment_Utility::load('config', '/path/to/your/gateway/config');
$params = array('cc_number' =&gt; 4111111111111111, 'amt' =&gt; 35.00, 'cc_exp' =&gt; '022016', 'cc_code' =&gt; '203');
$response = $p-&gt;oneoff_payment('name_of_payment_driver', $params, $config);
</pre>
<div class="row-fluid">
<div class="span6">
<h2>Framework Agnostic</h2>
<p>Though the project began as a CodeIgniter spark, PHP-Payments is now a framework agnostic API. Writing an interface to bring it to your framework is easy, and your framework could already be supported. Check out the <a href="/frameworks.html">frameworks page</a> for more info.</p>
</div>
<div class="span6">
<h2>Get PHP-Payments</h2>
<p>Hot and fresh.</p>
<a href="https://github.com/calvinfroedge/PHP-Payments/zipball/master" class="btn btn-large">Download .zip</a>
<a href="https://github.com/calvinfroedge/PHP-Payments" class="btn btn-large">Fork Me on Github</a>
</div>
</div>
</div>

View File

@ -0,0 +1,61 @@
<div class="page-header">
<h1>PHP-Payments supports many gateways and payment methods</h1>
</div>
<div class="row-fluid">
<div class="span8">
<h2>All Methods with Example Params</h2>
<p>Please note that not all drivers implement each of these methods. In addition, the params available in each method may not be used in a particular driver's implementation. If you use a param in a request which is not used, it will appear in your error log, but will not create any ill effects in the request - it simply will not be sent to the gateway.</p>
<?php
$dir = dirname(dirname(dirname(__DIR__))).'/lib/';
$mdir = $dir.'payment_methods/';
include $dir.'payment_method.php';
foreach(scandir($mdir) as $k=>$v)
{
if($v[0] != '.')
{
include $mdir.$v;
$class = str_replace('.php', '', $v);
$ex = explode('_', $class);
foreach($ex as $k=>$v)
{
$ex[$k] = ucfirst($v);
}
$class_name = implode("_", $ex);
$class_instance = new $class();
?>
<h3><?php echo $class;?></h3>
<h4>Parameters:</h4>
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>#</th>
<th>Parameter</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<?php
$pcount = 0;
foreach($class_instance->get_params() as $pk=>$pv)
{
++$pcount;
?>
<tr>
<td><?php echo $pcount;?></td>
<td><?php echo $pk;?></td>
<td><?php echo $pv;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
}
?>
</div>

View File

@ -0,0 +1,37 @@
<div class="page-header">
<h1>PHP-Payments supports x gateways and x methods</h1>
</div>
<div class="row-fluid">
<div class="span8">
<h2>Basic Usage</h2>
<pre>
include('/path/to/lib/payments.php');
$payments = new PHP_Payments;
$config = Payment_Utility::load('config', '/path/to/config/file'); //You can do this or you can make this an array. Config file is recommended since configuration needs differ by gateway.
//Make the call
$response = $payments-&gt;payment_action('gateway_name', $params, $config);
</pre>
<h2>Responses</h2>
<p>There are two types of responses returned, local responses and gateway responses. If a method is not supported, required params are missing, a gateway does not exist, etc., a local response will be returned. This prevents the transaction from being sent to the gateway and the gateway telling you 3 seconds later there is something wrong with your request.</p>
<p>Accessing response properties looks like this:</p>
<pre>
$status = $response-&gt;status;
</pre>
<p>Gateway responses will usually have a full response from the gateway, and on failure a 'reason' property in the details object:</p>
<pre>
$gatway_response = $response-&gt;details;
$failure_reason = $response-&gt;reason;
</pre>
</div>

View File

@ -0,0 +1,15 @@
<?php
$output_dir = dirname(__DIR__).'/html/';
$content_dir = (__DIR__).'/content/';
$template = (__DIR__).'/template.php';
$files = scandir($content_dir);
foreach($files as $file)
{
if($file[0] !== '.')
{
$output_file = $output_dir . str_replace('.php', '.html', $file);
exec("php $template $file > $output_file");
}
}

View File

@ -0,0 +1,14 @@
<?php
$page = $argv[1];
include('template/head.php');
include('template/header.php');
?>
<div class="container-fluid">
<?php
$page_include = (__DIR__).'/content/'.$page;
include($page_include);
include('template/sidebar.php');
?>
</div>
<?php
include('template/footer.php');

View File

@ -0,0 +1,2 @@
</body>
</html>

View File

@ -0,0 +1,6 @@
<html>
<head>
<link href="assets/bootstrap/docs/assets/css/bootstrap.css" type="text/css" rel="stylesheet" />
<link href="assets/style.css" type="text/css" rel="stylesheet" />
</head>
<body>

View File

@ -0,0 +1,32 @@
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="brand" href="/index.html">
&lt;?php $payments; ?&gt;
</a>
<ul class="nav pull-right">
<li class="<?php echo ($page == 'index.php') ? 'active' : '';?>">
<a href="/index.html">Overview</a>
</li>
<li class="<?php echo ($page == 'contributors.php') ? 'active' : '';?>">
<a href="/contributors.html">Contributors</a>
</li>
<!--<li class="<?php echo ($page == 'frameworks.php') ? 'active' : '';?>">
<a href="/frameworks.html">Frameworks</a>
</li>-->
<li class="<?php echo ($page == 'usage.php') ? 'active' : '';?>">
<a href="/usage.html">Usage</a>
</li>
<li class="<?php echo ($page == 'methods.php') ? 'active' : '';?>">
<a href="/methods.html">Methods</a>
</li>
<li class="<?php echo ($page == 'drivers.php') ? 'active' : '';?>">
<a href="/drivers.html">Driver Specific Documentation</a>
</li>
<li class="<?php echo ($page == 'add_driver.php') ? 'active' : '';?>">
<a href="/add_drivers.html">Adding Drivers</a>
</li>
</ul>
</div>
</div>
</div>

View File

@ -0,0 +1,7 @@
<div class="span4">
<h2>Support PHP-Payments</h2>
<p>This stuff takes a lot of hard work. To date, we've logged hundreds of hours on this project, and sadly free code doesn't pay bills.</p>
<a href="https://flattr.com/submit/auto?user_id=calvinfroedge&url=http://github.com/calvinfroedge/codeigniter-payments&title=Codeigniter%20Payments&language=en_GB&tags=github&category=software" class="btn btn-large btn-primary">Make a Donation</a>
<a href="/add_drivers.html" class="btn btn-large">Contribute Code</a>
</div>
</div>

View File

@ -0,0 +1 @@
body { margin-top:80px;}

View File

@ -0,0 +1,39 @@
<?php
/**
* Response Details
*
* Additional details to help in debugging
*/
$lang = array (
'invalid_billing_period' => 'Billing period must be formatted as "Month", "Date", "Year" or "Week."',
'invalid_date_format' => 'Dates must be provided in MMYYYY format.',
'invalid_amount_format' => 'Money amounts must be formatted in decimal format, rounded to the hundredths place, ie 30.00',
'missing_ip_address' => 'IP address is required but was not provided in the request',
'missing_cc_type' => 'Credit Card Type is required but was not provided in the request',
'missing_cc_number' => 'Credit Card Number is required but was not provided in the request',
'missing_cc_details' => 'Full Credit Card details must be provided.',
'missing_cc_exp' => 'Credit Card Expiration is required but was not provided in the request',
'missing_cc_code' => 'Credit Card code is required but was not provided in the request',
'missing_email' => 'Email is required but was not provided in the request',
'missing_street' => 'Street is required but was not provided in the request',
'missing_city' => 'City is required but was not provided in the request',
'missing_state' => 'State is required but was not provided in the request',
'missing_country' => 'Country is required but was not provided in the request',
'missing_postal_code' => 'Postal code is required but was not provided in the request',
'missing_amt' => 'Amount is required but was not provided in the request',
'missing_identifier' => 'An identifier (such as a previous transaction ID) is required but was not provided in the request',
'missing_action' => 'An action to be taken by the payment gateway is required but was not provided in the request',
'missing_refund_type' => 'The type of refund you are issuing is required but was not provided in the request',
'missing_start_date' => 'Start date is required but was not provided in the request',
'missing_profile_start_date'=> 'Profile start date is required but was not provided in the request',
'missing_billing_period' => 'Billing period is required but was not provided in the request',
'missing_billing_frequency' => 'Billing frequency is required but was not provided in the request',
'missing_desc' => 'Description (desc) is required but was not provided in the request',
'missing_first_name' => 'First name is required but was not provided in the request',
'missing_last_name' => 'Last name is required but was not provided in the request',
'missing_currency_code' => 'Currency is required but was not provided in the request',
'no_details' => 'No further details provided',
'is_not_a_param' => 'Is not a valid parameter for this method',
);
return $lang;

View File

@ -0,0 +1,81 @@
<?php
/**
* Response Messages
*
* These messages return something that could be meaningful in a log message or to a user.
*/
$lang = array (
'not_a_module' => 'The payment module provided is not valid.',
'invalid_input' => 'The input provided is not in the correct format',
'invalid_date_params' => 'Units of time must be called "Year", "Month", or "Day"',
'not_a_method' => 'The method called does not exist',
'required_params_missing' => 'Some required parameters have been omitted.',
'invalid_xml' => 'A response was returned from the gateway, but we cannot parse it as XML. The string has been included',
'authentication_failure' => 'Application failed to authenticate with the payment gateway. Cannot proceed.',
//Payment Methods
'authorize_payment_success' => 'The authorization was successful.',
'authorize_payment_local_failure' => 'The authorization was not sent to the payment gateway because it failed validation.',
'authorize_payment_gateway_failure' => 'The authorization was declined by the payment gateway.',
'oneoff_payment_success' => 'The payment was successful.',
'oneoff_payment_local_failure' => 'The payment could not be sent to the payment gateway because it failed local validation.',
'oneoff_payment_gateway_failure' => 'The payment was declined by the payment gateway.',
'oneoff_payment_button_success' => 'The payment button was generated successfully',
'oneoff_payment_button_local_failure' => 'There was a problem generating the payment button',
'oneoff_payment_button_gateway_failure' => 'The payment button could not be generated',
'reference_payment_success' => 'The payment was successful.',
'reference_payment_local_failure' => 'The payment could not be sent to the payment gateway because it failed local validation.',
'reference_payment_gateway_failure' => 'The payment was declined by the payment gateway.',
'capture_payment_success' => 'The payment capture was successful.',
'capture_payment_local_failure' => 'The payment capture could not be sent to the payment gateway because it failed local validation.',
'capture_payment_gateway_failure' => 'The payment capture was declined by the gateway.',
'void_payment_success' => 'The payment was voided successfully.',
'void_refund_success' => 'The return was voided successfully.',
'void_payment_local_failure' => 'The void request could not be sent to the payment gateway because it failed local validation.',
'void_payment_gateway_failure' => 'The void request was rejected by the payment gateway.',
'void_refund_gateway_failure' => 'The void return request was rejected by the payment gateway.',
'get_transaction_details_success' => 'Transaction details returned successfully.',
'get_transaction_details_local_failure' => 'Transaction details were not requested from the payment gateway because local validation failed.',
'get_transaction_details_gateway_failure' => 'Transaction details could not be retrieved by the payment gateway.',
'change_transaction_status_success' => 'Transaction status was changed successfully.',
'change_transaction_status_local_failure' => 'Transaction status could not be requested from the payment gateway because local validation failed.',
'change_transaction_status_gateway_failure' => 'Transaction status could not retrieved from the payment gateway.',
'refund_payment_success' => 'Refund has been made.',
'refund_payment_local_failure' => 'Refund request could not be sent to the payment gateway because local validation failed.',
'refund_payment_gateway_failure' => 'Refund request was declined by the payment gateway.',
'search_transactions_success' => 'Transaction information successfully retrieved.',
'search_transactions_local_failure' => 'Transaction search request could not be sent to the payment gateway because local validation failed',
'search_transactions_gateway_failure' => 'Transaction search failed.',
'recurring_payment_success' => 'Recurring payments successfully initiated.',
'recurring_payment_local_failure' => 'Recurring payment request could not be sent to the payment gateway because local validation failed.',
'recurring_payment_gateway_failure' => 'Recurring payment was declined by the payment gateway.',
'get_recurring_profile_success' => 'Recurring profile successfully retrieved.',
'get_recurring_profile_local_failure' => 'Recurring profile could not be retrieved from the payment gateway because local validation failed.',
'get_recurring_profile_gateway_failure' => 'Recurring profile could not be retrieved by the payment gateway.',
'suspend_recurring_profile_success' => 'Recurring profile successfully suspended.',
'suspend_recurring_profile_local_failure' => 'Recurring profile suspension request could not be sent to the payment gateway because local validation failed.',
'suspend_recurring_profile_gateway_failure' => 'Recurring profile could not be suspended by the payment gateway.',
'activate_recurring_profile_success' => 'Recurring profile successfully activated.',
'activate_recurring_profile_local_failure' => 'Recurring profile activation request could not be sent to the payment gateway because local validation failed.',
'activate_recurring_profile_gateway_failure' => 'Recurring profile could not be activated by the payment gateway.',
'cancel_recurring_profile_success' => 'Recurring profile cancelled successfully.',
'cancel_recurring_profile_local_failure' => 'Recurring profile cancellation request could not be sent to the payment gateway because local validation failed.',
'cancel_recurring_profile_gateway_failure' => 'Recurring profile could not be cancelled by the payment gateway.',
'recurring_bill_outstanding_success' => 'Outstanding bill amount successfully billed.',
'recurring_bill_outstanding_local_failure' => 'Outstanding bill request could not be sent to the payment gateway because local validation failed.',
'recurring_bill_outstanding_gateway_failure' => 'Outstanding bill request was rejected by the payment gateway.',
'update_recurring_profile_success' => 'Recurring profile updated successfully.',
'update_recurring_profile_local_failure' => 'Recurring profile update request could not be sent to the payment gateway because local validation failed.',
'update_recurring_profile_gateway_failure' => 'Recurring profile update was rejected by the payment gateway.',
'token_create_success' => 'Card tokenization successful.',
'token_create_local_failure' => 'Card tokenization could not be attempted because validation failed locally.',
'token_create_gateway_failure' => 'Card tokenization failed at the payment gateway.',
'customer_create_success' => 'Customer creation successful',
'customer_create_local_failure' => 'Customer creation could not be attempted because validation failed locally.',
'customer_create_gateway_failure' => 'Customer creation failed at the payment gateway.',
'customer_charge_success' => 'Customer charge successful',
'customer_charge_local_failure' => 'Customer charge could not be attempted because validation failed locally.',
'customer_chage_gateway_failure' => 'Customer charge failed at the payment gateway.'
);
return $lang;

64
vendor/php-payments/lib/payment_driver.php vendored Executable file
View File

@ -0,0 +1,64 @@
<?php
abstract class Payment_Driver
{
abstract public function __construct($config);
/**
* Call Magic Method Must Be Implemented
*/
abstract public function __call($method, $params);
/**
* Maps Methods to Details Particular to Each Request for that Method
*/
abstract public function method_map();
/**
* Builds the Request
*/
abstract protected function _build_request($params);
/**
* Parse the Response and then Delegate to the Response Object
*/
abstract protected function _parse_response($response);
/**
* Returns a List of Drivers
*/
public static function get_drivers()
{
$drivers = array();
/*
* Humanize the Driver Name
*/
function humanize($segs)
{
$prepped = array();
foreach($segs as $v) $prepped[] = ucfirst($v);
return trim(ucfirst(str_replace('Driver', '', implode(' ', $prepped))));
}
/*
* Driverize the Driver Name
*/
function driverize($segs)
{
foreach($segs as &$v) ucfirst($v);
return str_replace('_driver', '', implode('_', $segs));
}
foreach(scandir(__DIR__.'/payment_drivers') as $driver)
{
if($driver[0] != '.')
{
$ex = explode('_', str_replace('.php', '', $driver));
$drivers[driverize($ex)] = humanize($ex);
}
}
return $drivers;
}
}

View File

@ -0,0 +1,148 @@
<?php
class Amazon_SimplePay_Driver extends Payment_Driver
{
/**
* The PHP-Payments Library Method Being Utilized
*/
private $_lib_method;
/**
* The Config Array
*/
private $_config;
/**
* If the Request Returns a Button
*/
private $_is_button;
/**
* The Mode. Either "sandbox" or "prod"
*/
private $_mode;
/**
* Class Constructor
*/
public function __construct($config)
{
$this->_mode = ($config['mode'] == 'test') ? 'sandbox' : 'prod';
$this->_config = $config;
}
/**
* The Caller Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
try{
$request = $this->_build_request($args);
}
catch(Exception $e){
return Payment_Response::instance()->local_response(
'failure',
$e->getMessage()
);
}
return $this->_parse_response($request);
}
/**
* Maps PHP-Payments Keys to Gateway
*/
public function method_map()
{
$map = array(
'oneoff_payment_button' => array(
'api' => 'ButtonGenerator',
'method' => 'GenerateForm',
'required' => array(
'amt',
'desc',
'currency_code'
),
'keymatch' => array(
'amount' => 'amount',
'desc' => 'description',
'identifier' => 'referenceId'
),
'static' => array(
'signature_method' => 'HmacSHA256',
'abandon_url' => $this->_config['abandon_url'],
'return_url' => $this->_config['return_url'],
'immediate_return' => $this->_config['immediate_return'],
'process_immediate' => $this->_config['process_immediate'],
'ipn_url' => $this->_config['ipn_url'],
'collect_shipping_address' => $this->_config['collect_shipping_address']
)
)
);
return $map;
}
/**
* Build the Request
*
* @param array Params array
* @return mixed array for requests, strings for buttons
*/
protected function _build_request($params)
{
$map = $this->method_map();
$l = $this->_lib_method;
$api = $map[$l]['api'];
$method = $map[$l]['method'];
$static = $map[$l]['static'];
if($api == 'ButtonGenerator')
{
Payment_Utility::load('file', 'vendor/amazon_simplepay/ButtonGenerationWithSignature/src/ButtonGenerator');
$this->_is_button = true;
ob_start();
$api::$method(
$this->_config['access_key'],
$this->_config['secret_key'],
$params['currency_code'] . ' ' . $params['amt'],
$params['desc'],
(isset($params['identifier'])) ? $params['identifier'] : '',
$static['immediate_return'],
$static['return_url'],
$static['abandon_url'],
$static['process_immediate'],
$static['ipn_url'],
$static['collect_shipping_address'],
$static['signature_method'],
$this->_mode
);
$string = ob_get_clean();
return $string;
}
}
/**
* Parse the Response
*
* @param array Raw response
* @return object Payment_Response
*/
protected function _parse_response($response)
{
if($this->_is_button)
{
return Payment_Response::instance()->local_response(
'success',
$this->_lib_method.'_success',
$response
);
}
}
}

View File

@ -0,0 +1,620 @@
<?php
class Authorize_Net_Driver extends Payment_Driver
{
/**
* Endpoint to Send the Query To
*/
private $_endpoint;
/**
* The particular API which is being used
*/
private $_api;
/**
* The particular API method which is being used
*/
private $_api_method;
/**
*
*/
private $_lib_method;
/**
* Stores Settings for the Transaction
*/
private $_settings;
/**
* The Constructor Function
*/
public function __construct($config)
{
$this->_settings = array(
'xml_version' => '1.0',
'encoding' => 'utf-8',
'xml_schema' => 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"',
'email_customer' => (isset($config['email_customer'])) ? $config['email_customer'] : TRUE
);
foreach($config as $k=>$v)
{
$this->_settings[$k] = $v;
}
}
/**
* Call Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
$this->_endpoint = ($this->_settings['mode'] !== 'test') ? 'https://secure.authorize.net/gateway/transact.dll' : 'https://apitest.authorize.net/xml/v1/request.api';
$method_map = $this->method_map();
$this->_api = $method_map[$method]['api'];
$this->_api_method = (isset($method_map[$method]['method'])) ? $method_map[$method]['method'] : '';
$request_string = $this->_build_request($args);
$response_raw = Payment_Request::curl_request($this->_endpoint, $request_string);
return $this->_parse_response($response_raw);
}
/**
* Maps PHP-Payments Methods to Details Particular to Each Request for that Method
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'createTransactionRequest',
'method' => 'authCaptureTransaction',
'required' => array(
'cc_type',
'cc_number',
'cc_exp',
'amt'
)
),
'authorize_payment' => array(
'api' => 'createTransactionRequest',
'method' => 'authOnlyTransaction',
'required' => array(
'cc_type',
'cc_number',
'cc_exp',
'amt'
)
),
'capture_payment' => array(
'api' => 'createTransactionRequest',
'method' => 'priorAuthCaptureTransaction',
'required' => array(
'identifier'
)
),
'void_payment' => array(
'api' => 'createTransactionRequest',
'method' => 'voidTransaction',
'required' => array(
'identifier'
)
),
'get_transaction_details' => array(
'api' => 'getTransactionDetailsRequest',
'required' => array(
'identifier'
)
),
'refund_payment' => array(
'api' => 'createTransactionRequest',
'method' => 'refundTransaction',
'required' => array(
'identifier',
'cc_number',
'cc_exp',
'amt'
)
),
'recurring_payment' => array(
'api' => 'ARBCreateSubscriptionRequest',
'required' => array(
'first_name',
'last_name',
'profile_start_date',
'billing_period',
'billing_frequency',
'total_billing_cycles',
'amt',
'cc_type',
'cc_exp',
'cc_number',
'country_code',
'street',
'city',
'state',
'postal_code'
)
),
'get_recurring_profile' => array(
'api' => 'ARBGetSubscriptionStatusRequest',
'required' => array(
'identifier'
)
),
'update_recurring_profile' => array(
'api' => 'ARBUpdateSubscriptionRequest',
'required' => array(
'identifier',
'cc_number',
'cc_exp'
)
),
'cancel_recurring_profile' => array(
'api' => 'ARBCancelSubscriptionRequest',
'required' => array(
'identifier'
)
)
);
return $map;
}
/**
* Builds the Request
*/
protected function _build_request($params)
{
$nodes = array();
$nodes['merchantAuthentication'] = array(
'name' => $this->_settings['api_username'],
'transactionKey' => $this->_settings['api_password'],
);
if($this->_api == 'createTransactionRequest')
{
$nodes['transactionRequest'] = $this->_transaction_fields($params);
$nodes['transactionRequest']['transactionSettings'] = $this->_transaction_settings();
}
if($this->_api == 'getTransactionDetailsRequest')
{
$nodes['transId'] = $params['identifier'];
}
if($this->_api == 'ARBGetSubscriptionStatusRequest' OR $this->_api == 'ARBUpdateSubscriptionRequest' OR $this->_api == 'ARBCancelSubscriptionRequest')
{
$nodes['subscriptionId'] = $params['identifier'];
}
if($this->_api == 'ARBCreateSubscriptionRequest' OR $this->_api == 'ARBUpdateSubscriptionRequest')
{
$nodes['subscription'] = $this->_transaction_fields($params);
}
$request_string = Payment_Request::build_xml_request(
$this->_settings['xml_version'],
$this->_settings['encoding'],
$nodes,
$this->_api,
$this->_settings['xml_schema']
);
return $request_string;
}
/**
* Sets transaction settings
* @return array Array of transaction settings
*/
protected function _transaction_settings()
{
return array(
'repeated_key' => array(
'name' => 'setting',
'wraps' => FALSE,
'values' => array(
array(
'settingName' => 'allowPartialAuth',
'settingValue'=> TRUE,
),
array(
'settingName' => 'emailCustomer',
'settingValue' => $this->_settings['email_customer']
),
array(
'settingName' => 'recurringBilling',
'settingValue' => FALSE
),
array(
'settingName' => 'testRequest',
'settingValue' => ($this->_settings['mode'] == 'test') ? true : false
)
)
)
);
}
/**
* Sets fields to a request
* @param string The transaction type
* @param array Array of params
* @return array Array of fields
*/
protected function _transaction_fields($params)
{
$fields = array();
if(!is_null($this->_api_method))
{
$fields['transactionType'] = $this->_api_method;
}
if($this->_api == 'ARBCreateSubscriptionRequest')
{
$fields['name'] = $params['first_name'] . ' ' . $params['last_name'];
if($params['billing_period'] != 'Month' && $params['billing_period'] != 'Day')
{
return Payment_Response::instance()->return_response(
'Failure',
'invalid_date_params',
'local_response'
);
}
if($params['billing_period'] == 'Month')
{
$params['billing_period'] = 'months';
}
if($params['billing_period'] == 'Day')
{
$params['billing_period'] = 'days';
}
$fields['paymentSchedule'] = array(
'interval' => array(
'length' => $params['billing_frequency'],
'unit' => $params['billing_period'],
),
'startDate' => $params['profile_start_date'],
'totalOccurrences' => $params['total_billing_cycles']
);
if(isset($params['trial_billing_cycles']) AND isset($params['trial_amt']))
{
$fields['paymentSchedule']['interval']['trialOccurrences'] = $params['trial_billing_cycles'];
$fields['trialAmount'] = $params['trial_amt'];
}
}
if(isset($params['amt']))
{
$fields['amount'] = $params['amt'];
}
if(isset($params['cc_number']))
{
$fields['payment']['creditCard'] = $this->_add_payment('credit_card', $params);
}
if(isset($params['identifier']) AND $this->_api != 'ARBUpdateSubscriptionRequest')
{
$fields['refTransId'] = $params['identifier'];
}
$fields['order'] = $this->_build_order_fields($params);
if(isset($params['tax_amt']))
{
$fields['tax'] = array(
'amount' => $params['tax_amt']
);
}
if(isset($params['shipping']))
{
$fields['shipping'] = array(
'amount' => $params['shipping_amt']
);
}
if(isset($params['po_num']))
{
$fields['poNumber'] = $params['po_num'];
}
$fields['customer'] = $this->_build_customer_fields($params);
$fields['billTo'] = $this->_build_bill_to_fields($params);
$fields['shipTo'] = $this->_build_ship_to_fields($params);
if(isset($params['ip_address']))
{
$fields['customerIP'] = $params['ip_address'];
}
return $fields;
}
/**
* Builds fields for order node
* @param array Array of params
* @return array Array of fields
*/
protected function _build_order_fields($params)
{
$order = array();
if(isset($params['inv_num']))
{
if(isset($params['desc']))
{
$order = array(
'invoiceNumber' => $params['inv_num'],
'description' => $params['desc']
);
}
else
{
$order = array(
'invoiceNumber' => $params['inv_num']
);
}
}
return $order;
}
/**
* Builds fields for billTo node
* @param array Array of params
* @return array Array of fields
*/
protected function _build_bill_to_fields($params)
{
$bill_to = array();
if(isset($params['first_name']))
{
$bill_to['firstName'] = $params['first_name'];
}
if(isset($params['last_name']))
{
$bill_to['lastName'] = $params['last_name'];
}
if(isset($params['business_name']))
{
$bill_to['company'] = $params['business_name'];
}
if(isset($params['street']))
{
$bill_to['address'] = $params['street'];
}
if(isset($params['city']))
{
$bill_to['city'] = $params['city'];
}
if(isset($params['state']))
{
$bill_to['state'] = $params['state'];
}
if(isset($params['postal_code']))
{
$bill_to['zip'] = $params['postal_code'];
}
if(isset($params['country']))
{
$bill_to['country'] = $params['country'];
}
if(isset($params['phone']))
{
$bill_to['phoneNumber'] = $params['phone'];
}
if(isset($params['fax']))
{
$bill_to['faxNumber'] = $params['fax'];
}
return $bill_to;
}
/**
* Builds fields for customer node
* @param array Array of params
* @return array Array of fields
*/
protected function _build_customer_fields($params)
{
$customer = array();
if(isset($params['email']))
{
$customer['email'] = $params['email'];
}
if(isset($params['phone']))
{
$customer['phoneNumber'] = $params['phone'];
}
if(isset($params['fax']))
{
$customer['faxNumber'] = $params['fax'];
}
}
/**
* Builds fields for shipTo node
* @param array Array of params
* @return array Array of fields
*/
protected function _build_ship_to_fields($params)
{
$ship_to = array();
if(isset($params['ship_to_first_name']))
{
$ship_to['firstName'] = $params['ship_to_first_name'];
}
if(isset($params['ship_to_last_name']))
{
$ship_to['lastName'] = $params['ship_to_last_name'];
}
if(isset($params['ship_to_company']))
{
$ship_to['company'] = $params['ship_to_company'];
}
if(isset($params['ship_to_street']))
{
$ship_to['address'] = $params['ship_to_street'];
}
if(isset($params['ship_to_city']))
{
$ship_to['city'] = $params['ship_to_city'];
}
if(isset($params['ship_to_state']))
{
$ship_to['state'] = $params['ship_to_state'];
}
if(isset($params['ship_to_postal_code']))
{
$ship_to['zip'] = $params['ship_to_postal_code'];
}
if(isset($params['ship_to_country']))
{
$ship_to['country'] = $params['ship_to_country'];
}
return $ship_to;
}
/**
* Add a payment method to a request
* @param string Bank or credit card #
* @param array params
* @return array array
*/
protected function _add_payment($type, $params)
{
if($type === 'credit_card')
{
$card = array();
if(isset($params['cc_number']))
{
$card['cardNumber'] = $params['cc_number'];
}
if(isset($params['cc_exp']))
{
$card['expirationDate'] = $params['cc_exp'];
}
if(isset($params['cc_code']))
{
$card['cardCode'] = $params['cc_code'];
}
return $card;
}
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
protected function _parse_response($xml)
{
//If it failed when being parsed as XML, go ahead and return it
if(isset($xml->status) && $xml->status == 'failure') return $xml;
$details = (object) array();
$as_array = Payment_Utility::arrayize_object($xml);
$result = $as_array['messages']['resultCode'];
if(isset($as_array['transactionResponse']))
{
$identifier = $as_array['transactionResponse']['transId'];
}
if(isset($as_array['subscriptionId']))
{
$identifier = $as_array['subscriptionId'];
}
$timestamp = gmdate('c');
$details->timestamp = $timestamp;
$details->gateway_response = $as_array;
if(isset($identifier) AND strlen($identifier) > 1)
{
$details->identifier = $identifier;
}
if($result == 'Ok')
{
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method.'_success',
$details
);
}
if($result == 'Error')
{
if(isset($as_array['transactionResponse']['errors']['error']['errorText']))
{
$message = $as_array['transactionResponse']['errors']['error']['errorText'];
}
if(isset($as_array['messages']['message']['text']))
{
$message = $as_array['messages']['message']['text'];
}
if(isset($message))
{
$details->reason = $message;
}
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
}

View File

@ -0,0 +1,563 @@
<?php
class Beanstream_Driver
{
/**
* The API method currently being utilized
*/
protected $_api_method;
/**
* The API method currently being utilized
*/
private $_api_endpoint = 'https://www.beanstream.com/scripts/process_transaction.asp?';
/**
* Recurring Endpoint
*/
private $_recurring_endpoint = 'https://www.beanstream.com/scripts/recurring_billing.asp?';
/**
* An array for storing all settings
*/
private $_settings = array();
/**
* The final string to be sent in the http query
*/
private $_http_query;
/**
* Constructor method
*/
public function __construct($config)
{
$this->_api_settings = array(
'merchant_id' => $config['merchant_id'],
'username' => $config['username'],
'password' => $config['password'],
'requestType' => 'BACKEND'
);
$this->config = $config;
}
private function _recurring_settings()
{
$this->_api_endpoint = $this->_recurring_endpoint;
$this->_api_settings['passCode'] = $this->config['passCode'];
$this->_api_settings['merchantId'] = $this->config['merchant_id'];
$this->_api_settings['serviceVersion'] = "1.0";
$this->_api_settings = array_reverse($this->_api_settings);
unset($this->_api_settings['username']);
unset($this->_api_settings['password']);
unset($this->_api_settings['requestType']);
unset($this->_api_settings['merchant_id']);
}
/**
* Magic Method for Making Method Calls
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
$method_map = $this->method_map();
$this->_api_method = array($method_map[$method]['descriptor'] => $method_map[$method]['api']);
$request = (isset($method_map[$method]['method'])) ? $this->_build_request($args, $method_map[$method]['method']) : $this->_build_request($args);
return $this->_handle_query($method, $request);
}
/**
* Build requests
* @param array An array of payment param
* @return void
*/
private function _build_request($params, $transaction_type = NULL)
{
$request = $this->_build_common_fields($params);
//If it's a recurring transaction, but not profile creation
if(strstr($transaction_type, 'recurring') !== FALSE AND $transaction_type !== 'recurring')
{
$this->_recurring_settings();
}
if($transaction_type === 'recurring' OR $transaction_type === 'recurring_modify')
{
$request['trnRecurring'] = '1';
if(isset($params['billing_period']) AND !empty($params['billing_period']))
{
$period = strtolower($params['billing_period']);
$periods = array(
'month' => 'M',
'year' => 'Y',
'week' => 'W',
'day' => 'D'
);
$request['rbBillingPeriod'] = $periods[$period];
}
if(isset($params['billing_frequency']))
{
$request['rbBillingIncrement'] = $params['billing_frequency'];
}
$request['rbCharge'] = $this->config['delay_charge'];
$request['processBackPayments'] = $this->config['bill_outstanding'];
if(isset($params['profile_start_date']))
{
$start = $params['profile_start_date'];
$m = substr($start, 4, 2);
$d = substr($start, -2, 2);
$y = substr($start, 0, 4);
$first_bill = $m.$d.$y;
$request['rbFirstBilling'] = $first_bill;
}
//rbSecondBilling could be integrated as well. It is a field used in combination with rbFirstBilling to prorate a first payment. The second billing date will mark the start of the regular billing schedule. The first customer payment will be prorated based on the difference between the first and second billing date. All subsequent billing intervals will be counted after this date. This value must be formatted as MMDDYYYY.
//Profile end date could also be passed here as rbExpiry
//Did not use rbApplyTax1 or rbApplyTax2
}
if($transaction_type === 'recurring_modify' OR $transaction_type === 'recurring_cancel' OR $transaction_type === 'recurring_suspend' OR $transaction_type === 'recurring_activate')
{
$request['rbAccountID'] = $params['identifier'];
$request['processBackPayments'] = $this->config['bill_outstanding'];
}
if($transaction_type === 'recurring_suspend')
{
$request['rbBillingState'] = 'O';
}
if($transaction_type === 'recurring_activate')
{
$request['rbBillingState'] = 'A';
}
return $request;
}
/**
* Build common fields for the request
* @param array An array of payment param
* @return void
*/
private function _build_common_fields($params)
{
$request = array();
if(isset($this->_api_method['trnType']))
{
$method = $this->_api_method['trnType'];
}
if(isset($this->_api_method['operationType']))
{
$method = $this->_api_method['operationType'];
}
if(isset($params['first_name']) AND isset($params['last_name']))
{
$name = $params['first_name'].' '.$params['last_name'];
$request['ordName'] = $name;
$request['trnCardOwner'] = $name;
}
if(isset($params['cc_exp']))
{
$month = substr($params['cc_exp'], 0, 2);
$year = substr($params['cc_exp'], -2, 2);
$request['trnExpMonth'] = $month;
$request['trnExpYear'] = $year;
}
if(isset($params['cc_code']))
{
$request['trnCardCvd'] = $params['cc_code'];
}
if(isset($params['identifier']))
{
if($method === 'PAC' OR $method === 'VP' OR $method === 'VR' OR $method === 'R')
{
$request['adjId'] = $params['identifier'];
}
if($method === 'Q' OR $method === 'P')
{
$request['trnOrderNumber'] = $params['identifier'];
}
}
if(isset($params['cc_number']))
{
$request['trnCardNumber'] = $params['cc_number'];
}
if (isset($params['amt']))
{
if ($method == 'M')
{
$request['Amount'] = $params['amt'];
} else {
$request['trnAmount'] = $params['amt'];
}
}
if(isset($params['phone']))
{
$request['ordPhoneNumber'] = $params['phone'];
}
if(isset($params['email']))
{
$request['ordEmailAddress'] = $params['email'];
}
if(isset($params['street']))
{
$request['ordAddress1'] = $params['street'];
}
if(isset($params['city']))
{
$request['ordCity'] = $params['city'];
}
if(isset($params['state']))
{
$request['ordProvince'] = $params['state'];
}
if(isset($params['postal_code']))
{
$request['ordPostalCode'] = $params['postal_code'];
}
if(isset($params['country']))
{
$request['ordCountry'] = $params['country'];
}
if(isset($params['ship_to_name']))
{
$request['shipName'] = $params['ship_to_name'];
}
if(isset($params['ship_to_phone_number']))
{
$request['shipPhoneNumber'];
}
if(isset($params['ship_to_street']))
{
$request['shipAddress1'] = $params['ship_to_street'];
}
if(isset($params['ship_to_city']))
{
$request['shipCity'] = $params['ship_to_city'];
}
if(isset($params['ship_to_state']))
{
$request['shipProvince'] = $params['ship_to_state'];
}
if(isset($params['ship_to_postal_code']))
{
$request['shipPostalCode'] = $params['ship_to_postal_code'];
}
if(isset($params['ship_to_country']))
{
$request['shipCountry'] = $params['ship_to_country'];
}
if(isset($params['note']))
{
$request['trnComments'] = $params['note'];
}
if(isset($params['ip_address']))
{
$request['customerIP'] = $params['ip_address'];
}
return $request;
}
/**
* Maps PHP Payments Methods to Beanstream Methods
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'P',
'descriptor' => 'trnType',
'required' => array(
'cc_number',
'cc_exp',
'cc_code',
'amt',
'first_name',
'last_name',
'phone',
'email',
'street',
'city',
'state',
'country',
'postal_code'
)
),
'authorize_payment' => array(
'api' => 'PA',
'descriptor' => 'trnType',
'required' => array(
'cc_number',
'cc_exp',
'cc_code',
'amt',
'first_name',
'last_name',
'phone',
'email',
'street',
'city',
'state',
'country',
'postal_code'
)
),
'capture_payment' => array(
'api' => 'PAC',
'descriptor' => 'trnType',
'required' => array(
'identifier',
'amt'
)
),
'void_payment' => array(
'api' => 'VP',
'descriptor' => 'trnType',
'required' => array(
'identifier',
'amt'
)
),
'void_refund' => array(
'api' => 'VR',
'descriptor' => 'trnType',
'required' => array(
'identifier',
'amt',
'first_name',
'last_name',
'cc_number',
'cc_exp',
'email',
'phone',
'street',
'city',
'state',
'country'
)
),
'refund_payment' => array(
'api' => 'R',
'descriptor' => 'trnType',
'required' => array(
'identifier'
)
),
'get_transaction_details' => array(
'api' => 'Q',
'descriptor' => 'trnType',
'required' => array(
'identifier'
)
),
'recurring_payment' => array(
'api' => 'P',
'descriptor' => 'trnType',
'method' => 'recurring',
'required' => array(
'cc_number',
'cc_exp',
'cc_code',
'amt',
'first_name',
'last_name',
'phone',
'email',
'street',
'city',
'state',
'country',
'postal_code'
)
),
'cancel_recurring_profile' => array(
'api' => 'C',
'descriptor' => 'operationType',
'method' => 'recurring_cancel',
'required' => array(
'identifier'
)
),
'suspend_recurring_profile' => array(
'api' => 'M',
'descriptor' => 'operationType',
'method' => 'recurring_suspend',
'required' => array(
'identifier'
)
),
'activate_recurring_profile' => array(
'api' => 'M',
'descriptor' => 'operationType',
'method' => 'recurring_activate',
'required' => array(
'identifier'
)
),
'update_recurring_profile' => array(
'api' => 'M',
'descriptor' => 'operationType',
'method' => 'recurring_modify',
'required' => array(
'identifier'
)
)
);
return $map;
}
/**
* Build the query for the response and call the request function
*
* @param array
* @param array
* @return array
*/
private function _handle_query($method, $request)
{
$settings = array_merge($this->_api_settings, $this->_api_method);
$merged = array_merge($settings, $request);
$request = http_build_query($merged);
$this->_http_query = $this->_api_endpoint.$request;
$request = Payment_Request::curl_request($this->_http_query);
$response = $this->_parse_response($request);
return $response;
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
private function _parse_response($response)
{
$details = (object) array();
if (is_object($response))
{
if ($response->code == '1')
{
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method . '_success',
$details
);
}
else
{
$details->reason = $response->message;
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method . '_gateway_failure',
$details
);
}
}
elseif(strstr($response, '<response>'))
{
$response = Payment_Utility::parse_xml($response);
$response = Payment_Utility::arrayize_object($response);
$details->gateway_response = $response;
if($response['code'] == '1')
{
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method.'_success',
$details
);
}
else
{
$details->reason = $response['message'];
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
else
{
$results = explode('&',urldecode($response));
foreach($results as $result)
{
list($key, $value) = explode('=', $result);
$gateway_response[$key]=$value;
}
$details->gateway_response = $gateway_response;
$details->timestamp = (isset($gateway_response['trnDate'])) ? $gateway_response['trnDate'] : gmdate('c');
if(isset($gateway_response['trnApproved']) && $gateway_response['trnApproved'] == '1')
{
$details->identifier = (isset($gateway_response['trnId'])) ? $gateway_response['trnId'] : null;
if(isset($gateway_response['rbAccountId']))
{
$details->identifier = $gateway_response['rbAccountId'];
}
return Payment_Response::instance()->gateway_response(
'success',
$this->_lib_method.'_success',
$details
);
}
else
{
$details->reason = (isset($gateway_response['messageText'])) ? $gateway_response['messageText'] : null;
return Payment_Response::instance()->gateway_response(
'failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
}
}

View File

@ -0,0 +1,306 @@
<?php
/**
* BluePay Payment Module
*
* @author Joel Kallman (www.eclarian.com)
* @email jkallman@eclarian.com
* @created 08/24/2011
* @license http://www.opensource.org/licenses/mit-license.php
*/
class Bluepay_Driver extends Payment_Driver {
/**
* The API endpoint
*/
private $_api_endpoint = 'https://secure.bluepay.com/interfaces/bp20post';
/**
* The API method currently being utilized
*/
private $_api_method;
/**
* An array for storing all settings
*/
private $_api_settings;
/**
* The version of the API to use
*/
private $_api_version = '2';
/**
* The lib method
*/
private $_lib_method;
// -------------------------------------------------------------------------
/**
* Constructor method
*/
public function __construct($config)
{
$this->_api_settings = array(
'ACCOUNT_ID' => $config['api_account_id'],
'PAYMENT_TYPE' => 'CREDIT', //means credit card - not giving away money!
'SECRET_KEY' => $config['api_secret_key'],
'MODE' => ($config['mode'] == 'production') ? 'LIVE' : 'TEST'
);
if(!empty($config['api_user_id'])) $this->_api_settings['USER_ID'] = $config['api_user_id'];
}
/**
* Caller Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
$request_string = $this->_build_request($params);
$raw_response = Payment_Request::curl_request($this->_api_endpoint, $request_string, 'application/x-www-form-urlencoded');
return $this->_parse_response($raw_response);
}
/**
* Maps Methods to Their Attributes
*/
public function method_map()
{
$map =
array(
'oneoff_payment' => array(
'method' => 'SALE',
'required' => array(
'cc_number',
'cc_code',
'cc_exp',
'amt'
),
'keymatch' => array(
'cc_number' => 'PAYMENT_ACCOUNT', //Credit card number
'cc_exp' => 'CARD_EXPIRE', //Must be formatted MMYYYY @todo - Must translate to MMYY
'cc_code' => 'CARD_CVV2', //3 or 4 digit cvv code
'email' => 'EMAIL', //email associated with account being billed
'first_name' => 'NAME1', //first name of the purchaser
'last_name' => 'NAME2', //last name of the purchaser
'business_name' => 'COMPANY_NAME', //name of business
'street' => 'ADDR1', //street address of the purchaser @todo - Only 64 Char
'street2' => 'ADDR2', //street address 2 of purchaser @todo - Only 64 Char
'city' => 'CITY', //city of the purchaser @todo - Only 32 Char
'state' => 'STATE', //state of the purchaser @todo - Only 16 Char; 2 lttr abbr pref.
'country' => 'COUNTRY', // country of the purchaser (64 Char)
'postal_code' => 'ZIP', //zip code of the purchaser (16 Char)
'amt' => 'AMOUNT', //purchase amount (XXXXXXX.XX FORMAT) Includes Tax and Tip
'phone' => 'PHONE', //phone num of customer shipped to @todo - Required for ACH; 16 Chars.
'tax_amt' => 'AMOUNT_TAX', //Amount for just tax.
'desc' => 'MEMO', //Description for the transaction
'inv_num' => 'INVOICE_ID', //Invoice number @todo - 64 Characters
'po_num' => 'ORDER_ID',
)
),
'authorize_payment' => array(
'method' => 'AUTH',
'required' => array(
'cc_number',
'cc_code',
'cc_exp',
'amt'
),
'keymatch' => array(
'cc_number' => 'PAYMENT_ACCOUNT', //Credit card number
'cc_exp' => 'CARD_EXPIRE', //Must be formatted MMYYYY @todo - Must translate to MMYY
'cc_code' => 'CARD_CVV2', //3 or 4 digit cvv code
'email' => 'EMAIL', //email associated with account being billed
'first_name' => 'NAME1', //first name of the purchaser
'last_name' => 'NAME2', //last name of the purchaser
'business_name' => 'COMPANY_NAME', //name of business
'street' => 'ADDR1', //street address of the purchaser @todo - Only 64 Char
'street2' => 'ADDR2', //street address 2 of purchaser @todo - Only 64 Char
'city' => 'CITY', //city of the purchaser @todo - Only 32 Char
'state' => 'STATE', //state of the purchaser @todo - Only 16 Char; 2 lttr abbr pref.
'country' => 'COUNTRY', // country of the purchaser (64 Char)
'postal_code' => 'ZIP', //zip code of the purchaser (16 Char)
'amt' => 'AMOUNT', //purchase amount (XXXXXXX.XX FORMAT) Includes Tax and Tip
'phone' => 'PHONE', //phone num of customer shipped to @todo - Required for ACH; 16 Chars.
'tax_amt' => 'AMOUNT_TAX', //Amount for just tax.
'desc' => 'MEMO', //Description for the transaction
'inv_num' => 'INVOICE_ID', //Invoice number @todo - 64 Characters
'po_num' => 'ORDER_ID',
)
),
'capture_payment' => array(
'method' => 'CAPTURE',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'MASTER_ID', //Merchant provided identifier for the transaction @todo - IS PREVIOUS TRANS_ID AND ONLY REQUIRED FOR CAPTURE OR REFUND.
)
),
'refund_payment' => array(
'method' => 'REFUND',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'MASTER_ID', //Merchant provided identifier for the transaction @todo - IS PREVIOUS TRANS_ID AND ONLY REQUIRED FOR CAPTURE OR REFUND.
)
),
'void_payment' => array(
'method' => 'VOID',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'MASTER_ID', //Merchant provided identifier for the transaction @todo - IS PREVIOUS TRANS_ID AND ONLY REQUIRED FOR CAPTURE OR REFUND.
)
)
);
return $map;
}
// -------------------------------------------------------------------------
/**
* Builds a request
*
* Builds as an HTTP POST Request
*
* @param array array of params
* @param string the api call to use
* @return array Array of transaction settings
*/
protected function _build_request($params)
{
$params_ready = array();
// Map CI Payments Keys to Gateway Keys
$map = $this->method_map();
foreach($map as $k => $v)
{
// Key not being used or Parameter not included or empty
if($v === FALSE OR ! isset($params[$k]) OR empty($params[$k])) continue;
$params_ready[$v] = $params[$k];
}
$params_ready['TRANS_TYPE'] = $this->_lib_method;
$params_ready['TAMPER_PROOF_SEAL'] = $this->_build_tamper_proof_seal(array_merge($params_ready, $this->_api_settings));
// Build HTTP Query Because we are using POST rather than XML
return http_build_query(array_merge($this->_api_settings ,$params_ready));
}
// -------------------------------------------------------------------------
/**
* Build Tamper Proof Seal
*
* This function creates a md5 checksum to validate the integrity of the request
* The secret key is never passed directly and is used as a salt to provide a check
* on the gateway servers.
*
* FORMAT:
* md5(SECRET KEY + ACCOUNT_ID + TRANS_TYPE + AMOUNT + MASTER_ID + NAME1 + PAYMENT_ACCOUNT)
*
* @param array Current Requests Parameters
* @return string Checksum for Tamper Proof Seal
*/
protected final function _build_tamper_proof_seal($params)
{
$hash = '';
$tps_contents = array('SECRET_KEY', 'ACCOUNT_ID', 'TRANS_TYPE', 'AMOUNT', 'MASTER_ID', 'NAME1', 'PAYMENT_ACCOUNT');
foreach($tps_contents as $key) $hash .= (isset($params[$key])) ? $params[$key]: '';
return bin2hex( md5($hash, TRUE) );
}
// -------------------------------------------------------------------------
/**
* Build the query for the response and call the request function
*
* @param array
* @param array
* @param string
* @return array
*/
protected function _handle_query()
{
$this->_http_query = $this->_request;
}
// -------------------------------------------------------------------------
/**
* Parse the response from the server
*
* @param object Always includes timestamp, gateway_response, reason
* @return object
*/
protected function _parse_response($data)
{
// Since this module currently uses POST to make the gateway request
// We know our current object can be simply typecasted back to an array.
// IF THIS EVER CHANGES, USE $this->payments->arrayize_object($data);
$results = explode('&',urldecode($data));
foreach($results as $result)
{
list($key, $value) = explode('=', $result);
$gateway_response[$key]=$value;
}
$details = (object) array();
$details->timestamp = gmdate('c');
$details->gateway_response = $gateway_response; // Full Gateway Response
//Set response types
$response_types = array(
'E' => $this->_lib_method.'_gateway_failure',
'1' => $this->_lib_method.'_success',
'0' => $this->_lib_method.'_local_failure'
);
// Default to Failure if data is not what is expected
$status = 'failure';
// Setup Final Response
if(isset($gateway_response['MESSAGE']))
{
$details->reason = $gateway_response['MESSAGE'];
}
if(isset($gateway_response['STATUS']))
{
$details->status = $gateway_response['STATUS']; // The request can be successful, yet have the card be declined
}
// Setup additional properties if successful
if(isset($gateway_response['TRANS_ID']))
{
$details->identifier = $gateway_response['TRANS_ID'];
}
// Return Local Response, because we didn't get an expected response from server
if( ! isset($gateway_response['STATUS'], $gateway_response['MESSAGE']))
{
// @todo - Don't know if this should be a different response than "gateway"
return Payment_Response::instance()->gateway_response($status, $response_types['E'], $details);
}
// Possible Responses are 1 = Approved, 0 = Decline, 'E' = Error
$is_success = ($data['STATUS'] === '1');
// Setup Response
$status = ($is_success) ? 'success': 'failure';
$response = $response_types[$gateway_response['STATUS']];
// Send it back!
return Payment_Response::instance()->gateway_response($status, $response, $details);
}
// -------------------------------------------------------------------------
}

View File

@ -0,0 +1,310 @@
<?php
class Braintree_Driver extends Payment_Driver
{
/**
* URL to Use
*/
private $_api_url;
/**
* Endpoint to Send the Query To
*/
private $_endpoint;
/**
* The particular API which is being used
*/
private $_api;
/**
* The particular API method which is being used
*/
private $_api_method;
/**
* The PHP Payments library method
*/
private $_lib_method;
/**
* Stores Settings for the Transaction
*/
private $_settings;
/**
* The Constructor Function
*/
public function __construct($config)
{
Payment_Utility::load('file', 'vendor/braintree/lib/Braintree');
$bt_mode = ($config['mode'] == 'test') ? 'sandbox' : 'production';
Braintree_Configuration::environment($bt_mode);
unset($config['mode']);
foreach($config as $k=>$v)
{
//merchantId, publicKey, privateKey need to be set
Braintree_Configuration::$k($v);
}
}
/**
* Call Magic Method
*/
public function __call($method, $params)
{
$args = $params[0];
$method_map = $this->method_map();
$this->_api = $method_map[$method]['api'];
$this->_api_method = (isset($method_map[$method]['method'])) ? $method_map[$method]['method'] : '';
$this->_lib_method = $method;
list($api, $api_method, $params_ready) = $this->_build_request($args);
try {
//If the only param is an id, just use that as a string instead of sending an array
if(count($params_ready) == 1 && isset($params_ready['id']))
{
$response_raw = $api::$api_method($param_ready['id']);
}
else if(count($params_ready) == 2 && isset($params_ready['id']) && isset($params_ready['amount']))
{
$response_raw = $api::$api_method($params_ready['id'], $params_ready['amount']);
}
else
{
$response_raw = $api::$api_method($params_ready);
}
}
catch (Exception $e) {
if(get_class($e) == 'Braintree_Exception_Authentication') $message = "Authentication failed.";
return Payment_Response::instance()->gateway_response(
'failure',
$method.'_gateway_failure',
(isset($message)) ? $message : $e->getMessage()
);
}
return $this->_parse_response($response_raw);
}
/**
* Maps PHP-Payments Methods to Details Particular to Each Request for that Method
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'Braintree_Transaction',
'method' => 'sale',
'required' => array(
'cc_number',
'cc_exp',
'amt',
),
'keymatch' => array(
'amt' => 'amount',
'identifier' => 'orderId',
'cc_number' => 'creditCard["number"]',
'cc_exp' => 'creditCard["expirationDate"]',
'cc_code' => 'creditCard["cvv"]',
'first_name' => 'billing["firstName"]',
'last_name' => 'billing["lastName"]',
'street' => 'billing["streetAddress"]',
'street2' => 'billing["extendedAddress"]',
'postal_code' => 'billing["postalCode"]',
'state' => 'billing["region"]',
'country' => 'billing["countryCodeAlpha2"]',
'city' => 'billing["locality"]',
'ship_to_first_name' => 'shipping["firstName"]',
'ship_to_last_name' => 'shipping["lastName"]',
'ship_to_company' => 'shipping["company"]',
'ship_to_street' => 'shipping["streetAddress"]',
'ship_to_city' => 'shipping["locality"]',
'ship_to_state' => 'shipping["state"]',
'ship_to_postal_code' => 'shipping["postalCode"]',
'ship_to_country' => 'shipping["countryCodeAlpha2"]'
),
'static' => array(
'options' => array(
'submitForSettlement' => true
)
)
),
'authorize_payment' => array(
'api' => 'Braintree_Transaction',
'method' => 'sale',
'required' => array(
'cc_number',
'cc_exp',
'amt',
),
'keymatch' => array(
'amt' => 'amount',
'identifier' => 'orderId',
'cc_number' => 'creditCard["number"]',
'cc_exp' => 'creditCard["expirationDate"]',
'cc_code' => 'creditCard["cvv"]',
'first_name' => 'billing["firstName"]',
'last_name' => 'billing["lastName"]',
'street' => 'billing["streetAddress"]',
'street2' => 'billing["extendedAddress"]',
'postal_code' => 'billing["postalCode"]',
'state' => 'billing["region"]',
'country' => 'billing["countryCodeAlpha2"]',
'city' => 'billing["locality"]',
'ship_to_first_name' => 'shipping["firstName"]',
'ship_to_last_name' => 'shipping["lastName"]',
'ship_to_company' => 'shipping["company"]',
'ship_to_street' => 'shipping["streetAddress"]',
'ship_to_city' => 'shipping["locality"]',
'ship_to_state' => 'shipping["state"]',
'ship_to_postal_code' => 'shipping["postalCode"]',
'ship_to_country' => 'shipping["countryCodeAlpha2"]'
),
'static' => array(
'options' => array(
'submitForSettlement' => false
)
)
),
'capture_payment' => array(
'api' => 'Braintree_Transaction',
'method' => 'submitForSettlement',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'id'
)
),
'get_transaction_details' => array(
'api' => 'Braintree_Transaction',
'method' => 'find',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'id'
)
),
'refund_payment' => array(
'api' => 'Braintree_Transaction',
'method' => 'refund',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'id',
'amt' => 'amount'
)
),
);
return $map;
}
/**
* Builds the Request
*/
protected function _build_request($params)
{
$api = $this->_api;
$method = $this->_api_method;
$params_ready = $this->_match_params($params);
//Now we have what we need to build the request
return array($api, $method, $params_ready);
}
/**
* Match the Params
*/
private function _match_params($params)
{
$map = $this->method_map();
$l = $this->_lib_method;
$params_ready = array();
$matcher = $map[$l]['keymatch'];
foreach($params as $k=>$v)
{
if(isset($matcher[$k]))
{
if(strpos($matcher[$k], '["') !== false)
{
$ex = explode('["', $matcher[$k]);
$arr = $ex[0];
$arrk = str_replace('"]', '', $ex[1]);
if(!isset($params_ready[$arr])) $params_ready[$arr] = array();
if($k === 'cc_exp')
{
$d_mm = substr($v, 0, 2);
$d_yyyy = substr($v, 2, 4);
$params_ready[$arr][$arrk] = $d_mm.'/'.$d_yyyy; //set the date
}
else
{
$params_ready[$arr][$arrk] = $v;
}
}
else
{
$key = $matcher[$k];
$val = $v;
$params_ready[$key] = $val;
}
}
else
{
error_log("$k is not a valid param for this method in this driver");
}
}
if(isset($map[$l]['static']))
{
$static = $map[$l]['static'];
foreach($static as $k=>$v)
{
$params_ready[$k] = $v;
}
}
return $params_ready;
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
protected function _parse_response($response)
{
$details = (object) array();
if(isset($response->transaction->id)) $details->identifier = $response->transaction->id;
$details->timestamp = $response->created;
$details->gateway_response = $response;
if(isset($response->transaction->processorResponseText)) $details->reason = $response->transaction->processorResponseText;
$indicator = ($response->success === true) ? 'success' : 'failure';
return Payment_Response::instance()->gateway_response(
$indicator,
$this->_lib_method.'_'.$indicator,
$details
);
}
}

View File

@ -0,0 +1,197 @@
<?php
class Eway_Driver Extends Payment_Driver
{
/**
* The API Endpoint
*/
private $_api_endpoint;
/**
* Testing API Endpoint
*/
private $_api_endpoint_test = 'https://www.eway.com.au/gateway/xmltest/testpage.asp';
/**
* Production API Endpoint
*/
private $_api_endpoint_production = 'https://www.eway.com.au/gateway_cvn/xmlpayment.asp';
/**
* Constructor method
*/
public function __construct($config)
{
$this->_api_endpoint = ($config['mode'] == 'test') ? $this->_api_endpoint_test : $this->_api_endpoint_production;
$this->_api_settings = array(
'api_cid' => $config['api_cid'],
'xml_version' => '1.0',
'encoding' => 'utf-8',
'xml_schema' => ''
);
}
/**
* Caller Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
$request = $this->_build_request($args);
$response_raw = Payment_Request::curl_request($this->_api_endpoint, $request);
return $this->_parse_response($response_raw);
}
/**
* Method Map
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'authCaptureTransaction',
'required' => array(
'amt',
'first_name',
'last_name',
'email',
'cc_number',
'cc_exp',
'cc_code',
'street',
'postal_code',
'desc'
),
'keymatch' => array(
'amt' => 'ewayTotalAmount',
'first_name' => 'ewayCardHoldersName&ewayCustomerFirstName',
'last_name' => 'ewayCardHoldersName&ewayCustomerLastName',
'cc_number' => 'ewayCardNumber',
'cc_exp' => 'ewayCardExpiryMonth,ewayCardExpiryYear',
'cc_code' => 'ewayCVN',
'email' => 'ewayCustomerEmail',
'street' => 'ewayCustomerAddress',
'postal_code' => 'ewayCustomerPostcode',
'desc' => 'ewayCustomerInvoiceDescription',
'identifier' => 'ewayCustomerInvoiceRef'
)
)
);
return $map;
}
/**
* Builds a request
* @param array array of params
* @param string the api call to use
* @param string the type of transaction
* @return array Array of transaction settings
*/
protected function _build_request($params, $transaction_type = NULL)
{
$nodes = array('ewaygateway' => array());
$root = &$nodes['ewaygateway'];
$root['ewayCustomerID'] = $this->_api_settings['api_cid'];
$root['ewayTrxnNumber'] = ' ';
$root['ewayOption1'] = ' ';
$root['ewayOption2'] = ' ';
$root['ewayOption3'] = ' ';
if(!isset($params['identifier'])) $root['ewayCustomerInvoiceRef'] = mt_rand(10, 10000);
$map = $this->method_map();
foreach($params as $k=>$v)
{
$l = $this->_lib_method;
if(isset($map[$l]['keymatch'][$k]))
{
$key = $map[$l]['keymatch'][$k];
if(strpos($key, ',') !== false)
{
$ex = explode(',', $key);
if($k == 'cc_exp')
{
$month = substr($v, 0, 2);
$year = substr($v, -2, 2);
$root[$ex[0]] = $month;
$root[$ex[1]] = $year;
}
}
else if(strpos($key, '&') !== false)
{
$ex = explode('&', $key);
foreach($ex as $exk)
{
$root[$exk] = $v;
}
}
else
{
$root[$key] = $v;
continue;
}
if(isset($root[$key]))
{
$root[$key] .= $v;
}
}
else
{
error_log("The $k param for the $l method in the Eway Driver does not exist.");
}
}
$request = Payment_Request::build_xml_request(
$this->_api_settings['xml_version'],
$this->_api_settings['encoding'],
$nodes
);
return $request;
}
/**
* Parses the XML response from the gateway and returns success or failure, along with details
*
* @param object
* @return object
*/
protected function _parse_response($response)
{
$details = (object) array();
$as_array = Payment_Utility::arrayize_object($response);
if($as_array['ewayTrxnStatus'] == 'True')
{
$details->identifier = $as_array['ewayTrxnNumber'];
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method.'_success',
$details
);
}
else
{
$details->reason = $as_array['ewayTrxnError'];
$details->gateway_response = $as_array;
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
}

View File

@ -0,0 +1,182 @@
<?php
class Gocardless_Driver extends Payment_Driver
{
/*
* The endpoint to use
*/
private $_endpoint;
/*
* The PHP Payments method
*/
private $_lib_method;
/*
* Config array
*/
private $_config;
/*
* Constructor
*/
public function __construct($config)
{
Payment_Utility::load('file', 'vendor/gocardless/lib/gocardless');
$this->_config = $config;
}
/**
* Caller Magic Method
*
* @param string
* @param array
* @return object
*/
public function __call($method, $params)
{
GoCardless::$environment = ($this->_config['mode'] == 'test') ? 'sandbox' : 'production';
$account_details = array(
'app_id' => $this->_config['app_identifier'],
'app_secret' => $this->_config['app_secret'],
'merchant_id' => $this->_config['id'],
'access_token' => $this->_config['access_token']
);
GoCardless::set_account_details($account_details);
$args = $params[0];
$this->_lib_method = $method;
list($api, $api_method, $params_ready) = $this->_build_request($args);
try
{
$raw = $api::$api_method($params_ready);
return $this->_parse_response($raw);
}
catch(Exception $e)
{
return Payment_Response::instance()->gateway_response(
'failure',
$method.'_gateway_failure',
$e->getMessage()
);
}
}
/**
* Maps Methods to Details Particular to Each Request for that Method
*
* @return array
*/
public function method_map()
{
$method_map = array(
'oneoff_payment_button' => array(
'api' => 'GoCardless',
'method' => 'new_bill_url',
'required' => array(
'amt',
'desc'
),
'keymatch' => array(
'amt' => 'amount',
'desc' => 'name'
),
'is_button' => true
),
'recurring_payment_button' => array(
'api' => 'GoCardless',
'method' => 'new_subscription_url',
'required' => array(
'amt',
'name',
'billing_period',
'billing_frequency'
),
'keymatch' => array(
'amt' => 'amount',
'desc' => 'name',
'billing_frequency' => 'interval_length',
'billing_period' => 'interval_unit'
),
'is_button' => true
),
'get_transaction_details' => array(
'api' => 'GoCardless_Bill',
'method' => 'find',
'required' => array(
'identifier'
)
),
'get_recurring_profile' => array(
'api' => 'GoCardless_Subscription',
'method' => 'find',
'required' => array(
'identifier'
)
)
);
return $method_map;
}
/**
* Builds the Request
*
* @param array
* @return array
*/
protected function _build_request($params)
{
$method_map = $this->method_map();
$m = $method_map[$this->_lib_method];
if(count($params) == 1 && array_key_exists('identifier', $params))
{
$return_params = $params;
}
else
{
$return_params = array();
foreach($m['keymatch'] as $k=>$v)
{
$return_params[$v] = $params[$k];
}
}
$this->_is_button = (isset($m['is_button']) && $m['is_button'] == true) ? true : false;
return array(
$m['api'],
$m['method'],
$return_params
);
}
/**
* Parse the Response and then Delegate to the Response Object
*
* @param object
* @return object
*/
protected function _parse_response($response)
{
if($this->_is_button)
{
return Payment_Response::instance()->local_response(
'success',
$this->_lib_method.'_success',
$response
);
}
else
{
/*return Payment_Response::instance()->gateway_response(
'success',
$this->_lib_method.'_success',
$response
);*/ //Will be integrated when testing details are received
var_dump($response);exit;
}
}
}

View File

@ -0,0 +1,154 @@
<?php
class Google_Checkout_Driver extends Payment_Driver
{
/**
* The Config Settings
*/
private $_config;
/**
* The API Mode (sandbox or live)
*/
private $_mode;
/**
* If it's a button, we just need to spit the button out, we don't need to parse a response
*/
private $_is_button;
/**
* Constructor Function
*/
public function __construct($config)
{
$this->_mode = ($config['mode'] == 'test') ? 'sandbox' : 'live';
$this->_config = $config;
}
/**
* The Caller Magic Method
*/
public function __call($method, $params)
{
Payment_Utility::load_all_files('vendor/google_checkout/library');
$this->_lib_method = $method;
$args = $params[0];
$request = $this->_build_request($args);
return $this->_parse_response($request);
}
/**
* Maps PHP Payments to Gateway
*/
public function method_map()
{
$map = array(
'oneoff_payment_button' => array(
'api' => 'GoogleCart',
'required' => array(
'currency_code',
'items',
'shipping_options',
/*'items' => array( I'll THINK about adding item support = )
'name',
'desc',
'qty',
'amt',
),
'shipping_options' => array(
'option' => array(
'desc',
'amt'
)
),*/
'edit_url',
'continue_url'
),
'static' => array(
'SetRequestBuyerPhone' => $this->_config['request_buyer_phone'],
'CheckoutButtonCode' => $this->_config['button_size']
)
)
);
return $map;
}
/**
* Builds a Request
*/
protected function _build_request($params)
{
$map = $this->method_map();
$l = $this->_lib_method;
$api = $map[$l]['api']; //Creates the object that the request is made from
$caller = new $api($this->_config['merchant_id'], $this->_config['merchant_key'], $this->_mode, $params['currency_code']);
foreach($params as $k=>$v)
{
if($k == 'items'){
foreach($v as $item)
{
$item_arr = new GoogleItem(
$item['name'],
$item['desc'],
$item['qty'],
$item['amt']
);
$caller->AddItem($item_arr);
}
}
if($k =='shipping_options'){
foreach($v as $ship)
{
$ship_arr = new GoogleFlatRateShipping(
$ship['desc'],
$ship['amt']
);
//TODO: Add filters
$caller->AddShipping($ship_arr);
}
}
//TODO: Add tax rules
if($k == 'phone')
{
$caller->SetRequestBuyerPhone(true);
}
}
if($api = 'GoogleCart')
{
$caller->SetEditCartUrl($params['edit_url']);
$caller->SetContinueShoppingUrl($params['continue_url']);
$this->_is_button = TRUE;
return $caller->CheckoutButtonCode($this->_config['button_size']);
}
}
/**
* Parses Response from the Gateway
*/
protected function _parse_response($response)
{
if($this->_is_button)
{
return Payment_Response::instance()->local_response(
'success',
$this->_lib_method.'_success',
$response
);
}
}
}

View File

@ -0,0 +1,571 @@
<?php
class PayPal_PaymentsPro_Driver extends Payment_Driver
{
/**
* The PHP Payments Method
*/
private $_lib_method;
/**
* The Paypal API to use
*/
private $_api;
/**
* Test or Production Mode
*/
private $_mode;
/**
* The API endpoint to send the request to
*/
private $_api_endpoint = 'https://api-3t.paypal.com/nvp';
/**
* The API endpoint to send a test request to
*/
private $_api_endpoint_test = 'https://api-3t.sandbox.paypal.com/nvp';
/**
* Current Version of PayPal's API
*/
private $_api_version = '66.0';
/**
* An array for storing all settings
*/
private $_settings = array();
/**
* Constructor method
*/
public function __construct($config)
{
$this->_settings = array(
'USER' => $config['api_username'],
'PWD' => $config['api_password'],
'SIGNATURE' => $config['api_signature'],
'VERSION' => $this->_api_version
);
$this->_mode = $config['mode'];
}
/**
* Caller Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
$request = $this->_build_request($args);
$endpoint = ($this->_mode == 'production') ? $this->_api_endpoint : $this->_api_endpoint_test;
$request_string = $endpoint.'?'.$request;
$raw_response = Payment_Request::curl_request($request_string);
return $this->_parse_response($raw_response);
}
/**
* Maps Methods to Keys
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'DoDirectPayment',
'required' => array(
'cc_type',
'cc_number',
'cc_exp',
'amt'
),
'keymatch' => array(
'ip_address' => 'IPADDRESS',
'cc_type' => 'CREDITCARDTYPE',
'cc_number' => 'ACCT',
'cc_exp' => 'EXPDATE',
'cc_code' => 'CVV2',
'email' => 'EMAIL',
'first_name' => 'FIRSTNAME',
'last_name' => 'LASTNAME',
'street' => 'STREET',
'street2' => 'STREET2',
'city' => 'CITY',
'state' => 'STATE',
'country' => 'COUNTRY',
'postal_code' => 'ZIP',
'amt' => 'AMT',
'phone' => 'SHIPTOPHONENUM',
'currency_code' => 'CURRENCYCODE',
'item_amt' => 'ITEMAMT',
'shipping_amt' => 'SHIPPINGAMT',
'insurance_amt' => 'INSURANCEAMT',
'shipping_disc_amt' => 'SHIPDISCAMT',
'handling_amt' => 'HANDLINGAMT',
'tax_amt' => 'TAXAMT',
'desc' => 'DESC',
'custom' => 'CUSTOM',
'inv_num' => 'INVNUM',
'notify_url' => 'NOTIFYURL',
'ship_to_first_name' => 'SHIPTONAME',
'ship_to_last_name' => 'SHIPTONAME',
'ship_to_street'=> 'SHIPTOSTREET',
'ship_to_city' => 'SHIPTOCITY',
'ship_to_state' => 'SHIPTOSTATE',
'ship_to_postal_code' => 'SHIPTOZIP',
'ship_to_country' => 'SHIPTOCOUNTRY',
),
'static' => array(
'PAYMENTACTION' => 'Sale'
)
),
'reference_payment' => array(
'api' => 'DoReferenceTransaction',
'required' => array(
'identifier', //Reference for a previous payment
'amt'
),
'keymatch' => array(
'identifier' => 'REFERENCEID',
'amt' => 'AMT'
),
'static' => array(
'PAYMENTACTION' => 'Sale'
)
),
'authorize_payment' => array(
'api' => 'DoDirectPayment',
'required' => array(
'cc_type',
'cc_number',
'cc_exp',
'amt'
),
'keymatch' => array(
'ip_address' => 'IPADDRESS',
'cc_type' => 'CREDITCARDTYPE',
'cc_number' => 'ACCT',
'cc_exp' => 'EXPDATE',
'cc_code' => 'CVV2',
'email' => 'EMAIL',
'first_name' => 'FIRSTNAME',
'last_name' => 'LASTNAME',
'street' => 'STREET',
'street2' => 'STREET2',
'city' => 'CITY',
'state' => 'STATE',
'country' => 'COUNTRY',
'postal_code' => 'ZIP',
'amt' => 'AMT',
'phone' => 'SHIPTOPHONENUM',
'currency_code' => 'CURRENCYCODE',
'item_amt' => 'ITEMAMT',
'shipping_amt' => 'SHIPPINGAMT',
'insurance_amt' => 'INSURANCEAMT',
'shipping_disc_amt' => 'SHIPDISCAMT',
'handling_amt' => 'HANDLINGAMT',
'tax_amt' => 'TAXAMT',
'desc' => 'DESC',
'custom' => 'CUSTOM',
'inv_num' => 'INVNUM',
'notify_url' => 'NOTIFYURL',
),
'static' => array(
'PAYMENTACTION' => 'Authorization'
)
),
'capture_payment' => array(
'api' => 'DoDirectPayment',
'required' => array(
'identifier',
'amt',
'cc_type',
'cc_number',
'cc_exp'
),
'keymatch' => array(
'identifier' => 'AUTHORIZATIONID',
'amt' => 'AMT',
'cc_type' => 'CREDITCARDTYPE',
'cc_number' => 'ACCT',
'cc_exp' => 'EXPDATE',
'inv_num' => 'INVOICEID',
'note' => 'NOTE',
'desc' => 'SOFTDESCRIPTOR' //Description for credit card statement
)
),
'void_payment' => array(
'api' => 'DoVoid',
'required' => array(
'identifier',
'note'
),
'keymatch' => array(
'identifier' => 'AUTHORIZATIONID',
'note' => 'NOTE'
)
),
'change_transaction_status' => array(
'api' => 'ManagePendingTransactionStatus',
'required' => array(
'identifier',
'action'
),
'keymatch' => array(
'identifier' => 'TRANSACTIONID',
'action' => 'ACTION'
)
),
'refund_payment' => array(
'api' => 'RefundTransaction',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'TRANSACTIONID',
'refund_type' => 'REFUNDTYPE',
'amt' => 'AMT',
'currency_code' => 'CURRENCYCODE',
'inv_num' => 'INVOICEID',
'note' => 'NOTE'
)
),
'get_transaction_details' => array(
'api' => 'GetTransactionDetails',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'TRANSACTIONID'
)
),
'search_transactions' => array(
'api' => 'TransactionSearch',
'required' => array(
'start_date'
),
'keymatch' => array(
'start_date' => 'STARTDATE',
'end_date' => 'ENDDATE',
'email' => 'EMAIL',
'receiver' => 'RECEIVER',
'receipt_id' => 'RECEIPTID',
'transaction_id'=> 'TRANSACTIONID',
'inv_num' => 'INVNUM',
'cc_number' => 'ACCT',
'transaction_class' => 'TRANSACTIONCLASS',
'amt' => 'AMT',
'currency_code' => 'CURRENCYCODE',
'status' => 'STATUS',
'salutation' => 'SALUTATION',
'first_name' => 'FIRSTNAME',
'middle_name' => 'MIDDLENAME',
'last_name' => 'LASTNAME',
'suffix' => 'SUFFIX'
)
),
'recurring_payment' => array(
'api' => 'CreateRecurringPaymentsProfile',
'required' => array(
'first_name',
'last_name',
'email',
'amt',
'cc_type',
'cc_number',
'cc_exp',
'cc_code',
'billing_period',
'billing_frequency',
'profile_start_date'
),
'keymatch' => array(
'first_name' => 'SUBSCRIBERNAME',
'last_name' => 'SUBSCRIBERNAME',
'profile_start_date' => 'PROFILESTARTDATE',
'profile_reference' => 'PROFILEREFERENCE',
'desc' => 'DESC',
'max_failed_payments' => 'MAXFAILEDPAYMENTS',
'auto_bill_amt' => 'AUTOBILLAMT',
'billing_period' => 'BILLINGPERIOD',
'billing_frequency' => 'BILLINGFREQUENCY',
'total_billing_cycles' => 'TOTALBILLINGCYCLES',
'amt' => 'AMT',
'currency_code' => 'CURRENCYCODE',
'shipping_amt' => 'SHIPPINGAMT',
'tax_amt' => 'TAXAMT',
'trial_billing_cycles' => 'TRIALBILLINGPERIOD',
'trial_billing_frequency' => 'TRIALBILLINGFREQUENCY',
'trial_amt' => 'TRIALAMT',
'cc_type' => 'CREDITCARDTYPE',
'cc_number' => 'ACCT',
'cc_exp' => 'EXPDATE',
'cc_code' => 'CVV2',
'email' => 'EMAIL',
'identifier' => 'PAYERID',
'country_code' => 'COUNTRY',
'business_name' => 'BUSINESS',
'salutation' => 'SALUTATION',
'first_name' => 'FIRSTNAME',
'middle_name' => 'MIDDLENAME',
'last_name' => 'LASTNAME',
'suffix' => 'SUFFIX',
'street' => 'STREET',
'street2' => 'STREET2',
'city' => 'CITY',
'state' => 'STATE',
'postal_code' => 'ZIP'
)
),
'get_recurring_profile' => array(
'api' => 'GetRecurringPaymentsProfileDetails',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'PROFILEID'
)
),
'suspend_recurring_profile' => array(
'api' => 'ManageRecurringPaymentsProfileStatus',
'required' => array(
'identifier'
),
'keymatch' => array(
'note' => 'NOTE',
'identifier' => 'PROFILEID'
),
'static' => array(
'ACTION' => 'Suspend'
)
),
'activate_recurring_profile' => array(
'api' => 'ManageRecurringPaymentsProfileStatus',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'PROFILEID',
'note' => 'NOTE'
),
'static' => array(
'ACTION' => 'Reactivate'
)
),
'cancel_recurring_profile' => array(
'api' => 'ManageRecurringPaymentsProfileStatus',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'PROFILEID',
'note' => 'NOTE'
),
'static' => array(
'ACTION' => 'Cancel'
)
),
'recurring_bill_outstanding' => array(
'api' => 'BillOutstandingAmount',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'PROFILEID',
'amt' => 'AMT',
'note' => 'NOTE'
)
),
'update_recurring_profile' => array(
'api' => 'UpdateRecurringPaymentsProfile',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'PROFILEID',
'note' => 'NOTE',
'desc' => 'DESC',
'subscriber_name'=> 'SUBSCRIBERNAME',
'profile_reference' => 'PROFILEREFERENCE',
'additional_billing_cycles' => 'ADDITIONALBILLINGCYCLES',
'amt' => 'AMT',
'shipping_amt' => 'SHIPPINGAMT',
'tax_amt' => 'TAXAMT',
'outstanding_amt'=> 'OUTSTANDINGAMT',
'auto_bill_amt' => 'AUTOBILLOUTAMT',
'max_failed_payments' => 'MAXFAILEDPAYMENTS',
'profile_start_date' => 'PROFILESTARTDATE',
'total_billing_cycles' => 'TOTALBILLINGCYCLES',
'currency_code' => 'CURRENCYCODE',
'shipping_amt' => 'SHIPPINGAMT',
'tax_amt' => 'TAXAMT',
'cc_type' => 'CREDITCARDTYPE',
'cc_number' => 'ACCT',
'cc_exp' => 'EXPDATE',
'cc_code' => 'CVV2',
'start_date' => 'STARTDATE',
'issue_number' => 'ISSUENUMBER',
'email' => 'EMAIL',
'first_name' => 'FIRSTNAME',
'last_name' => 'LASTNAME',
'street' => 'STREET',
'street2' => 'STREET2',
'city' => 'CITY',
'state' => 'STATE',
'country_code' => 'COUNTRY',
'postal_code' => 'ZIP',
'trial_amt' => 'TRIALAMT',
'trial_total_billing_cycles' => 'TRIALTOTALBILLINGCYCLES'
)
)
);
return $map;
}
/**
* Build the Request
*
* @param array
* @return array
*/
protected function _build_request($params)
{
//Normalize some param formats
$params_adjusted = array();
foreach($params as $k=>$v)
{
if($k == 'currency_code')
{
$val = strtoupper($v);
}
else
{
$val = $v;
}
$params_adjusted[$k] = $val;
}
$args = $this->_match_params($params_adjusted);
$request = http_build_query(array_merge(array('METHOD' => $this->_api), $this->_settings, $args));
return $request;
}
/**
* Match Params
*
* @param array
* @return array
*/
private function _match_params($params)
{
$l = $this->_lib_method;
$map = $this->method_map();
$this->_api = $map[$l]['api'];
$fields = array();
foreach($params as $k=>$v)
{
if(isset($map[$l]['keymatch'][$k]))
{
$key = $map[$l]['keymatch'][$k];
if(!isset($fields[$key]))
{
$fields[$key] = $v;
}
else
{
$fields[$key] .= " $v";
}
}
else
{
error_log("$k is not a valid param for the $l method of the Paypal PaymentsPro driver.");
}
}
if(isset($map[$l]['static']))
{
$static = $map[$l]['static'];
foreach($static as $k=>$v)
{
$fields[$k] = $v;
}
}
return $fields;
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
protected function _parse_response($response)
{
if($response === FALSE)
{
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure'
);
}
$results = explode('&',urldecode($response));
foreach($results as $result)
{
list($key, $value) = explode('=', $result);
$gateway_response[$key]=$value;
}
$details = (object) array(
'gateway_response' => (object) array()
);
foreach($gateway_response as $k=>$v)
{
$details->gateway_response->$k = $v;
}
if(isset($gateway_response['L_LONGMESSAGE0']))
{
$details->reason = $gateway_response['L_LONGMESSAGE0'];
}
if(isset($gateway_response['TIMESTAMP']))
{
$details->timestamp = $gateway_response['TIMESTAMP'];
}
if(isset($gateway_response['TRANSACTIONID']))
{
$details->identifier = $gateway_response['TRANSACTIONID'];
}
if(isset($gateway_response['PROFILEID']))
{
$details->identifier = $gateway_response['PROFILEID'];
}
if($gateway_response['ACK'] == 'Success')
{
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method.'_success',
$details
);
}
else
{
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
}

View File

@ -0,0 +1,346 @@
<?php
class Psigate_Driver extends Payment_Driver
{
/**
* The config object
*/
public $config;
/**
* The endpoint for a particular transaction
*/
private $_api_endpoint;
/**
* The settings for a particular transaction
*/
private $_api_settings;
/**
* The api method to use
*/
private $_api_method;
/**
* The library method being used
*/
private $_lib_method;
/**
* Constructor method
*/
public function __construct($config)
{
$this->_api_endpoint = ($config['mode'] == 'test') ? $config['api_endpoint'.'_test']: $config['api_endpoint'.'_production'];
$this->_api_settings = array(
'cid' => $config['api_cid'],
'store_id' => $config['api_username'],
'pass_phrase' => $config['api_password'],
'xml_version' => '1.0',
'encoding' => 'utf-8',
'xml_schema' => '',
);
}
/**
* Caller Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
$request = $this->_build_request($args);
$response_raw = Payment_Request::curl_request($this->_api_endpoint, $request);
return $this->_parse_response($response_raw);
}
/**
* Method Map
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'Order',
'method' => '0',
'required' => array(
'cc_number',
'cc_exp',
'cc_code',
'amt'
),
'keymatch' => array(
'amt' => 'Subtotal',
'first_name' => 'Bname',
'last_name' => 'Bname',
'company' => 'Bcompany',
'street' => 'Baddress1',
'city' => 'Bcity',
'state' => 'Bprovince',
'country' => 'Bcountry',
'ship_to_first_name' => 'Sname',
'ship_to_last_name' => 'Sname',
'ship_to_company' => 'Scompany',
'ship_to_street' => 'Saddress1',
'ship_to_city' => 'Scity',
'ship_to_state' => 'Sprovince',
'ship_to_country' => 'Scountry',
'cc_number' => 'CardNumber',
'cc_exp' => 'CardExpMonth,CardExpYear', //ex 11/15
'cc_code' => 'CardIDNumber',
'phone' => 'Phone',
'fax' => 'Fax',
'email' => 'Email',
'note' => 'Comments',
'tax_amt' => 'Tax1',
'shipping_amt' => 'ShippingTotal',
'ip_address' => 'CustomerIP'
),
'static' => array(
'PaymentType' => 'CC',
'CardAction' => '0'
)
),
'authorize_payment' => array(
'api' => 'Order',
'method' => '1',
'required' => array(
'cc_number',
'cc_exp',
'cc_code',
'amt'
),
'keymatch' => array(
'amt' => 'Subtotal',
'first_name' => 'Bname',
'last_name' => 'Bname',
'company' => 'Bcompany',
'street' => 'Baddress1',
'city' => 'Bcity',
'state' => 'Bprovince',
'country' => 'Bcountry',
'ship_to_first_name' => 'Sname',
'ship_to_last_name' => 'Sname',
'ship_to_company' => 'Scompany',
'ship_to_street' => 'Saddress1',
'ship_to_city' => 'Scity',
'ship_to_state' => 'Sprovince',
'ship_to_country' => 'Scountry',
'cc_number' => 'CardNumber',
'cc_exp' => 'CardExpMonth,CardExpYear', //ex 11/15
'cc_code' => 'CardIDNumber',
'phone' => 'Phone',
'fax' => 'Fax',
'email' => 'Email',
'note' => 'Comments',
'tax_amt' => 'Tax1',
'shipping_amt' => 'ShippingTotal',
'ip_address' => 'CustomerIP'
),
'static' => array(
'CardAction' => '1',
'PaymentType' => 'CC'
)
),
'capture_payment' => array(
'api' => 'Order',
'method' => '2',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'OrderId'
),
'static' => array(
'CardAction' => '2',
'PaymentType' => 'CC'
)
),
'void_payment' => array(
'api' => 'Order',
'method' => '9',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'OrderId'
),
'static' => array(
'CardAction' => '9',
'PaymentType' => 'CC'
)
),
'refund_payment'=> array(
'api' => 'Order',
'method' => '3',
'required' => array(
'identifier',
'identifier_2',
'amt'
),
'keymatch' => array(
'identifier' => 'OrderId',
'identifier_2' => 'TransRefNumber',
'amt' => 'Subtotal'
),
'static' => array(
'CardAction' => '3',
'PaymentType' => 'CC'
)
)
);
return $map;
}
/**
* Builds a request
* @param array array of params
* @param string the type of transaction
* @return array Array of transaction settings
*/
protected function _build_request($params)
{
$map = $this->method_map();
$l = $this->_lib_method;
$nodes = array();
$nodes[$map[$l]['api']] = array();
$root = &$nodes[$map[$l]['api']];
$root['test'] = 'haha';
$root['StoreId'] = $this->_api_settings['store_id'];
$root['Passphrase'] = $this->_api_settings['pass_phrase'];
foreach($params as $k=>$v)
{
if(isset($map[$l]['keymatch'][$k]))
{
$key = $map[$l]['keymatch'][$k];
if(strpos($key, ',') !== false) //If a key comprises multiple fields: complicated
{
$ex = explode(',', $key);
if($k == 'cc_exp')
{
$k1 = $ex[0];
$k2 = $ex[1];
$root[$k1] = substr($v, 0, 2); //Sets the month
$root[$k2] = substr($v, -2, 2); //Sets the year
}
}
else //Simple = )
{
if(isset($nodes[$key]))
{
$root[$key] .= $v;
}
else
{
$root[$key] = $v;
}
}
}
else
{
error_log("$k is not a valid param for the $l method in the Psigate class");
}
}
foreach($map[$l]['static'] as $k=>$v)
{
$root[$k] = $v;
}
$request = Payment_Request::build_xml_request(
$this->_api_settings['xml_version'],
$this->_api_settings['encoding'],
$nodes
);
return $request;
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
protected function _parse_response($xml)
{
$details = (object) array();
$as_array = Payment_Utility::arrayize_object($xml);
$result = $as_array['Approved'];
if(isset($as_array['OrderID']) && !empty($as_array['OrderID']))
{
$identifier = $as_array['OrderID'];
}
if(isset($as_array['TransRefNumber']))
{
$identifier2 = $as_array['TransRefNumber'];
}
$details->timestamp = $as_array['TransTime'];
$details->gateway_response = $as_array;
if(isset($identifier))
{
$identifier = (string) $identifier;
if(strlen($identifier) > 1)
{
$details->identifier = $identifier;
}
}
if(isset($identifier2))
{
$identifier2 = (string) $identifier2;
if(strlen($identifier2) > 1)
{
$details->identifier2 = $identifier2;
}
}
if($result == 'APPROVED')
{
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method.'_success',
$details
);
}
if($result == 'ERROR' OR $result == 'DECLINED')
{
if(isset($as_array['ErrMsg']))
{
$message = $as_array['ErrMsg'];
$message = explode(':', $message);
$message = $message[1];
}
if(isset($message))
{
$details->reason = $message;
}
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
}

View File

@ -0,0 +1,404 @@
<?php
class QuickBooksMS_Driver extends Payment_Driver
{
/**
* The PHP-Payments method
*/
private $_lib_method;
/**
* The API method currently being utilized
*/
private $_api_method;
/**
* The API method currently being utilized
*/
private $_api_endpoint;
/**
* The endpoint to use for test requests
*/
private $_api_endpoint_test = 'https://merchantaccount.ptc.quickbooks.com/j/AppGateway';
/**
* The endpoint to use for production requests
*/
private $_api_endpoint_production = 'https://merchantaccount.quickbooks.com/j/AppGateway';
/**
* Version
*/
private $_version = '4.5';
/**
* An array for storing all settings
*/
private $_settings = array();
/**
* An array for storing all request data
*/
private $_request = array();
/**
* Constructor method
*/
public function __construct($config)
{
$this->_api_endpoint = ($config['mode'] == 'test') ? $this->_api_endpoint_test : $this->_api_endpoint_production;
$this->_api_settings = array(
'login' => $config['api_application_login'],
'connection_ticket' => $config['api_connection_ticket'],
'xml_version' => '1.0',
'encoding' => 'utf-8',
'xml_extra' => 'qbmsxml version="'.$this->_version.'"'
);
}
/**
* Call Magic Method
*/
public function __call($method, $params)
{
$this->_lib_method = $method;
$args = $params[0];
try {
$request = $this->_build_request($args);
}
catch(Exception $e){
return Payment_Response::instance()->gateway_response(
'failure',
$e->getMessage(),
''
);
}
$response_raw = Payment_Request::curl_request($this->_api_endpoint, $request, "application/x-qbmsxml");
return $this->_parse_response($response_raw);
}
/**
* The Method Map
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'CustomerCreditCardChargeRq',
'required' => array(
'cc_number',
'cc_exp',
'amt'
),
'keymatch' => array(
'amt' => 'Amount',
'cc_number' => 'CreditCardNumber',
'cc_exp' => 'ExpirationMonth,ExpirationYear',
'first_name' => 'NameOnCard',
'last_name' => 'NameOnCard',
'street' => 'CreditCardAddress',
'postal_code' => 'CreditCardPostalCode',
'tax_amt' => 'SalesTaxAmt',
'cc_code' => 'CardSecurityCode'
)
),
'authorize_payment' => array(
'api' => 'CustomerCreditCardAuthRq',
'required' => array(
'cc_number',
'cc_exp',
'amt'
),
'keymatch' => array(
'amt' => 'Amount',
'cc_number' => 'CreditCardNumber',
'cc_exp' => 'ExpirationMonth,ExpirationYear',
'first_name' => 'NameOnCard',
'last_name' => 'NameOnCard',
'street' => 'CreditCardAddress',
'postal_code' => 'CreditCardPostalCode',
'tax_amt' => 'SalesTaxAmt',
'cc_code' => 'CardSecurityCode'
),
'static' => array(
'isCardPresent' => '0'
)
),
'capture_payment' => array(
'api' => 'CustomerCreditCardCaptureRq',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'CreditCardTransID'
)
),
'void_payment' => array(
'api' => 'CustomerCreditCardTxnVoidRq',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'CreditCardTransID'
)
),
'refund_payment' => array(
'api' => 'CustomerCreditCardTxnVoidOrRefundRq',
'required' => array(
'identifier',
'amt'
),
'keymatch' => array(
'identifier' => 'CreditCardTransID',
'amt' => 'Amount',
)
),
'recurring_payment' => array(
'api' => 'CustomerCreditCardChargeRq',
'required' => array(
'cc_number',
'cc_exp',
'amt'
),
'keymatch' => array(
'amt' => 'Amount',
'cc_number' => 'CreditCardNumber',
'cc_exp' => 'ExpirationMonth,ExpirationYear',
'first_name' => 'NameOnCard',
'last_name' => 'NameOnCard',
'street' => 'CreditCardAddress',
'postal_code' => 'CreditCardPostalCode',
'tax_amt' => 'SalesTaxAmt',
'cc_code' => 'CardSecurityCode'
),
'static' => array(
'isRecurring' => '1'
)
)
);
return $map;
}
/**
* Builds a request
* @param array array of params
* @param string the api call to use
* @param string the type of transaction
* @return array Array of transaction settings
*/
protected function _build_request($params)
{
$session = $this->_get_session_ticket();
$map = $this->method_map();
$l = $this->_lib_method;
$nodes = array();
$nodes['SignonMsgsRq'] = array(
'SignonTicketRq' => array(
'ClientDateTime' => $session->time,
'SessionTicket' => $session->ticket
)
);
$unordered = array();
$unordered['TransRequestID'] = mt_rand(1, 1000000); //This is used to avoid duplicate transactions coming from the merchant.
foreach($params as $k=>$v)
{
if(isset($map[$l]['keymatch'][$k]))
{
$key = $map[$l]['keymatch'][$k];
if(strpos($key, ',') !== false)
{
$ex = explode(',', $key);
if($k == 'cc_exp')
{
$month = substr($params['cc_exp'], 0, 2);
$year = substr($params['cc_exp'], -4, 4);
$unordered[$ex[0]] = $month;
$unordered[$ex[1]] = $year;
}
}
else
{
if(isset($root[$key]))
{
$unordered[$key] .= $v;
}
else
{
$unordered[$key] = $v;
}
}
}
else
{
error_log("$k is not a valid param for the $l method of QuickBooksMS");
}
}
if(isset($map[$l]['static']))
{
$static = $map[$l]['static'];
foreach($static as $k=>$v)
{
$unordered[$k] = $v;
}
}
//QuickBooks requires a specific sort order...
$order = array('TransRequestID', 'CreditCardNumber', 'ExpirationMonth', 'ExpirationYear', 'isCardPresent', 'isRecurring', 'Amount', 'NameOnCard', 'CreditCardAddress', 'CreditCardCity', 'CreditCardState', 'CreditCardPostalCode', 'CommercialCode', 'SalesTaxAmount', 'CardSecurityCode', 'Lodging', 'ClientTransID', 'InvoiceID', 'Comment');
$ordered = Payment_Utility::sort_array_by_array($unordered, $order);
$nodes['QBMSXMLMsgsRq'] = array(
$map[$l]['api'] => $ordered
);
$request = Payment_Request::build_xml_request(
$this->_api_settings['xml_version'],
$this->_api_settings['encoding'],
$nodes,
'QBMSXML',
null,
$this->_api_settings['xml_extra']
);
return $request;
}
/**
* Get the Session Ticket So We Can Create Transactions
*
* @return object $session->time, $session->ticket
*/
private function _get_session_ticket()
{
$nodes = array();
$nodes['SignonMsgsRq'] = array(
'SignonDesktopRq' => array(
'ClientDateTime' => gmdate('c'),
'ApplicationLogin' => $this->_api_settings['login'],
'ConnectionTicket' => $this->_api_settings['connection_ticket']
)
);
$request = Payment_Request::build_xml_request(
$this->_api_settings['xml_version'],
$this->_api_settings['encoding'],
$nodes,
'QBMSXML',
null,
$this->_api_settings['xml_extra']
);
$response_raw = Payment_Request::curl_request($this->_api_endpoint, $request, "application/x-qbmsxml");
if(isset($response_raw->SignonMsgsRs->SignonDesktopRs))
{
$r = $response_raw->SignonMsgsRs->SignonDesktopRs;
$session = (object) array(
'time' => $r->ServerDateTime,
'ticket' => $r->SessionTicket
);
return $session;
}
else
{
throw new Exception('authentication_failure');
}
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
protected function _parse_response($xml)
{
$details = (object) array();
$as_array = Payment_Utility::arrayize_object($xml);
$signon = (isset($as_array['SignonMsgsRs'])) ? $as_array['SignonMsgsRs'] : '';
$response = (isset($as_array['QBMSXMLMsgsRs'])) ? $as_array['QBMSXMLMsgsRs'] : '';
$result = '';
$message = '';
$identifier = '';
if(isset($response['CustomerCreditCardChargeRs']))
{
$result = $response['CustomerCreditCardChargeRs']['@attributes']['statusCode'];
$message = $response['CustomerCreditCardChargeRs']['@attributes']['statusMessage'];
$identifier = $response['CustomerCreditCardChargeRs']['CreditCardTransID'];
}
if(isset($response['CustomerCreditCardAuthRs']))
{
$result = $response['CustomerCreditCardAuthRs']['@attributes']['statusCode'];
$message = $response['CustomerCreditCardAuthRs']['@attributes']['statusMessage'];
$identifier = $response['CustomerCreditCardAuthRs']['CreditCardTransID'];
}
if(isset($response['CustomerCreditCardCaptureRs']))
{
$result = $response['CustomerCreditCardCaptureRs']['@attributes']['statusCode'];
$message = $response['CustomerCreditCardCaptureRs']['@attributes']['statusMessage'];
$identifier = $response['CustomerCreditCardCaptureRs']['CreditCardTransID'];
}
if(isset($response['CustomerCreditCardTxnVoidRs']))
{
$result = $response['CustomerCreditCardTxnVoidRs']['@attributes']['statusCode'];
$message = $response['CustomerCreditCardTxnVoidRs']['@attributes']['statusMessage'];
$identifier = $response['CustomerCreditCardTxnVoidRs']['CreditCardTransID'];
}
if(isset($response['CustomerCreditCardTxnVoidOrRefundRs']))
{
$result = $response['CustomerCreditCardTxnVoidOrRefundRs']['@attributes']['statusCode'];
$message = $response['CustomerCreditCardTxnVoidOrRefundRs']['@attributes']['statusMessage'];
if(isset($response['CustomerCreditCardTxnVoidOrRefundRs']['CreditCardTransID']))
{
$identifier = $response['CustomerCreditCardTxnVoidOrRefundRs']['CreditCardTransID'];
}
}
$details->gateway_response = $as_array;
if($result === '0')
{ //Transaction was successful
$details->identifier = $identifier;
$details->timestamp = (isset($signon['ServerDateTime'])) ? $signon['ServerDateTime'] : '';
return Payment_Response::instance()->gateway_response(
'Success',
$this->_lib_method.'_success',
$details
);
}
else
{ //Transaction failed
$details->reason = $message;
return Payment_Response::instance()->gateway_response(
'Failure',
$this->_lib_method.'_gateway_failure',
$details
);
}
}
}

View File

@ -0,0 +1,307 @@
<?php
class Stripe_Driver extends Payment_Driver
{
/**
* URL to Use
*/
private $_api_url;
/**
* Endpoint to Send the Query To
*/
private $_endpoint;
/**
* The particular API which is being used
*/
private $_api;
/**
* The particular API method which is being used
*/
private $_api_method;
/**
* The PHP Payments library method
*/
private $_lib_method;
/**
* Stores Settings for the Transaction
*/
private $_settings;
/**
* Whether to Make the Final Call in Object Scope
*/
private $_object_scoped;
/**
* The Constructor Function
*/
public function __construct($config)
{
foreach($config as $k=>$v)
{
$this->_settings[$k] = $v;
}
}
/**
* Call Magic Method
*/
public function __call($method, $params)
{
$args = $params[0];
//If you pass 10 to stripe you don't charge 10 dollars, you charge 10 cents
if(isset($args['amt']) && strpos($args['amt'], '.') === false){
$args['amt'] .= ".00";
}
if(isset($args['amt'][0]) && $args['amt'][0] == '.'){
unset($args['amt'][0]);
}
$method_map = $this->method_map();
$this->_api = $method_map[$method]['api'];
$this->_api_method = (isset($method_map[$method]['method'])) ? $method_map[$method]['method'] : '';
$this->_lib_method = $method;
list($api, $api_method, $params_ready) = $this->_build_request($args);
try {
//If the only param is an id, just use that as a string instead of sending an array
if(count($params_ready) == 1 && isset($params_ready['id'])) $params_ready = $params_ready['id'];
$response_raw = ($this->_object_scoped) ? $api->$api_method() : $api::$api_method($params_ready);
}
catch (Exception $e) {
return Payment_Response::instance()->gateway_response(
'failure',
$method.'_gateway_failure',
$e->getMessage()
);
}
return $this->_parse_response($response_raw);
}
/**
* Maps PHP-Payments Methods to Details Particular to Each Request for that Method
*/
public function method_map()
{
$map = array(
'oneoff_payment' => array(
'api' => 'Stripe_Charge',
'method' => 'create',
'required' => array(
'cc_number',
'cc_exp',
'amt',
'currency_code'
),
'keymatch' => array(
'amt' => 'amount',
'currency_code' => 'currency',
'identifier' => 'customer',
'cc_number' => 'card["number"]',
'cc_exp' => 'card["exp_month,exp_year"]',
'cc_code' => 'card["cvc"]',
'first_name' => 'card["name"]',
'last_name' => 'card["name"]',
'street' => 'card["address_line1"]',
'street2' => 'card["address_line2"]',
'postal_code' => 'card["address_zip"]',
'state' => 'card["address_state"]',
'country' => 'card["address_country"]',
'desc' => 'description'
)
),
'get_transaction_details' => array(
'api' => 'Stripe_Charge',
'method' => 'retrieve',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'id'
)
),
'refund_payment' => array(
'api' => 'Stripe_Charge',
'method' => 'retrieve->refund',
'required' => array(
'identifier'
),
'keymatch' => array(
'identifier' => 'id',
'amt' => 'amount'
)
),
'token_create' => array(
'api' => 'Stripe_Token',
'method' => 'create',
'required' => array(
'cc_number',
'cc_exp'
),
'keymatch' => array(
'identifier' => 'customer',
'cc_number' => 'card["number"]',
'cc_exp' => 'card["exp_month,exp_year"]',
'cc_code' => 'card["cvc"]',
'first_name' => 'card["name"]',
'last_name' => 'card["name"]',
'street' => 'card["address_line1"]',
'street2' => 'card["address_line2"]',
'postal_code' => 'card["address_zip"]',
'state' => 'card["address_state"]',
'country' => 'card["address_country"]',
'desc' => 'description'
)
),
'customer_create' => array(
'api' => 'Stripe_Customer',
'method' => 'create',
'required' => array(
'desc',
'identifier'
),
'keymatch' => array(
'identifier' => 'card',
'desc' => 'description'
)
),
'customer_charge' => array(
'api' => 'Stripe_Charge',
'method' => 'create',
'required' => array(
'amt',
'currency_code',
'identifier'
),
'keymatch' => array(
'identifier' => 'customer',
'amt' => 'amount',
'currency_code' => 'currency'
)
)
);
return $map;
}
/**
* Builds the Request
*/
protected function _build_request($params)
{
$stripe = Payment_Utility::load('file', 'vendor/stripe/lib/Stripe');
Stripe::setApiKey($this->_settings['api_key']);
$api = $this->_api;
if(strpos($this->_api_method, '->') === false)
{
$method = $this->_api_method;
}
else
{
$ex = explode('->', $this->_api_method);
$m1 = $ex[0];
$method = $ex[1];
$api = $api::$m1($params['identifier']);
$this->_object_scoped = true;
}
$params_ready = $this->_match_params($params);
//Make the call to Stripe API
return array($api, $method, $params_ready);
}
/**
* Match the Params
*/
private function _match_params($params)
{
$method_map = $this->method_map();
$l = $this->_lib_method;
$params_ready = array();
$matcher = $method_map[$l]['keymatch'];
foreach($params as $k=>$v)
{
if(isset($matcher[$k]))
{
if(strpos($matcher[$k], '["') !== false)
{
$ex = explode('["', $matcher[$k]);
$arr = $ex[0];
$arrk = str_replace('"]', '', $ex[1]);
if(!isset($params_ready[$arr])) $params_ready[$arr] = array();
if(strpos($arrk, ',') !== false && $k === 'cc_exp')
{
$cex = explode(',', $arrk);
$d_mm = substr($v, 0, 2);
$d_yyyy = substr($v, 2, 4);
$params_ready[$arr][$cex[0]] = $d_mm; //set the month
$params_ready[$arr][$cex[1]] = $d_yyyy; //set the year
}
else
{
$params_ready[$arr][$arrk] = $v;
}
}
else
{
$key = $matcher[$k];
$val = $v;
//Remove the decimal place to format money in cents
if($k == 'amt') $val = str_replace('.', '', $val);
$params_ready[$key] = $val;
}
}
else
{
error_log("$k is not a valid param for this method in this driver");
}
}
return $params_ready;
}
/**
* Parse the response from the server
*
* @param array
* @return object
*/
protected function _parse_response($response)
{
$details = (object) array();
if(isset($response->id)) $details->identifier = $response->id;
$details->timestamp = $response->created;
$details->gateway_response = $response;
return Payment_Response::instance()->gateway_response(
'success',
$this->_lib_method.'_success',
$details
);
}
}

8
vendor/php-payments/lib/payment_method.php vendored Executable file
View File

@ -0,0 +1,8 @@
<?php
interface Payment_Method
{
public function get_params();
public function get_description();
}

View File

@ -0,0 +1,26 @@
<?php
class Activate_Recurring_Profile_Method implements Payment_Method
{
private $_params;
private $_descrip = "This method activates a recurring profile which was previously suspended.";
public function __construct()
{
$this->_params = array(
'identifier' => '2390229', //Required. Should have been returned when you created the profile.
'note' => 'This is a note for making a note on activating this recurring profile.', //This is just a note.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,26 @@
<?php
class Authorize_Payment_Button_Method implements Payment_Method
{
private $_params;
private $_descrip = "This method generates a button which is used to provide the user a link to a hosted payments page on which they can enter their payment information. This method is similar to Authorize_Payment.";
public function __construct()
{
$this->_params = array(
'amt' => '2.00', //Amount for the payment
'desc' => 'Click here to buy me', //A description for the button
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,62 @@
<?php
class Authorize_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "This method ensures that funds are available for a particular transaction and returns an identifier that can later be used to complete the transaction. This method does not charge a user immediately.";
public function __construct()
{
$this->_params = array(
'ip_address' => '138.29.23.29', //IP address of purchaser
'cc_type' => 'Visa', //Visa, MasterCard, Discover, Amex
'cc_number' => '4111111111111111', //Credit card number
'cc_exp' => '022012', //Must be formatted MMYYYY
'cc_code' => '203', //3 or 4 digit cvv code
'email' => 'calvinsemail@gmail.com', //email associated with account being billed
'first_name' => 'Calvin', //first name of the purchaser
'last_name' => 'Froedge', //last name of the purchaser
'business_name' => 'Mango Reservations', //name of business
'street' => 'Some Street', //street address of the purchaser
'street2' => '', //street address 2 of purchaser
'city' => 'Honolulu', //city of the purchaser
'state' => 'HI', //state of the purchaser
'country' => 'US', // country of the purchaser
'postal_code' => '94105', //zip code of the purchaser
'amt' => '50.00', //purchase amount
'phone' => '', //phone num of customer shipped to
'fax' => '(801) 754 4466',
'identifier' => '23432', //Merchant provided identifier for the transaction
'currency_code' => 'USD', //currency code to use for the transaction.
'item_amt' => '40.00', //Amount for just the item being purchased.
'insurance_amt' => '2.00', //Amount for just insurance.
'shipping_disc_amt' => '5.00', //Amount for just shipping.
'handling_amt' => '2.00', //Amount for just handling.
'tax_amt' => '1.00', //Amount for just tax.
'desc' => 'Some cool thing Calvin wants, probably a good programming book.', //Description for the transaction
'custom' => 'Some custom info', //Free form text field
'inv_num' => '234323', //Invoice number
'notify_url' => 'http://notify.me/url', //Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
'ship_to_first_name'=> 'Some',
'ship_to_last_name' => 'Dude',
'ship_to_street' => '100 Somewhere Street',
'ship_to_city' => 'Somwheresville',
'ship_to_state' => 'TN',
'ship_to_postal_code'=> '38501',
'ship_to_country' => 'US',
'ship_to_company' => 'Calvin\'s Company',
'shipping_amt' => '5.00',
'duty_amt' => '0.00',
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,26 @@
<?php
class Cancel_Recurring_Profile_Method implements Payment_Method
{
private $_params;
private $_descrip = "This method cancels recurring billing for a particular recurring billing profile.";
public function __construct()
{
$this->_params = array(
'identifier' => 'PROFILE-23928239', //Required. Should have been returned when you created the profile.
'note' => 'The reason for cancelling this profile', //This is just a note.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,32 @@
<?php
class Capture_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "This method completes a transaction which was previously auhorized.";
public function __construct()
{
$this->_params = array(
'ip_address' => '191.239.29.23', //IP address of purchaser
'cc_type' => 'Visa', //Visa, MasterCard, Discover, Amex
'cc_number' => '4111111111111111', //Credit card number
'cc_exp' => '022012', //Must be formatted MMYYYY
'cc_code' => '203', //3 or 4 digit cvv code
'custom' => 'This is some custom param', //Free form text field
'inv_num' => '1003', //Invoice number
'note' => 'Some note to include with the capture' //A note for the transaction
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,26 @@
<?php
class Change_Transaction_Status_Method implements Payment_Method
{
private $_params;
private $_descrip = "This method is used to alter a transaction's status to Accept or Deny.";
public function __construct()
{
$this->_params = array(
'identifier' => 'TRANS-239239', //Required. Unique identifier for the transaction, generated from a previous transaction.
'action' => 'Accept' //Required. Should be Accept or Deny.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,27 @@
<?php
class Customer_Charge_Method implements Payment_Method
{
private $_params;
private $_descrip = "Charge a customer";
public function __construct()
{
$this->_params = array(
'amt' => '20.00',
'currency_code' => 'usd',
'identifier' => 'PROFILE-2923849' //Some identifier for the transaction
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,26 @@
<?php
class Customer_Create_Method implements Payment_Method
{
private $_params;
private $_descrip = "Create a customer instance which is stored in the gateway.";
public function __construct()
{
$this->_params = array(
'desc' => 'Some description',
'identifier' => 'PROFILE-2923849' //Some identifier for the transaction
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,25 @@
<?php
class Get_Recurring_Profile_Method implements Payment_Method
{
private $_params;
private $_descrip = "Gets a particular recurring profile and returns an object with all the details about it.";
public function __construct()
{
$this->_params = array(
'identifier' => 'PROFILE-2923849', //Required. Should have been returned when you created the profile.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,25 @@
<?php
class Get_Transaction_Details_Method implements Payment_Method
{
private $_params;
private $_descrip = "Gets the logs for a particular transaction from the gateway.";
public function __construct()
{
$this->_params = array(
'identifier' => 'TRANS-239238', //Required. Should have been returned when you created the transaction.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,45 @@
<?php
class Oneoff_Payment_Button_Method implements Payment_Method
{
private $_params;
private $_descrip = "Creates HTML code for a button which directs the user to a hosted payments page on which they can complete the transaction. Similar to Oneoff_Payment.";
public function __construct()
{
$this->_params = array(
'amt' => '10.00', //Amount for the payment
'desc' => 'Your button text',
'notify_url' => 'http://notify.me/url', //Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
'shipping_amt' => '2.00', //The cost of shipping
'tax_amt' => '1.00', //Amount for just tax.
'continue_url' => 'http://continue.after/purchase', //Link for continue shopping button
'edit_url' => 'http://edit.purchase', //Url for editing one's cart
'items' => array(
array(
'desc' => 'Description for an item',
'amt' => '3.50',
'name' => 'The item name',
'qty' => '2'
)
), //An array of items
'shipping_options' => array(
array(
'desc' => 'The shipping option',
'amt' => '2.00'
)
)
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,63 @@
<?php
class Oneoff_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "Performs authorize and capture actions simultaneously. User is charged immediately.";
public function __construct()
{
$this->_params = array(
'ip_address' => '142.392.29.21', //IP address of purchaser
'cc_type' => 'Visa', //Visa, MasterCard, Discover, Amex
'cc_number' => '4111111111111111', //Credit card number
'cc_exp' => '022013', //Must be formatted MMYYYY
'cc_code' => '413', //3 or 4 digit cvv code
'email' => 'calvinsemail@gmail.com', //email associated with account being billed
'first_name' => 'Calvin', //first name of the purchaser
'last_name' => 'Froedge', //last name of the purchaser
'business_name' => 'The Business Name', //name of business
'street' => '251 Somewhere Street', //street address of the purchaser
'street2' => 'Apt B', //street address 2 of purchaser
'city' => 'Somewherton', //city of the purchaser
'state' => 'KY', //state of the purchaser
'country' => 'US', // country of the purchaser
'postal_code' => '42105', //zip code of the purchaser
'amt' => '25.00', //purchase amount
'phone' => '(801) 754 4466', //phone num of customer shipped to
'fax' => '(801) 754 4466',
'identifier' => 'YOUR-IDENTIFIER', //Merchant provided identifier for the transaction
'currency_code' => 'USD', //currency code to use for the transaction.
'item_amt' => '25.00', //Amount for just the item being purchased.
'insurance_amt' => '0.00', //Amount for just insurance.
'shipping_disc_amt' => '0.00',
'handling_amt' => '0.00', //Amount for just handling.
'tax_amt' => '0.00', //Amount for just tax.
'desc' => 'The transaction description', //Description for the transaction
'custom' => 'Anything you want to put here', //Free form text field
'inv_num' => 'YOUR-INV-NUMBER', //Invoice number
'po_num' => 'YOUR-PO-NUMBER',
'notify_url' => 'http://notify.me/url', //Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
'ship_to_first_name'=> 'Some',
'ship_to_last_name' => 'Dude',
'ship_to_street' => '311 North Washington Avenue',
'ship_to_city' => 'Cookeville',
'ship_to_state' => 'TN',
'ship_to_postal_code'=> '38501',
'ship_to_country' => 'US',
'ship_to_company' => 'Some Company',
'shipping_amt' => '0.00', //Amount for just shipping.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,27 @@
<?php
class Recurring_Bill_Outstanding_Method implements Payment_Method
{
private $_params;
private $_descrip = "Bill a particular recurring profile for an amount which previously could not be billed.";
public function __construct()
{
$this->_params = array(
'identifier' => 'PROFILE-IDENTIFIER', //Required. Should have been returned when you created the profile.
'amt' => '35.00', //The outstanding amount to bil. Cannot exceed total owed.
'note' => 'Why the profile is being billed' //This is just a note.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,34 @@
<?php
class Recurring_Payment_Button_Method implements Payment_Method
{
private $_params;
private $_descrip = "Generates an HTML button which redirects a user to a hosted payments page. Similar to Recurring_Payment.";
public function __construct()
{
$this->_params = array(
'amt' => '14.00', //Amount for the payment
'desc' => 'A description for the transaction', //A description for the transaction
'trial_billing_period' => 'Month',
'trial_billing_frequency' => '1', //Set this if you want a trial. Year, month, week, day.
'trial_billing_cycles' => '1', //Total # of times you want the customer to be billed at the trial rate.
'trial_amt' => '10.00', //The trial rate.
'profile_start_date' => '2012-07-18',
'billing_period' => 'Month',
'billing_frequency' => '1',
'total_billing_cycles' => '12'
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,72 @@
<?php
class Recurring_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "A transaction which repeats on a defined interval. Some gateways allow a trial interval as well.";
public function __construct()
{
$this->_params = array(
'profile_start_date' => '2012-05-31', //Required. The subscription start date.
'profile_reference' => 'REF-NUM', //A reference from your own subscription / invoicing system for the subscriber.
'desc' => 'This is my description', //Required. A description for the recurring bill.
'max_failed_payments' => '3', //Maximum # of failed payments before subscription is cancelled
'auto_bill_amt' => '5.00', // ?
'billing_period' => 'Year', //Required. Year, month, week
'billing_frequency' => '1', //Required. Number of times to bill per period
'total_billing_cycles' => '3', //Total # of times the customer will be billed.
'amt' => '25.00', //Required. Amount to bill on a recurring basis.
'trial_billing_frequency' => 'Year', //Set this if you want a trial. Year, month, week.
'trial_billing_cycles' => '1', //Total # of times you want the customer to be billed at the trial rate.
'trial_amt' => '5.00', //The trial rate.
'currency_code' => 'USD', //ie USD
'shipping_amt' => '0.00', //Total of shipping alone.
'tax_amt' => '0.00', //Total of tax alone.
'initial_amt' => '0.00', //billed immediately upon profile creation
'failed_init_action' => 'Continue', //What to do if the initial bill failes. Continue or Cancel.
'inv_num' => 'INV-NUM',
'ship_to_first_name' => 'Calvin', //Name of person being shipped to
'ship_to_last_name' => 'Froedge',
'ship_to_street' => '151 Somewhere Street',
'ship_to_street2' => 'Suite A',
'ship_to_city' => 'Somewhere',
'ship_to_state' => 'KY',
'ship_to_zip' => '42167',
'ship_to_country' => 'United States',
'ship_to_phone_num' => '(801) 754 4466',
'ship_to_company' => 'Some Company',
'cc_type' => 'Visa', //Required. Credit card type.
'cc_number' => '4111111111111111', //Required. Credit card number.
'cc_exp' => '022015', //Required. Credit card expiration date.
'cc_code' => '203', //Required. Credit Card CVV code.
'email' => 'calvinsemail@gmail.com',
'identifier' => 'YOUR-IDENTIFIER',
'country' => 'US', //Required. Buyer's country code.
'business_name' => 'The Business Name',
'salutation' => 'Mr.',
'first_name' => 'Calvin',
'middle_name' => 'P',
'last_name' => 'Froedge',
'suffix' => 'PIMP',
'street' => '317 Kublashayev', //Required. Buyer's street address.
'street2' => '',
'city' => 'Simferople', //Required. Buyer's city.
'state' => 'CR', //Required. Buyer's state or province.
'postal_code' => 'UKR', //Required. Buyer's postal code.
'phone' => '(801) 754 4466',
'fax' => '(801) 754 4466',
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,26 @@
<?php
class Reference_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "Similar to Oneoff_Payment and payment vaulting alike, but allows a user to make a payment just by reference a successfully completed payment which occurred in the past.";
public function __construct()
{
$this->_params = array(
'identifier' => 'PREVIOUS-TRANS-1923932',
'amt' => '30.00'
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

View File

@ -0,0 +1,31 @@
<?php
class Refund_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "Provides a refund for a transaction which has already been settled.";
public function __construct()
{
$this->_params = array(
'identifier' => 'TRANS-ID', //A unique identifier for the transaction
'inv_num' => 'INV-2392329',
'refund_type' => 'Full', //Can be Full or Partial
'amt' => '', //Do not set amount if refund type is Full
'currency_code' => 'USD',
'note' => 'This is a note to send with the refund.',
'last_4_digits' => '4111', //Last 4 digits of the credit card used
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

View File

@ -0,0 +1,41 @@
<?php
class Search_Transactions_Method implements Payment_Method
{
private $_params;
private $_description = "Search transactions previously submitted to the gateway by a set of criteria.";
public function __construct()
{
$this->_params = array(
'start_date' => '2011-07-02T00:24:59+00:00', //REQUIRED. Date to search from.
'end_date' => '2012-07-02T00:24:59+00:00', //Date to search to
'email' => 'calvinsemail@gmail.com', //Email used by purchaser
'receiver' => '293023', //Identifier of receiver
'receipt_id' => '23929', //Receipt id (generated by gateway)
'transaction_id' => '23929232', //Transaction id (generated by gateway)
'inv_num' => '23239', //Invoice number (generated by you, must match what's in gateway)
'cc_number' => '4111111111111111', //The credit card number to use
'transaction_class' => 'DoDirectPayment', //The transaction class (Method of original API query)
'amt' => '25.00', //Transactions of amount..
'currency_code' => 'USD', //Transactions with currency code..
'status' => '', //Transactions with status
'salutation' => 'Mr.', //The buyer's salutation
'first_name' => 'Calvin', //The buyer's first name
'middle_name' => 'P', //The buyer's middle name
'last_name' => 'Froedge', //The buyer's last name
'suffix' => 'PIMP' //The buyer's suffix
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

View File

@ -0,0 +1,26 @@
<?php
class Suspend_Recurring_Profile_Method implements Payment_Method
{
private $_params;
private $_descrip = "Stop billing a reccurring profile.";
public function __construct()
{
$this->_params = array(
'identifier' => 'IDENTIFIER-2392032', //Required. Should have been returned when you created the profile.
'note' => 'This is the note', //This is just a note.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

View File

@ -0,0 +1,44 @@
<?php
class Token_Create_Method implements Payment_Method
{
private $_params;
private $_descrip = "Stores card data on payment server and gives you a secure identifier for the card which can be used to create payments later.";
public function __construct()
{
$this->_params = array(
'cc_type' => 'Visa', //Visa, MasterCard, Discover, Amex
'cc_number' => '4111111111111111', //Credit card number
'cc_exp' => '022013', //Must be formatted MMYYYY
'cc_code' => '413', //3 or 4 digit cvv code
'email' => 'calvinsemail@gmail.com', //email associated with account being billed
'first_name' => 'Calvin', //first name of the purchaser
'last_name' => 'Froedge', //last name of the purchaser
'business_name' => 'The Business Name', //name of business
'street' => '251 Somewhere Street', //street address of the purchaser
'street2' => 'Apt B', //street address 2 of purchaser
'city' => 'Somewherton', //city of the purchaser
'state' => 'KY', //state of the purchaser
'country' => 'US', // country of the purchaser
'postal_code' => '42105', //zip code of the purchaser
'amt' => '25.00', //purchase amount
'phone' => '(801) 754 4466', //phone num of customer shipped to
'fax' => '(801) 754 4466',
'desc' => 'The transaction description', //Description for the transaction
'custom' => 'Anything you want to put here', //Free form text field
'po_num' => 'YOUR-PO-NUMBER',
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip();
}
}

View File

@ -0,0 +1,63 @@
<?php
class Update_Recurring_Profile_Method implements Payment_Method
{
private $_params;
private $_descrip = "Update the details associated with a recurring profile, including user information and billing information.";
public function __construct()
{
$this->_params = array(
'identifier' => 'YOUR-IDENTIFIER', //Merchant provided identifier for the transaction
'ip_address' => '142.392.29.21', //IP address of purchaser
'cc_type' => 'Visa', //Visa, MasterCard, Discover, Amex
'cc_number' => '4111111111111111', //Credit card number
'cc_exp' => '022013', //Must be formatted MMYYYY
'cc_code' => '413', //3 or 4 digit cvv code
'email' => 'calvinsemail@gmail.com', //email associated with account being billed
'first_name' => 'Calvin', //first name of the purchaser
'last_name' => 'Froedge', //last name of the purchaser
'business_name' => 'The Business Name', //name of business
'street' => '251 Somewhere Street', //street address of the purchaser
'street2' => 'Apt B', //street address 2 of purchaser
'city' => 'Somewherton', //city of the purchaser
'state' => 'KY', //state of the purchaser
'country' => 'US', // country of the purchaser
'postal_code' => '42105', //zip code of the purchaser
'amt' => '25.00', //purchase amount
'phone' => '(801) 754 4466', //phone num of customer shipped to
'fax' => '(801) 754 4466',
'currency_code' => 'USD', //currency code to use for the transaction.
'item_amt' => '25.00', //Amount for just the item being purchased.
'insurance_amt' => '0.00', //Amount for just insurance.
'shipping_disc_amt' => '0.00',
'handling_amt' => '0.00', //Amount for just handling.
'tax_amt' => '0.00', //Amount for just tax.
'desc' => 'The transaction description', //Description for the transaction
'custom' => 'Anything you want to put here', //Free form text field
'inv_num' => 'YOUR-INV-NUMBER', //Invoice number
'po_num' => 'YOUR-PO-NUMBER',
'notify_url' => 'http://notify.me/url', //Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
'ship_to_first_name'=> 'Some',
'ship_to_last_name' => 'Dude',
'ship_to_street' => '311 North Washington Avenue',
'ship_to_city' => 'Cookeville',
'ship_to_state' => 'TN',
'ship_to_postal_code'=> '38501',
'ship_to_country' => 'US',
'ship_to_company' => 'Some Company',
'shipping_amt' => '0.00', //Amount for just shipping.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

View File

@ -0,0 +1,26 @@
<?php
class Void_Payment_Method implements Payment_Method
{
private $_params;
private $_descrip = "Tell the gateway not to settle a transaction which has not yet been settled. Similar to a refund, but no monies have been billed to the user yet.";
public function __construct()
{
$this->_params = array(
'identifier' => 'ID2930238', //Required. Unique identifier for the transaction, generated from a previous authorization.
'note' => 'Some note to tell why you voided it.' //An optional note to be submitted along with the request.
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

View File

@ -0,0 +1,39 @@
<?php
class Void_Refund_Method implements Payment_Method
{
private $_params;
private $_descrip = "Second guess a previous void operation. Go ahead and settle. Admittedly a weird API operation.";
public function __construct()
{
$this->_params = array(
'cc_number' => '4111111111111111',
'cc_type' => 'Visa',
'cc_code' => '203',
'cc_exp' => '022012',
'amt' => '14.00',
'first_name' => 'Calvin',
'last_name' => 'Froedge',
'phone' => '(801) 754 4466',
'email' => 'calvintest@gmail.com',
'street' => '311 Something Street',
'city' => 'Cookeville',
'state' => 'TN',
'country' => 'US',
'postal_code' => '38501',
'identifier' => 'IDTEST2039'
);
}
public function get_params()
{
return $this->_params;
}
public function get_description()
{
return $this->_descrip;
}
}

193
vendor/php-payments/lib/payment_request.php vendored Executable file
View File

@ -0,0 +1,193 @@
<?php
class Payment_Request
{
public function __construct(){}
/**
* Returns an xml document
*
* @param array the structure for the xml
* @return string a well-formed XML string
*/
public static function build_xml_request($xml_version, $character_encoding, $xml_params, $parent = NULL, $xml_schema = NULL, $xml_extra = NULL)
{
$encoding = ($character_encoding !== null) ? ' encoding="'.$character_encoding.'"' : '';
$xml = '<?xml version="'.$xml_version.'"'.$encoding.'?>';
if(!is_null($xml_extra))
{
$xml .= '<?'.$xml_extra.'?>';
}
if(!is_null($parent) AND is_null($xml_schema))
{
$xml .= '<'.$parent.'>';
}
if(!is_null($parent) AND !is_null($xml_schema))
{
$xml .= '<'.$parent.' '.$xml_schema.'>';
}
//XML parsing at the server end will break if certain characters are not replaced
Payment_Utility::sanitize_xml_params($xml_params);
$xml .= self::build_nodes($xml_params);
if(!is_null($parent))
{
$xml .= '</'.$parent.'>';
}
return $xml;
}
/**
* Returns a well-formed string of XML nodes
*
* @param array associative array of values
* @return string well-formed XML string
*/
public static function build_nodes($params, $key_to_set = NULL)
{
$string = "";
$dont_wrap = FALSE;
foreach($params as $k=>$v)
{
if(is_bool($v) AND $v === TRUE)
{
$v = 'true';
}
if(is_bool($v) AND $v === FALSE)
{
$v = 'false';
}
if(empty($v) AND $v != '0')
{
unset($k);
continue;
}
if(is_array($v))
{
if($k === 'repeated_key')
{
if($v['wraps'] === FALSE)
{
$dont_wrap = TRUE;
}
$node_name = $v['name'];
$node_contents = self::build_nodes($v['values'], $v['name']);
}
else
{
$node_name = $k;
$node_contents = self::build_nodes($v);
}
}
if(!is_array($v))
{
$node_name = $k;
$node_contents = $v;
}
if($key_to_set !== NULL)
{
$node_name = $key_to_set;
}
if(!empty($node_contents) AND $dont_wrap === TRUE)
{
$string .= $node_contents;
}
if(!empty($node_contents) AND $dont_wrap === FALSE)
{
$string .= '<'.$node_name.'>';
$string .= $node_contents;
$string .= '</'.$node_name.'>';
}
if($node_contents === '0' AND $dont_wrap === TRUE)
{
$string .= $node_contents;
}
if($node_contents === '0' AND $dont_wrap === FALSE)
{
$string .= '<'.$node_name.'>';
$string .= $node_contents;
$string .= '</'.$node_name.'>';
}
}
return $string;
}
/**
* Makes the actual request to the gateway
*
* @param string This is the API endpoint currently being used
* @param string The data to be passed to the API
* @param string A specific content type to define for cURL request
* @return object response object
*/
public static function curl_request($query_string, $payload = NULL, $content_type = NULL, $custom_headers = NULL)
{
$headers = (is_null($custom_headers)) ? array() : $custom_headers;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $query_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
if(is_null($payload))
{
$request = curl_exec($curl);
if($request[0] == '<')
{
return Payment_Utility::parse_xml($request);
}
else
{
return $request;
}
}
else
{
if(is_null($content_type))
{
$xml = TRUE;
$headers[] = "Content-Type: text/xml";
}
else
{
if(strpos($content_type, 'xml') !== FALSE)
{
$xml = TRUE;
}
$headers[] = "Content-Type: $content_type";
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
$request = curl_exec($curl);
if(isset($xml) && $xml === TRUE)
{
return Payment_Utility::parse_xml($request);
}
else
{
return $request;
}
}
}
}

111
vendor/php-payments/lib/payment_response.php vendored Executable file
View File

@ -0,0 +1,111 @@
<?php
class Payment_Response
{
/**
* The Language to Return the Response In
*/
private static $_language = 'english';
/**
* Holds the Instance
*/
private static $_instance = false;
/**
* Response Details Array
*/
private static $_response_details;
/**
* Response Messages Array
*/
private static $_response_messages;
/**
* Response Codes Array
*/
private static $_response_codes;
//Make this a Singleton
private function __construct()
{
self::$_response_details = Payment_Utility::load('lang', self::$_language.'/response_details');
self::$_response_messages = Payment_Utility::load('lang', self::$_language.'/response_messages');
self::$_response_codes = Payment_Utility::load('config', 'payments', 'response_codes');
}
/**
* Instance Manager
*/
public static function instance()
{
self::$_instance = (self::$_instance !== false) ? self::$_instance : new Payment_Response();
return self::$_instance;
}
/**
* Set the Language
*/
public static function set_language($_language, $value)
{
self::$_language = $value;
}
/**
* Get the Language
*/
public static function get_language()
{
return self::$_language;
}
/**
* Returns a local response
*
* @param string can be either 'Success' or 'Failure'
* @param string the response used to grab the code / message
* @param mixed can be string or null.
* @return object
*/
public function local_response($status, $response, $details = null)
{
$status = strtolower($status);
if(!is_null($details))
{
$details_msg = (isset(self::$_response_details[$details])) ? self::$_response_details[$details] : $details;
}
return (object) array
(
'type' => 'local_response',
'status' => $status,
'response_code' => self::$_response_codes[$response],
'response_message' => self::$_response_messages[$response],
'details' => (isset($details_msg)) ? $details_msg : self::$_response_details['no_details']
);
}
/**
* Returns a gateway response
*
* @param string can be either 'Success' or 'Failure'
* @param string the response used to grab the code / message
* @param mixed can be string or null.
* @return object
*/
public function gateway_response($status, $response, $details)
{
return (object) array
(
'type' => 'gateway_response',
'status' => $status,
'response_code' => self::$_response_codes[$response],
'response_message' => self::$_response_messages[$response],
'details' => $details
);
}
}

253
vendor/php-payments/lib/payment_utility.php vendored Executable file
View File

@ -0,0 +1,253 @@
<?php
class Payment_Utility
{
public function __construct(){}
/*
* Checks classes which are attempted to autoload, ensures they are not ignored (ie to prevent conflict with frameworks)
*/
public static $autoload_ignore = array();
/**
* Autoloader. Allows us to call classes without a require or include statement - lookups are referred here
*/
public function class_autoload($class)
{
//If a class name is not going to match, don't bother looking for it - we'll just end up with an exception
if(strpos($class, 'Payment') === false && strpos($class, 'Driver') === false && strpos($class, 'Method') === false) return;
//Ignore classes that should be ignored
foreach(static::$autoload_ignore as $ignore)
{
if(strpos($class, $ignore) !== false) return;
}
$class = strtolower($class);
$base_dir = __DIR__.'/';
if(file_exists($base_dir.$class.'.php'))
{
include_once($base_dir.$class.'.php');
return;
}
else if(file_exists($base_dir.'payment_drivers/'.$class.'.php'))
{
include_once($base_dir.'payment_drivers/'.$class.'.php');
return;
}
else if(file_exists($base_dir.'payment_methods/'.$class.'.php'))
{
include_once($base_dir.'payment_methods/'.$class.'.php');
return;
}
else
{
throw new Exception("Could not find class");
}
}
/**
* Load a resource. Alternative to include / require / etc. Passing a key will return a specific entry in a config / lang array.
*/
public static function load($type, $file, $key = null)
{
$base_dir = dirname(__DIR__);
switch($type)
{
case $type == 'config':
$ob = false;
$path = $base_dir.'/config/'.$file.'.php';
break;
case $type == 'file':
$ob = true;
$path = $base_dir.'/'.$file.'.php';
break;
case $type == 'lang':
$ob = false;
$path = $base_dir.'/language/'.$file.'_lang.php';
break;
default:
die("$type is not a valid filetype to load for Payments");
}
if(!is_file($path)) die("$path does not exist.");
if($ob)
{
ob_start();
include_once($path);
return ob_get_clean();
}
else
{
$f = include $path;
return (isset($f[$key])) ? $f[$key] : $f;
}
}
/**
* Loads all files in a particular directory
*
* @param string A dir to load from
*/
public static function load_all_files($dir)
{
$base_dir = dirname(__DIR__);
foreach(scandir($base_dir.'/'.$dir) as $k=>$v){
//Ignore swap files, directory files, etc.
if($v[0] !== '.' && (substr($v, -3, 3) == 'php') )
{
$file = str_replace('.php', '', $v);
self::load('file', $dir.'/'.$file);
}
}
}
/**
* Arrayize an object
*
* @param object the object to convert to an array
* @return array a converted array
*/
public static function arrayize_object($input)
{
if(!is_object($input))
{
return $input;
}
else
{
$final = array();
$vars = get_object_vars($input);
foreach($vars as $k=>$v)
{
if(is_object($v))
{
$final[$k] = self::arrayize_object($v);
}
else
{
$final[$k] = $v;
}
}
}
return $final;
}
/**
* Sort an array by an array. Modified example from StackOverflow: http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
*
* @param array An array to sort
* @param array An array to sort by
* @return array A sorted array
*/
public static function sort_array_by_array($array, $order) {
$ordered = array();
foreach($order as $key) {
if(array_key_exists($key,$array)) {
$ordered[$key] = $array[$key];
unset($array[$key]);
}
}
return $ordered;
}
/**
* Parses an XML response and creates an object using SimpleXML
*
* @param string raw xml string
* @return object response SimpleXMLElement object
*/
public static function parse_xml($xml_str)
{
$xml_str = trim($xml_str);
$xml_str = preg_replace('/xmlns="(.+?)"/', '', $xml_str);
if($xml_str[0] != '<')
{
$xml_str = explode('<', $xml_str);
if(count($xml_str) > 1)
{
unset($xml_str[0]);
$xml_str = '<'.implode('<', $xml_str);
}
else
{
$xml_str = $xml_str[0];
}
}
try {
$xml = @new SimpleXMLElement($xml_str);
}
catch(Exception $e) {
return Payment_Response::instance()->local_response(
'failure',
'invalid_xml',
$xml_str
);
}
return $xml;
}
/**
* Sanitizes XML params so they will not cause parsing errors on remote end
*
* @param array Reference to XML params
*/
public static function sanitize_xml_params(&$params)
{
if(!function_exists('array_walk_sanitize_callback'))
{
function array_walk_sanitize_callback(&$v, $k)
{
if(strpos($v, '&') !== false) $v = str_replace('&', '&#x26;', $v);
if(strpos($v, '<') !== false) $v = str_replace('<', '&#x3c;', $v);
if(strpos($v, '>') !== false) $v = str_replace('>', '&#x3e;', $v);
}
}
array_walk_recursive($params, 'array_walk_sanitize_callback');
}
/**
* Connection is Secure
*
* Checks whether current connection is secure and will redirect
* to secure version of page if 'force_secure_connection' is TRUE
*
* To Force HTTPS for your entire website, use a .htaccess like the following:
*
* RewriteEngine On
* RewriteCond %{SERVER_PORT} 80
* RewriteRule ^(.*)$ https://domain.com/$1 [R,L]
*
* @link http://davidwalsh.name/force-secure-ssl-htaccess
* @return bool
*/
public static function connection_is_secure($config)
{
// Check whether secure connection is required
if($config['force_secure_connection'] === FALSE)
{
error_log('WARNING!! Using Payment Gateway without Secure Connection!', 0);
return false;
}
// Redirect if NOT secure and forcing a secure connection.
if(($_SERVER['SERVER_PORT'] === '443' && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') === FALSE)
{
$loc = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header($loc);
exit;
}
return true;
}
}

117
vendor/php-payments/lib/payment_validator.php vendored Executable file
View File

@ -0,0 +1,117 @@
<?php
class Payment_Validator
{
public function __construct($payments)
{
$this->utility = $payments['utility'];
$this->payments_config = $payments['payments_config'];
$this->lang = $payments['lang'];
}
/**
* Make sure params are as expected
*
* @param array array of params to check to ensure proper formatting
* @param array array of required params
* @return mixed Will return TRUE if all pass. Will return an object if a param is bad.
*/
public static function validate($method, $params, $required_params)
{
//Append _method to method name
$method = $method."_method";
//We'll need this later
$lang = Payment_Utility::load('lang', 'english/response_details');
//Ensure no invalid methods were passed
include_once('payment_methods/'.$method.'.php');
$m = new $method;
$method_params = $m->get_params();
$bad_params = array();
foreach($params as $k=>$v)
{
if(!isset($method_params[$k]))
{
$bad_params[] = "$k " . $lang['is_not_a_param'];
}
}
if(count($bad_params) > 0)
{
return Payment_Response::instance()->local_response(
'failure',
'invalid_input',
implode(', ', $bad_params)
);
}
//Ensure no required params are missing
$missing = array();
foreach($required_params as $k=>$v)
{
if(!array_key_exists($v, $params) OR empty($params[$v]) OR is_null($params[$v]) OR $params[$v] == ' ')
{
$key = 'missing_'.$v;
if(isset($lang[$key]))
{
$missing[] = $lang[$key];
}
else
{
error_log("$key does not exist in response message language file.");
$missing[] = "$v is required but was not provided";
}
}
}
if(count($missing) > 0)
{
return Payment_Response::instance()->local_response(
'failure',
'required_params_missing',
implode(', ', $missing)
);
}
//Ensure dates match MMYYYY format
if(array_key_exists('cc_exp', $params))
{
$exp_date = $params['cc_exp'];
$m1 = $exp_date[0];
if(strlen($exp_date) != 6 OR !is_numeric($exp_date) OR $m1 > 1)
{
return Payment_Response::instance()->local_response(
'failure',
'invalid_input',
'invalid_date_format'
);
}
}
//Ensure billing period is submitted in normalized form
if(array_key_exists('billing_period', $params))
{
$accepted_billing_period = array(
'Month',
'Day',
'Week',
'Year'
);
if(!in_array($params['billing_period'], $accepted_billing_period))
{
return Payment_Response::instance()->local_response(
'failure',
'invalid_input',
'invalid_billing_period'
);
}
}
return TRUE;
}
}

72
vendor/php-payments/lib/payments.php vendored Executable file
View File

@ -0,0 +1,72 @@
<?php
/**
* PHP-Payments
*
* @package Payments
* @author Calvin Froedge (www.calvinfroedge.com)
* @created 07/02/2011
* @refactored 02/11/2012
* @license http://www.opensource.org/licenses/mit-license.php
*/
class PHP_Payments
{
/**
* Config Property
*/
public $config;
/**
* The constructor function.
*/
public function __construct($config = array())
{
$this->config = $config;
$this->_bootstrap();
Payment_Utility::connection_is_secure($this->config);
}
/**
* Sets up Autoload, Sets Some Properties We Need
*
* @return void
*/
private function _bootstrap()
{
include_once('payment_utility.php');
spl_autoload_register(array(new Payment_Utility, 'class_autoload'));
$this->config = array_merge($this->config, Payment_Utility::load('config', 'payments')); //Note that here, config file configuration rules are merged with what was passed in the constructor. If there is a conflict, what was passed in the constructor is used.
}
/**
* Make a call to a gateway. Uses other helper methods to make the request.
*
* @param string The payment method to use
* @param array $params[0] is the gateway, $params[1] are the params for the request. $params[2] is a config array for the driver.
* @return object Should return a success or failure, along with a response.
*/
public function __call($method, $params)
{
$gateway = $params[0].'_Driver';
$args = $params[1];
$config = (isset($params[2])) ? $params[2] : @Payment_Utility::load('config', 'drivers/'.$params[0]); //Load the driver config if not passed in constructor
$config['mode'] = (isset($this->config['mode']) && $this->config['mode'] === 'test') ? 'test' : 'production';
try {
$driver = new $gateway($config);
}
catch (Exception $e) {
return Payment_Response::instance()->local_response('failure', 'not_a_module', $e->getMessage());
}
$method_map = $driver->method_map();
if(!isset($method_map[$method])) return Payment_Response::instance()->local_response('failure', 'not_a_method');
//Make sure params are in expected format, make sure required have been provided
$validation_check = Payment_Validator::validate($method, $args, $method_map[$method]['required']);
return ($validation_check === true) ? $driver->$method($args) : $validation_check;
}
}

View File

@ -0,0 +1,19 @@
<?php
class Test_Errors
{
public static $errors = array();
public static function set_error($class, $method, $code, $message, $details)
{
$error = array(
'class' => $class,
'method' => $method,
'response_code' => $code,
'response_message' => $message,
'details' => $details
);
self::$errors[] = (object) $error;
}
}

75
vendor/php-payments/tests/test.php vendored Executable file
View File

@ -0,0 +1,75 @@
<?php
class Test
{
/*
* Where is PHP Payments Located?
*/
public $dir;
/*
* Constructor
*/
public function __construct($tests = array())
{
//include PHP Payments
$this->dir = dirname(__DIR__);
include($this->dir."/lib/payments.php");
//Include class helpers. These are all static and do not require instantiation.
foreach(scandir('classes') as $class)
{
if($class[0] !== '.') include "classes/$class";
}
}
/*
* Run a Single Test
*/
public function single($test, $args = array())
{
include "tests/$test.php";
$class_name = 'Test_'.ucfirst(str_replace('.php', '', $test));
$test_instance = new $class_name($this->dir, $args);
$test_instance->run();
}
/*
* Run All Tests
*/
public function all()
{
foreach(scandir('tests') as $test)
{
if($test[0] !== '.' && !is_dir($this->dir.'/tests/tests/'.$test))
{
include "tests/$test";
$class_name = 'Test_'.ucfirst(str_replace('.php', '', $test));
$test_instance = new $class_name($this->dir);
$test_instance->run();
}
}
}
public function destruct()
{
echo "Thankyou for choosing PHP-Payments! Please send questions, comments or donations (via PayPal) to calvinfroedge@gmail.com. If you find a bug, please post it in the issues section of the Git repository: https://github.com/calvinfroedge/PHP-Payments \n \n";
}
}
$test = new Test();
//The 0th element is simply the filename. Get rid of it and reindex the array.
unset($argv[0]);
$argv = array_values($argv);
if(empty($argv))
{
$test->all();
}
else
{
$test_name = $argv[0]; //This should be the name of the test to run
unset($argv[0]);
$test->single($test_name, $argv); //Passing rest of the params to a specific test to set it's options (if any)
}

51
vendor/php-payments/tests/tests/drivers.php vendored Executable file
View File

@ -0,0 +1,51 @@
<?php
class Test_Drivers
{
/*
* The Drivers to Test
*/
public $drivers = array();
/*
* Constructor
*/
public function __construct($dir, $drivers = array())
{
if(empty($drivers))
{
$this->drivers = scandir($dir."/lib/payment_drivers");
}
else
{
foreach($drivers as $k=>$v)
{
if(file_exists($dir."/lib/payment_drivers/$v"."_driver.php"))
{
array_push($this->drivers, $v."_Driver");
}
else
{
error_log("$v driver does not exist");
}
}
}
include('drivers/driver.php');
}
/*
* Run
*/
public function run()
{
foreach($this->drivers as $driver)
{
if($driver[0] !== '.')
{
$driver_instance = new Test_Driver($driver);
$driver_instance->run();
}
}
}
}

View File

@ -0,0 +1,46 @@
<?php
$vals = array(
'all' => array(
'desc' => 'This is a description',
'cc_number' => '4111111111111111',
'cc_code' => '203',
'cc_type' => 'Visa',
'cc_exp' => '022016',
'amt' => '3.00',
'first_name' => 'John',
'last_name' => 'Doe',
'street' => '401 Somewhere street',
'city' => 'Cookeville',
'state' => 'TN',
'postal_code' => '38501',
'email' => 'johndoe@gmail.com',
'desc' => 'Testing',
'profile_start_date' => '2015-05-31',
'start_date' => '2012-05-31',
'billing_period' => 'Month',
'billing_frequency' => '1',
'total_billing_cycles' => '9999',
'country_code' => 'US',
'currency_code' => 'usd',
'phone' => '(239) 239 2392'
),
'authorize_net_driver' => array(
'cc_number' => '4997662409617853',
),
'paypal_paymentspro_driver' => array(
'cc_number' => '4997662409617853'
),
'google_checkout_driver' => array(
'edit_url' => 'http://test.me',
'continue_url' => 'http://test.me'
),
'eway_driver' => array(
'cc_number' => 4444333322221111
),
'beanstream_driver' => array(
'cc_number' => 4030000010001234
)
);
return $vals;

View File

@ -0,0 +1,157 @@
<?php
class Test_Driver
{
public $payments;
/*
* Class name of the driver being tested
*/
public $class_name;
/*
* Instance of the driver being tested
*/
public $class;
/*
* The configuration array used
*/
public $config;
/*
* The methods available, each of which will be tested
*/
public $methods_available;
/*
* The Constructor
*/
public function __construct($driver)
{
$config = array(
'mode' => 'test'
);
echo "\n \n Starting test for $driver \n \n";
$this->payments = new PHP_Payments($config);
$test_config = include('.drivers.test_vals.php');
$class_name = str_replace('.php', '', $driver);
$uc = explode("_", $class_name);
foreach($uc as $k=>$piece)
{
$uc[$k] = ucfirst($piece);
}
$class_name_uc = implode("_", $uc);
$this->class_name = $class_name_uc;
$config_name = str_replace('_driver', '', $class_name);
$loaded_config = Payment_Utility::load('config', 'drivers/'.$config_name);
$this->config = array_merge($config, $test_config);
$this->class = new $class_name_uc(array_merge($config, $loaded_config));
$this->methods_available = $this->class->method_map();
}
/*
* Run the test
*/
public function run()
{
//Reset the identifier
$last_identifier = '';
foreach($this->methods_available as $method=>$method_array)
{
$required = $method_array['required'];
$args = array();
$break = false;
foreach($required as $r)
{
if(isset($this->config[$this->class_name][$r]))
{
$args[$r] = $this->config[$this->class_name][$r];
}
else if(isset($this->config['all'][$r]))
{
$args[$r] = $this->config['all'][$r];
}
if($r == 'identifier')
{
if(empty($last_identifier))
{
Test_Errors::set_error($this->class_name, $method, '000', 'An identifier was not retrieved in the previous transaction, but is required for '.$method.', so failure is certain.', 'No further details available.');
$break = true;
}
else
{
$args['identifier'] = $last_identifier;
}
}
}
//If an error was already found, don't bother calling the method
if($break == true) { continue;}
$result = $this->class->$method($args);
if($result->response_code != 100)
{
Test_Errors::set_error($this->class_name, $method, $result->response_code, $result->response_message, $result->details);
}
if(isset($result->details->identifier))
{
$last_identifier = $result->details->identifier;
}
}
}
/*
* Echo the results of a test to a screen / console
*/
public function result()
{
if(count(Test_Errors::$errors) > 0)
{
echo "Your test resulted in the following Test_Errors \n \n";
$e = Test_Errors::$errors;
foreach($e as $k=>$v)
{
echo "Attempt to perform the ".$e[$k]->method." method on class ".$e[$k]->class." was unsuccessful. The following details may help you in debugging this: \n \n";
echo "The response code: ".$e[$k]->response_code." \n \n";
echo "The response message: ".$e[$k]->response_message." \n \n";
echo "The details of the response: \n \n";
var_dump($e[$k]->details);
echo " \n \n";
if(isset($e[$k]->errors_warnings)) echo "Additionally, the following errors and warnings were observed:";
echo " \n \n";
}
}
}
/*
* Shutdown Routine
*/
public function __destruct()
{
$this->result();
}
}

View File

@ -0,0 +1,119 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Amazon Simple Pay Standard examples</title>
<style type="text/css">
body, div, p, td, th {
font-family : helvetica,sans-serif, arial;
font-size : 12px;
color : #000000;
}
.aws-h1, h1{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 18px;
font-weight: bold;
color: #000000;
}
.aws-h2, h2{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 14px;
color: #c60;
}
.aws-h3, h3{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: #333333;
}
/*table ID selector styles*/
#aws-table {
border-top: 1px solid #cccccc;
border-left: 1px solid #cccccc;
width:95%;
}
#aws-table td{
font-size: 12px;
padding: 5px 5px 5px 5px;
border-bottom: 1px solid #cccccc;
border-right: 1px solid #cccccc;
vertical-align:top;
}
#aws-table th {
font-size: 12px;
padding: 5px 5px 5px 5px;
border-bottom: 1px solid #cccccc;
border-right: 1px solid #cccccc;
vertical-align:top;
background-color: #eeeeee;
color: #333333;
font-size: 12px;
font-weight: bold;
text-align: left;
}
/*code, note, and example styles*/
pre {
font-family: "Courier New", Courier, mono;
font-size: 12px;
margin-top: 5px;
margin-bottom: 5px;
color: #000066;
padding: 5px;
background-color: #eff7ff;
border: 1px dashed #333;
width:75%;
display:block;
}
</style>
</head><body>
<h2>Example for Amazon Simple Pay Merchants</h2>
<p>This section includes examples to help you understand how to form the string
to sign . New lines have been inserted to make the
examples easier to read. Explicit '\n' is used wherever new line is required.</p>
<p>Example Amazon Simple Pay request using POST :</p>
<pre> &lt;form action="https://authorize.payments-sandbox.amazon.com/pba/paypipeline" method="POST"&gt;
&lt;input type="image" src="https://authorize.payments-sandbox.amazon.com/pba/images/payNowButton.png" border="0"&gt;
&lt;input type="hidden" name="signatureVersion" value="2" &gt;
&lt;input type="hidden" name="immediateReturn" value="0" &gt;
&lt;input type="hidden" name="signature" value="Base64Encode(HmacSHA256(string-to-sign))" &gt;
&lt;input type="hidden" name="amount" value="USD 1.1" &gt;
&lt;input type="hidden" name="signatureMethod" value="HmacSHA256" &gt;
&lt;input type="hidden" name="description" value="Test Widget" &gt;
&lt;input type="hidden" name="ipnUrl" value="http://yourwebsite.com/ipn" &gt;
&lt;input type="hidden" name="accessKey" value="YourCallerKey" &gt;
&lt;input type="hidden" name="cobrandingStyle" value="logo" &gt;
&lt;input type="hidden" name="processImmediate" value="1" &gt;
&lt;input type="hidden" name="returnUrl" value="http://yourwebsite.com/return.html" &gt;
&lt;input type="hidden" name="referenceId" value="YourReferenceId" &gt;
&lt;/form&gt;
</pre>
<p>String to sign :</p>
<pre> POST\n
authorize.payments-sandbox.amazon.com\n
/pba/paypipeline\n
accessKey=YourCallerKey
&amp;amount=USD%201.1
&amp;cobrandingStyle=logo
&amp;description=Test%20Widget
&amp;immediateReturn=0
&amp;ipnUrl=http%3A%2F%2Fyourwebsite.com%2Fipn
&amp;processImmediate=1
&amp;referenceId=YourReferenceId
&amp;returnUrl=http%3A%2F%2Fyourwebsite.com%2Freturn.html
&amp;signatureMethod=HmacSHA256
&amp;signatureVersion=2
</pre>
</body></html>

View File

@ -0,0 +1,174 @@
<title>Amazon Simple Pay Standard Readme</title>
<style type="text/css">
body, div, p, td, th {
font-family : helvetica,sans-serif, arial;
font-size : 12px;
color : #000000;
}
.aws-h1, h1{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 18px;
font-weight: bold;
color: #000000;
}
.aws-h2, h2{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 14px;
color: #c60;
}
.aws-h3, h3{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: #333333;
}
/*table ID selector styles*/
#aws-table {
border-top: 1px solid #cccccc;
border-left: 1px solid #cccccc;
width:95%;
}
#aws-table td{
font-size: 12px;
padding: 5px 5px 5px 5px;
border-bottom: 1px solid #cccccc;
border-right: 1px solid #cccccc;
vertical-align:top;
}
#aws-table th {
font-size: 12px;
padding: 5px 5px 5px 5px;
border-bottom: 1px solid #cccccc;
border-right: 1px solid #cccccc;
vertical-align:top;
background-color: #eeeeee;
color: #333333;
font-size: 12px;
font-weight: bold;
text-align: left;
}
/*code, note, and example styles*/
pre {
font-family: "Courier New", Courier, mono;
font-size: 12px;
margin-top: 5px;
margin-bottom: 5px;
color: #000066;
padding: 5px;
background-color: #eff7ff;
border: 1px dashed #333;
width:75%;
display:block;
}
</style>
</head>
<body>
<h2>About this Library</h2>
<ul>
<li>Dynamic button generation helper for Amazon Simple Pay Standard using signature version 2.</li>
<li>Sample Code Version 2.0</li>
<li>Release Date : 2009-11-03</li>
</ul>
<h2>Prerequisites</h2>
<ul>
<li>You must have an Amazon Web Services developer account.<a href="http://aws.amazon.com/fps/">click here</a></li>
<li>You must have an Amazon Payments <b>Sandbox</b> Business Account.<a href="https://payments-sandbox.amazon.com/sdui/sdui/standardbutton">Click here</a></li>
<li>You must use the same email address and password for your Amazon Payments Sandbox Business Account and your Amazon Web Services developer account.</li>
<li>You must have PHP 5.2.10 or later installed</li>
<li>If you want to use this sdk to generate buttons for Production environment then you need to create a Amazon Payments Buisness Account <a href="https://payments.amazon.com/sdui/sdui/index.htm">Click here</a></li>
</ul>
<h2>Contents of sample codes:</h2>
<p>This package contains the following files for helping you to generate Dynamic Buttons for Amazon Simple Pay Standard .</p>
<ol>
<li>SignatureUtils.php - This class contains the following helper functions for calculating signature.</li>
<ul>
<li>signParameters - Takes a map of all the request parameters and
returns base64 encoded signature. Takes additional parameters like httpMethod, (GET or POST), host (e.g.
authorize.payments-sandbox.amazon.com) and requestURI (e.g. /pba/paypipeline) for
signature version 2. The input map should contain signature version parameter
depending on which it computes the signature.</li>
<li>_calculateStringToSignV2 - Takes a map of all the
request parameters along with httpMethod, hostName, requestURL and returns
string-to-sign calculated using signature version 2.</li>
<li>_sign - Takes string-to-sign, aws secret key and signature algorithm (HmacSHA256/HmacSHA1) as inputs and returns base64 encoded signature.</li>
</ul>
<li>ButtonGenerator.php - Generate the html form </li>
<ul>
<li> getSimplePayStandardParams - Takes all the parameters passed by user as input and returns a Map of key-value pairs </li>
<li> getSimplePayStandardForm - Takes a Map of key-value pair as input and returns the html form </li>
<li> GenerateForm - This function takes all the parameters from user, call appropriate function to get signature and generate html form.
It prints the html form on console. </li>
</ul>
<li> StandardButtonSample.php - Sample file to show how to generate buttons using ButtonGenerator.php </li>
<ul><li>It has only main method which makes a call to ButtonGenerator::GenerateForm()with appropriate parameters. </li><ul>
</ol>
<h2>Steps to use this sample:</h2>
<h3>How to Populate the input in StandardButtonSample.php </h3>
<ol>
<li>Sign into your Amazon Web Services developer account and retrieve your Access Key ID and Secret Access Key from <a href="https://aws-portal.amazon.com/gp/aws/developer/account/index.html/?action=access-key">here.</a>
<li> Replace the value of the accessKey constant in the code sample with your Access Key ID</li>
<li> Replace the value of the secretKey constant in the code sample with your Secret Access Key</li>
<li> Replace the values of the following parameters of the Button: </li>
<b>Required Parameters:</b>
<ul>
<li>amount - Enter the amount you want to collect for the item</li>
<li>description - Enter a description of the item</li>
</ul>
<b> Optional Parameters:</b>
<ul>
<li>referenceId - Optionally enter an ID that uniquely identifies this transaction for your records</li>
<li>abandonUrl - Optionally, enter the URL where senders should be redirected if they cancel their transaction</li>
<li>returnUrl - Optionally enter the URL where buyers should be redirected after they complete the transaction</li>
<li>immediateReturn - Optionally, enter "1" if you want to skip the final status page in Amazon Payments</li>
<li>processImmediate - Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"</li>
<li>ipnUrl - Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.</li>
<li> collectShippingAddress - Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information</li>
</ul>
<li> Set the environment to "sandbox" or "prod". (For testing use sandbox)</li>
<li> You can also set the SignatureMethod to either "HmacSHA256" and "HmacSHA1".</li>
</ol>
<h3>How to compile and run the code </h3>
<ol>
<li>Run the code sample as a php application:</li>
<pre>
$php StandardButtonSample.php
</pre>
<li>The code sample will output the HTML for the ' Amazon Simple Pay Standard' widget to the ConsoleYou can now integrate this code into your website.</li>
</ol>
<b>Note:</b>You cannot use your Amazon Payments Business Account as a buyer while testing your ' Amazon Simple Pay Standard' Widgets. You should create a new Amazon Payments Personal Account which you can use as a buyer.
<h2>Examples</h2>
<p><a href="Examples-ASP.html">Examples</a></p>
</body>
</html>

View File

@ -0,0 +1,143 @@
<?php
/**
* PHP Version 5
*
* @category Amazon
* @package Amazon_FPS
* @copyright Copyright 2008-2010 Amazon Technologies, Inc.
* @link http://aws.amazon.com
* @license http://aws.amazon.com/apache2.0 Apache License, Version 2.0
* @version 2008-09-17
*/
require_once 'SignatureUtils.php';
class ButtonGenerator {
const SIGNATURE_KEYNAME = "signature";
const SIGNATURE_METHOD_KEYNAME = "signatureMethod";
const SIGNATURE_VERSION_KEYNAME = "signatureVersion";
const HMAC_SHA1_ALGORITHM = "HmacSHA1";
const HMAC_SHA256_ALGORITHM = "HmacSHA256";
const SIGNATURE_VERSION = "2";
const COBRANDING_STYLE = "logo";
private static $httpMethod = "POST";
public static $SANDBOX_END_POINT = "https://authorize.payments-sandbox.amazon.com/pba/paypipeline";
public static $SANDBOX_IMAGE_LOCATION="https://authorize.payments-sandbox.amazon.com/pba/images/payNowButton.png";
public static $PROD_END_POINT = "https://authorize.payments.amazon.com/pba/paypipeline";
public static $PROD_IMAGE_LOCATION="https://authorize.payments.amazon.com/pba/images/payNowButton.png";
/**
* Function creates a Map of key-value pairs for all valid values passed to the function
* @param accessKey - Put your Access Key here
* @param amount - Enter the amount you want to collect for the item
* @param description - description - Enter a description of the item
* @param referenceId - Optionally enter an ID that uniquely identifies this transaction for your records
* @param abandonUrl - Optionally, enter the URL where senders should be redirected if they cancel their transaction
* @param returnUrl - Optionally enter the URL where buyers should be redirected after they complete the transaction
* @param immediateReturn - Optionally, enter "1" if you want to skip the final status page in Amazon Payments,
* @param processImmediate - Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"
* @param ipnUrl - Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.
* @param collectShippingAddress - Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information.
* @param signatureMethod - Valid values are HmacSHA256 and HmacSHA1
* @return - A map of key of key-value pair for all non null parameters
* @throws Exception
*/
public static function getSimplePayStandardParams($accessKey,$amount, $description, $referenceId, $immediateReturn,
$returnUrl, $abandonUrl, $processImmediate, $ipnUrl, $collectShippingAddress,
$signatureMethod) {
$cobrandingStyle= self::COBRANDING_STYLE;
$formHiddenInputs = array();
if($accessKey!=null) $formHiddenInputs["accessKey"] = $accessKey;
else throw new Exception("Accesskey is Required");
if($amount!=null) $formHiddenInputs["amount"] = $amount;
else throw new Exception("Amount is required");
if($description!=null) $formHiddenInputs["description"] = $description;
else throw new Exception("Description is required");
if($signatureMethod!=null) $formHiddenInputs[self::SIGNATURE_METHOD_KEYNAME] = $signatureMethod;
else throw new Exception("Signature Method is required");
if ($referenceId != null) $formHiddenInputs["referenceId"] = $referenceId;
if ($immediateReturn != null) $formHiddenInputs["immediateReturn"] = $immediateReturn;
if ($returnUrl != null) $formHiddenInputs["returnUrl"] = $returnUrl;
if ($abandonUrl != null) $formHiddenInputs["abandonUrl"] = $abandonUrl;
if ($processImmediate != null) $formHiddenInputs["processImmediate"] = $processImmediate;
if ($ipnUrl != null) $formHiddenInputs["ipnUrl"] = $ipnUrl;
if ($cobrandingStyle != null) $formHiddenInputs["cobrandingStyle"] = $cobrandingStyle;
if ($collectShippingAddress != null) $formHiddenInputs["collectShippingAddress"] = $collectShippingAddress;
$formHiddenInputs[self::SIGNATURE_VERSION_KEYNAME] = self::SIGNATURE_VERSION;
return $formHiddenInputs;
}
/**
* Creates a form from the provided key-value pairs
* @param formHiddenInputs - A map of key of key-value pair for all non null parameters
* @param serviceEndPoint - The Endpoint to be used based on environment selected
* @param imageLocation - The imagelocation based on environment
* @return - An html form created using the key-value pairs
*/
public static function getSimplePayStandardForm(array $formHiddenInputs,$endPoint,$imageLocation) {
$form = "";
$form .= "<form action=\"";
$form .= $endPoint;
$form .= "\" method=\"";
$form .= self::$httpMethod . "\">\n";
$form .= "<input type=\"image\" src=\"".$imageLocation."\" border=\"0\">\n";
foreach ($formHiddenInputs as $name => $value) {
$form .= "<input type=\"hidden\" name=\"$name";
$form .= "\" value=\"$value";
$form .= "\" >\n";
}
$form .= "</form>\n";
return $form;
}
/**
* Function Generates the html form
* @param accessKey - Put your Access Key here
* @param secretKey - Put your secret Key here
* @param amount - Enter the amount you want to collect for the ite
* @param description - description - Enter a description of the item
* @param referenceId - Optionally enter an ID that uniquely identifies this transaction for your records
* @param abandonUrl - Optionally, enter the URL where senders should be redirected if they cancel their transaction
* @param returnUrl - Optionally enter the URL where buyers should be redirected after they complete the transaction
* @param immediateReturn - Optionally, enter "1" if you want to skip the final status page in Amazon Payments,
* @param processImmediate - Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"
* @param ipnUrl - Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.
* @param collectShippingAddress - Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information
* @param signatureMethod - Valid values are HmacSHA256 and HmacSHA1
* @param environment - Sets the environment where your form will point to can be "sandbox" or "prod"
* @return - A map of key of key-value pair for all non null parameters
* @throws Exception
*/
public static function GenerateForm($accessKey,$secretKey,$amount, $description, $referenceId, $immediateReturn,
$returnUrl, $abandonUrl, $processImmediate, $ipnUrl,$collectShippingAddress,
$signatureMethod,$environment) {
if($environment=="prod"){
$endPoint = self::$PROD_END_POINT;
$imageLocation = self::$PROD_IMAGE_LOCATION;
}
else
{
$endPoint= self::$SANDBOX_END_POINT;
$imageLocation = self::$SANDBOX_IMAGE_LOCATION;
}
$params = self::getSimplePayStandardParams($accessKey,$amount, $description, $referenceId, $immediateReturn,
$returnUrl, $abandonUrl, $processImmediate, $ipnUrl,$collectShippingAddress, $signatureMethod);
$serviceEndPoint = parse_url($endPoint);
$signature = SignatureUtils::signParameters($params, $secretKey,
self::$httpMethod, $serviceEndPoint['host'], $serviceEndPoint['path'],$signatureMethod);
$params[self::SIGNATURE_KEYNAME] = $signature;
$simplePayForm = self::getSimplePayStandardForm($params,$endPoint,$imageLocation);
print $simplePayForm . "\n";
}
}
?>

View File

@ -0,0 +1,112 @@
<?php
/**
* PHP Version 5
*
* @category Amazon
* @package Amazon_FPS
* @copyright Copyright 2008-2010 Amazon Technologies, Inc.
* @link http://aws.amazon.com
* @license http://aws.amazon.com/apache2.0 Apache License, Version 2.0
* @version 2008-09-17
*/
class SignatureUtils
{
/**
* Computes RFC 2104-compliant HMAC signature for request parameters
* Implements AWS Signature, as per following spec:
*
* In Signature Version 2, string to sign is based on following:
*
* 1. The HTTP Request Method followed by an ASCII newline (%0A)
* 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline.
* 3. The URL encoded HTTP absolute path component of the URI
* (up to but not including the query string parameters);
* if this is empty use a forward '/'. This parameter is followed by an ASCII newline.
* 4. The concatenation of all query string components (names and values)
* as UTF-8 characters which are URL encoded as per RFC 3986
* (hex characters MUST be uppercase), sorted using lexicographic byte ordering.
* Parameter names are separated from their values by the '=' character
* (ASCII character 61), even if the value is empty.
* Pairs of parameter and values are separated by the '&' character (ASCII code 38).
*
*/
/**
* This function call appropriate functions for calculating signature
* @param array $parameters request parameters
* @param key - Secret key
* @param httpMethod - httpMethos used
* @param host - Host
* @requestURi - Path
*/
public static function signParameters(array $parameters, $key, $httpMethod, $host, $requestURI,$algorithm) {
$stringToSign = null;
$stringToSign = self::_calculateStringToSignV2($parameters, $httpMethod, $host, $requestURI);
return self::_sign($stringToSign, $key, $algorithm);
}
/**
* Calculate String to Sign for SignatureVersion 2
* @param array $parameters request parameters
* @return String to Sign
*/
private static function _calculateStringToSignV2(array $parameters, $httpMethod, $hostHeader, $requestURI) {
if ($httpMethod == null) {
throw new Exception("HttpMethod cannot be null");
}
$data = $httpMethod;
$data .= "\n";
if ($hostHeader == null) {
$hostHeader = "";
}
$data .= $hostHeader;
$data .= "\n";
if (!isset ($requestURI)) {
$requestURI = "/";
}
$uriencoded = implode("/", array_map(array("SignatureUtils", "_urlencode"), explode("/", $requestURI)));
$data .= $uriencoded;
$data .= "\n";
uksort($parameters, 'strcmp');
$data .= self::_getParametersAsString($parameters);
return $data;
}
private static function _urlencode($value) {
return str_replace('%7E', '~', rawurlencode($value));
}
/**
* Convert paremeters to Url encoded query string
*/
public static function _getParametersAsString(array $parameters) {
$queryParameters = array();
foreach ($parameters as $key => $value) {
$queryParameters[] = $key . '=' . self::_urlencode($value);
}
return implode('&', $queryParameters);
}
/**
* Computes RFC 2104-compliant HMAC signature.
*/
private static function _sign($data, $key, $algorithm) {
if ($algorithm === 'HmacSHA1') {
$hash = 'sha1';
} else if ($algorithm === 'HmacSHA256') {
$hash = 'sha256';
} else {
throw new Exception ("Non-supported signing method specified");
}
return base64_encode(
hash_hmac($hash, $data, $key, true)
);
}
}
?>

View File

@ -0,0 +1,43 @@
<?php
/**
* PHP Version 5
*
* @category Amazon
* @package Amazon_FPS
* @copyright Copyright 2008-2010 Amazon Technologies, Inc.
* @link http://aws.amazon.com
* @license http://aws.amazon.com/apache2.0 Apache License, Version 2.0
* @version 2008-09-17
*/
require_once 'ButtonGenerator.php';
class StandardButtonSample {
private static $accessKey = "<insert-your-access-key-here>"; //Put your Access Key here
private static $secretKey = "<insert-your-secret-key-here>"; //Put your Secret Key here
private static $amount="USD 1.1"; //Enter the amount you want to collect for the item
private static $signatureMethod="HmacSHA256"; // Valid values are HmacSHA256 and HmacSHA1.
private static $description="Test Widget"; //Enter a description of the item
private static $referenceId="test-reference123"; //Optionally, enter an ID that uniquely identifies this transaction for your records
private static $abandonUrl="http://yourwebsite.com/cancel.html"; //Optionally, enter the URL where senders should be redirected if they cancel their transaction
private static $returnUrl="http://yourwebsite.com/return.html"; //Optionally enter the URL where buyers should be redirected after they complete the transaction
private static $immediateReturn="0"; //Optionally, enter "1" if you want to skip the final status page in Amazon Payments
private static $processImmediate="1"; //Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"
private static $ipnUrl="http://yourwebsite.com/ipn"; //Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.
private static $collectShippingAddress=null; //Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information
private static $environment="sandbox"; //Valid values are "sandbox" or "prod"
public static function Sampleform() {
try{
ButtonGenerator::GenerateForm(self::$accessKey,self::$secretKey,self::$amount, self::$description, self::$referenceId, self::$immediateReturn,self::$returnUrl, self::$abandonUrl, self::$processImmediate, self::$ipnUrl, self::$collectShippingAddress,self::$signatureMethod, self::$environment);
}
catch(Exception $e){
echo 'Exception : ', $e->getMessage(),"\n";
}
}
}
StandardButtonSample::SampleForm();
?>

View File

@ -0,0 +1,168 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Amazon FPS PHP Library Ver-2008-09-17</title>
<style type="text/css">
body, div, p, td, th {
font-family : helvetica,sans-serif, arial;
font-size : 12px;
color : #000000;
}
.aws-h1, h1{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 18px;
font-weight: bold;
color: #000000;
}
.aws-h2, h2{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 14px;
color: #c60;
}
.aws-h3, h3{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: #333333;
}
/*table ID selector styles*/
#aws-table {
border-top: 1px solid #cccccc;
border-left: 1px solid #cccccc;
width:95%;
}
#aws-table td{
font-size: 12px;
padding: 5px 5px 5px 5px;
border-bottom: 1px solid #cccccc;
border-right: 1px solid #cccccc;
vertical-align:top;
}
#aws-table th {
font-size: 12px;
padding: 5px 5px 5px 5px;
border-bottom: 1px solid #cccccc;
border-right: 1px solid #cccccc;
vertical-align:top;
background-color: #eeeeee;
color: #333333;
font-size: 12px;
font-weight: bold;
text-align: left;
}
/*code, note, and example styles*/
pre {
font-family: "Courier New", Courier, mono;
font-size: 12px;
margin-top: 5px;
margin-bottom: 5px;
color: #000066;
padding: 5px;
background-color: #eff7ff;
border: 1px dashed #333;
width:75%;
display:block;
}
</style>
</head>
<body>
<h2>About this Library</h2>
<ul>
<li>Based on the 2008-09-17 API version.</li>
<li>Version 2.0</li>
<li>Release Date : 2009-11-03</li>
</ul>
<h2>Prerequisites</h2>
<ul>
<li>Amazon FPS Sandbox Account (<a href="https://developer.payments-sandbox.amazon.com/landingpage/">Click here to sign up</a>).</li>
<li>Amazon FPS Developer Account (<a href="http://aws.amazon.com/fps">Click here to sign up</a>).</li>
</ul>
<h2>Package Content</h2>
<table id="aws-table">
<tbody>
<tr>
<th>Directory</th>
<th>Overview</th>
</tr>
<tr>
<td>
src
</td>
<td>
Source distribution of the library. All sources including code samples that demonstrate the use of the library located under this directory.
</td>
</tr>
</tbody>
</table>
<h2>Steps to make a sample (Refund) API call</h2>
<ul>
<li> Open RefundSample.php in src/Amazon/FPS/Samples </li>
</ul>
<ul>
<li> Set request parameters. For example, find following pre-generated snippet:</li>
<pre>
// @TODO: set request. Action can be passed as Amazon_FPS_Model_RefundRequest
// object or array of parameters
// invokeRefund($service, $request);
</pre>
</ul>
<ul>
<li>Uncomment third line and set Refund request parameters</li>
<pre>
$request = new Amazon_FPS_Model_RefundRequest();
$request->setTransactionId("YourOriginalTransactionIdForWhichYouWantTheRefund");
$amount = new Amazon_FPS_Model_Amount();
$amount->setCurrencyCode(CurrencyCode.USD);
$amount->setValue("1");
$request->setRefundAmount(amount);
$request->setCallerReference("ABCDEFGHIJKL12345");
$request->setCallerDescription("Ecommerce Merchant - FPSBuy.com");
</pre>
<li>run sample. You should see the output similar to the following:</li>
<pre>
RefundResponse
RefundResult
TransactionId
14GK6F2QU755ODS27SGHEURLKPG72Z54KMF
TransactionStatus
Pending
ResponseMetadata
RequestId
1a146b9a-b37b-4f5f-bda6-012a5b9e45c3:0
</pre>
<li>Experiment with other samples, examine samples sources. When ready, add library project to your solution, and use it</li>
<li>If the response status is Pending, you can use <tt>GetTransactionStatus</tt> API to get latest transaction status</li>
<li>Use the samples in IPNAndReturnURLValidator package for validating and receiving IPNs for this refund transaction</li>
</ul>
</ol>
<h2>Related resources</h2>
<a href="http://aws.amazon.com/fps/">More about Amazon FPS</a>
<br/>
<a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=2022&categoryID=277">Documentation</a>
<br/>
<a href="http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=126">Code samples</a>
<br/>
<a href="http://developer.amazonwebservices.com/connect/forum.jspa?forumID=35">Contact us for technical issues</a>
<br/>
<h2>Comments, Questions or Feedback</h2>
If you have any comments, questions or feedback on the library, please start discussion here (<a href="http://developer.amazonwebservices.com/connect/forum.jspa?forumID=35">Amazon FPS forum</a>).
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,140 @@
<?php
/**
* PHP Version 5
*
* @category Amazon
* @package Amazon_FPS
* @copyright Copyright 2008-2010 Amazon Technologies, Inc.
* @link http://aws.amazon.com
* @license http://aws.amazon.com/apache2.0 Apache License, Version 2.0
* @version 2008-09-17
*/
/*******************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* Amazon FPS PHP5 Library
* Generated: Wed Sep 23 03:35:04 PDT 2009
*
*/
/**
* FPS Exception provides details of errors
* returned by FPS service
*
*/
class Amazon_FPS_Exception extends Exception
{
/** @var string */
private $_message = null;
/** @var int */
private $_statusCode = -1;
/** @var string */
private $_errorCode = null;
/** @var string */
private $_errorType = null;
/** @var string */
private $_requestId = null;
/** @var string */
private $_xml = null;
/**
* Constructs Amazon_FPS_Exception
* @param array $errorInfo details of exception.
* Keys are:
* <ul>
* <li>Message - (string) text message for an exception</li>
* <li>StatusCode - (int) HTTP status code at the time of exception</li>
* <li>ErrorCode - (string) specific error code returned by the service</li>
* <li>ErrorType - (string) Possible types: Sender, Receiver or Unknown</li>
* <li>RequestId - (string) request id returned by the service</li>
* <li>XML - (string) compete xml response at the time of exception</li>
* <li>Exception - (Exception) inner exception if any</li>
* </ul>
*
*/
public function __construct(array $errorInfo = array())
{
$this->_message = $errorInfo["Message"];
parent::__construct($this->_message);
if (array_key_exists("Exception", $errorInfo)) {
$exception = $errorInfo["Exception"];
if ($exception instanceof Amazon_FPS_Exception) {
$this->_statusCode = $exception->getStatusCode();
$this->_errorCode = $exception->getErrorCode();
$this->_errorType = $exception->getErrorType();
$this->_requestId = $exception->getRequestId();
$this->_xml= $exception->getXML();
}
} else {
$this->_statusCode = $errorInfo["StatusCode"];
$this->_errorCode = $errorInfo["ErrorCode"];
$this->_errorType = $errorInfo["ErrorType"];
$this->_requestId = $errorInfo["RequestId"];
$this->_xml= $errorInfo["XML"];
}
}
/**
* Gets error type returned by the service if available.
*
* @return string Error Code returned by the service
*/
public function getErrorCode(){
return $this->_errorCode;
}
/**
* Gets error type returned by the service.
*
* @return string Error Type returned by the service.
* Possible types: Sender, Receiver or Unknown
*/
public function getErrorType(){
return $this->_errorType;
}
/**
* Gets error message
*
* @return string Error message
*/
public function getErrorMessage() {
return $this->_message;
}
/**
* Gets status code returned by the service if available. If status
* code is set to -1, it means that status code was unavailable at the
* time exception was thrown
*
* @return int status code returned by the service
*/
public function getStatusCode() {
return $this->_statusCode;
}
/**
* Gets XML returned by the service if available.
*
* @return string XML returned by the service
*/
public function getXML() {
return $this->_xml;
}
/**
* Gets Request ID returned by the service if available.
*
* @return string Request ID returned by the service
*/
public function getRequestId() {
return $this->_requestId;
}
}

View File

@ -0,0 +1,438 @@
<?php
/**
* PHP Version 5
*
* @category Amazon
* @package Amazon_FPS
* @copyright Copyright 2008-2010 Amazon Technologies, Inc.
* @link http://aws.amazon.com
* @license http://aws.amazon.com/apache2.0 Apache License, Version 2.0
* @version 2008-09-17
*/
/*******************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* Amazon FPS PHP5 Library
* Generated: Wed Sep 23 03:35:04 PDT 2009
*
*/
/**
*
* Amazon Flexible Payments Service
*
*/
interface Amazon_FPS_Interface
{
/**
* Cancel Token
*
* Cancels any token installed by the calling application on its own account.
*
* @see http://docs.amazonwebservices.com/${docPath}CancelToken.html
* @param mixed $request array of parameters for Amazon_FPS_Model_CancelTokenRequest request
* or Amazon_FPS_Model_CancelTokenRequest object itself
* @see Amazon_FPS_Model_CancelTokenRequest
* @return Amazon_FPS_Model_CancelTokenResponse Amazon_FPS_Model_CancelTokenResponse
*
* @throws Amazon_FPS_Exception
*/
public function cancelToken($request);
/**
* Cancel
*
* Cancels an ongoing transaction and puts it in cancelled state.
*
* @see http://docs.amazonwebservices.com/${docPath}Cancel.html
* @param mixed $request array of parameters for Amazon_FPS_Model_CancelRequest request
* or Amazon_FPS_Model_CancelRequest object itself
* @see Amazon_FPS_Model_CancelRequest
* @return Amazon_FPS_Model_CancelResponse Amazon_FPS_Model_CancelResponse
*
* @throws Amazon_FPS_Exception
*/
public function cancel($request);
/**
* Fund Prepaid
*
* Funds the prepaid balance on the given prepaid instrument.
*
* @see http://docs.amazonwebservices.com/${docPath}FundPrepaid.html
* @param mixed $request array of parameters for Amazon_FPS_Model_FundPrepaidRequest request
* or Amazon_FPS_Model_FundPrepaidRequest object itself
* @see Amazon_FPS_Model_FundPrepaidRequest
* @return Amazon_FPS_Model_FundPrepaidResponse Amazon_FPS_Model_FundPrepaidResponse
*
* @throws Amazon_FPS_Exception
*/
public function fundPrepaid($request);
/**
* Get Account Activity
*
* Returns transactions for a given date range.
*
* @see http://docs.amazonwebservices.com/${docPath}GetAccountActivity.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetAccountActivityRequest request
* or Amazon_FPS_Model_GetAccountActivityRequest object itself
* @see Amazon_FPS_Model_GetAccountActivityRequest
* @return Amazon_FPS_Model_GetAccountActivityResponse Amazon_FPS_Model_GetAccountActivityResponse
*
* @throws Amazon_FPS_Exception
*/
public function getAccountActivity($request);
/**
* Get Account Balance
*
* Returns the account balance for an account in real time.
*
* @see http://docs.amazonwebservices.com/${docPath}GetAccountBalance.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetAccountBalanceRequest request
* or Amazon_FPS_Model_GetAccountBalanceRequest object itself
* @see Amazon_FPS_Model_GetAccountBalanceRequest
* @return Amazon_FPS_Model_GetAccountBalanceResponse Amazon_FPS_Model_GetAccountBalanceResponse
*
* @throws Amazon_FPS_Exception
*/
public function getAccountBalance($request);
/**
* Get Debt Balance
*
* Returns the balance corresponding to the given credit instrument.
*
* @see http://docs.amazonwebservices.com/${docPath}GetDebtBalance.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetDebtBalanceRequest request
* or Amazon_FPS_Model_GetDebtBalanceRequest object itself
* @see Amazon_FPS_Model_GetDebtBalanceRequest
* @return Amazon_FPS_Model_GetDebtBalanceResponse Amazon_FPS_Model_GetDebtBalanceResponse
*
* @throws Amazon_FPS_Exception
*/
public function getDebtBalance($request);
/**
* Get Outstanding Debt Balance
*
* Returns the total outstanding balance for all the credit instruments for the given creditor account.
*
* @see http://docs.amazonwebservices.com/${docPath}GetOutstandingDebtBalance.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetOutstandingDebtBalanceRequest request
* or Amazon_FPS_Model_GetOutstandingDebtBalanceRequest object itself
* @see Amazon_FPS_Model_GetOutstandingDebtBalanceRequest
* @return Amazon_FPS_Model_GetOutstandingDebtBalanceResponse Amazon_FPS_Model_GetOutstandingDebtBalanceResponse
*
* @throws Amazon_FPS_Exception
*/
public function getOutstandingDebtBalance($request);
/**
* Get Prepaid Balance
*
* Returns the balance available on the given prepaid instrument.
*
* @see http://docs.amazonwebservices.com/${docPath}GetPrepaidBalance.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetPrepaidBalanceRequest request
* or Amazon_FPS_Model_GetPrepaidBalanceRequest object itself
* @see Amazon_FPS_Model_GetPrepaidBalanceRequest
* @return Amazon_FPS_Model_GetPrepaidBalanceResponse Amazon_FPS_Model_GetPrepaidBalanceResponse
*
* @throws Amazon_FPS_Exception
*/
public function getPrepaidBalance($request);
/**
* Get Token By Caller
*
* Returns the details of a particular token installed by this calling application using the subway co-branded UI.
*
* @see http://docs.amazonwebservices.com/${docPath}GetTokenByCaller.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetTokenByCallerRequest request
* or Amazon_FPS_Model_GetTokenByCallerRequest object itself
* @see Amazon_FPS_Model_GetTokenByCallerRequest
* @return Amazon_FPS_Model_GetTokenByCallerResponse Amazon_FPS_Model_GetTokenByCallerResponse
*
* @throws Amazon_FPS_Exception
*/
public function getTokenByCaller($request);
/**
* Cancel Subscription And Refund
*
* Cancels a subscription.
*
* @see http://docs.amazonwebservices.com/${docPath}CancelSubscriptionAndRefund.html
* @param mixed $request array of parameters for Amazon_FPS_Model_CancelSubscriptionAndRefundRequest request
* or Amazon_FPS_Model_CancelSubscriptionAndRefundRequest object itself
* @see Amazon_FPS_Model_CancelSubscriptionAndRefundRequest
* @return Amazon_FPS_Model_CancelSubscriptionAndRefundResponse Amazon_FPS_Model_CancelSubscriptionAndRefundResponse
*
* @throws Amazon_FPS_Exception
*/
public function cancelSubscriptionAndRefund($request);
/**
* Get Token Usage
*
* Returns the usage of a token.
*
* @see http://docs.amazonwebservices.com/${docPath}GetTokenUsage.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetTokenUsageRequest request
* or Amazon_FPS_Model_GetTokenUsageRequest object itself
* @see Amazon_FPS_Model_GetTokenUsageRequest
* @return Amazon_FPS_Model_GetTokenUsageResponse Amazon_FPS_Model_GetTokenUsageResponse
*
* @throws Amazon_FPS_Exception
*/
public function getTokenUsage($request);
/**
* Get Tokens
*
* Returns a list of tokens installed on the given account.
*
* @see http://docs.amazonwebservices.com/${docPath}GetTokens.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetTokensRequest request
* or Amazon_FPS_Model_GetTokensRequest object itself
* @see Amazon_FPS_Model_GetTokensRequest
* @return Amazon_FPS_Model_GetTokensResponse Amazon_FPS_Model_GetTokensResponse
*
* @throws Amazon_FPS_Exception
*/
public function getTokens($request);
/**
* Get Total Prepaid Liability
*
* Returns the total liability held by the given account corresponding to all the prepaid instruments owned by the account.
*
* @see http://docs.amazonwebservices.com/${docPath}GetTotalPrepaidLiability.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetTotalPrepaidLiabilityRequest request
* or Amazon_FPS_Model_GetTotalPrepaidLiabilityRequest object itself
* @see Amazon_FPS_Model_GetTotalPrepaidLiabilityRequest
* @return Amazon_FPS_Model_GetTotalPrepaidLiabilityResponse Amazon_FPS_Model_GetTotalPrepaidLiabilityResponse
*
* @throws Amazon_FPS_Exception
*/
public function getTotalPrepaidLiability($request);
/**
* Get Transaction
*
* Returns all details of a transaction.
*
* @see http://docs.amazonwebservices.com/${docPath}GetTransaction.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetTransactionRequest request
* or Amazon_FPS_Model_GetTransactionRequest object itself
* @see Amazon_FPS_Model_GetTransactionRequest
* @return Amazon_FPS_Model_GetTransactionResponse Amazon_FPS_Model_GetTransactionResponse
*
* @throws Amazon_FPS_Exception
*/
public function getTransaction($request);
/**
* Get Transaction Status
*
* Gets the latest status of a transaction.
*
* @see http://docs.amazonwebservices.com/${docPath}GetTransactionStatus.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetTransactionStatusRequest request
* or Amazon_FPS_Model_GetTransactionStatusRequest object itself
* @see Amazon_FPS_Model_GetTransactionStatusRequest
* @return Amazon_FPS_Model_GetTransactionStatusResponse Amazon_FPS_Model_GetTransactionStatusResponse
*
* @throws Amazon_FPS_Exception
*/
public function getTransactionStatus($request);
/**
* Get Payment Instruction
*
* Gets the payment instruction of a token.
*
* @see http://docs.amazonwebservices.com/${docPath}GetPaymentInstruction.html
* @param mixed $request array of parameters for Amazon_FPS_Model_GetPaymentInstructionRequest request
* or Amazon_FPS_Model_GetPaymentInstructionRequest object itself
* @see Amazon_FPS_Model_GetPaymentInstructionRequest
* @return Amazon_FPS_Model_GetPaymentInstructionResponse Amazon_FPS_Model_GetPaymentInstructionResponse
*
* @throws Amazon_FPS_Exception
*/
public function getPaymentInstruction($request);
/**
* Install Payment Instruction
* Installs a payment instruction for caller.
*
* @see http://docs.amazonwebservices.com/${docPath}InstallPaymentInstruction.html
* @param mixed $request array of parameters for Amazon_FPS_Model_InstallPaymentInstructionRequest request
* or Amazon_FPS_Model_InstallPaymentInstructionRequest object itself
* @see Amazon_FPS_Model_InstallPaymentInstructionRequest
* @return Amazon_FPS_Model_InstallPaymentInstructionResponse Amazon_FPS_Model_InstallPaymentInstructionResponse
*
* @throws Amazon_FPS_Exception
*/
public function installPaymentInstruction($request);
/**
* Pay
*
* Allows calling applications to move money from a sender to a recipient.
*
* @see http://docs.amazonwebservices.com/${docPath}Pay.html
* @param mixed $request array of parameters for Amazon_FPS_Model_PayRequest request
* or Amazon_FPS_Model_PayRequest object itself
* @see Amazon_FPS_Model_PayRequest
* @return Amazon_FPS_Model_PayResponse Amazon_FPS_Model_PayResponse
*
* @throws Amazon_FPS_Exception
*/
public function pay($request);
/**
* Refund
*
* Refunds a previously completed transaction.
*
* @see http://docs.amazonwebservices.com/${docPath}Refund.html
* @param mixed $request array of parameters for Amazon_FPS_Model_RefundRequest request
* or Amazon_FPS_Model_RefundRequest object itself
* @see Amazon_FPS_Model_RefundRequest
* @return Amazon_FPS_Model_RefundResponse Amazon_FPS_Model_RefundResponse
*
* @throws Amazon_FPS_Exception
*/
public function refund($request);
/**
* Reserve
*
* Reserve API is part of the Reserve and Settle API conjunction that serve the purpose of a pay where the authorization and settlement have a timing difference.
*
* @see http://docs.amazonwebservices.com/${docPath}Reserve.html
* @param mixed $request array of parameters for Amazon_FPS_Model_ReserveRequest request
* or Amazon_FPS_Model_ReserveRequest object itself
* @see Amazon_FPS_Model_ReserveRequest
* @return Amazon_FPS_Model_ReserveResponse Amazon_FPS_Model_ReserveResponse
*
* @throws Amazon_FPS_Exception
*/
public function reserve($request);
/**
* Settle
*
* The Settle API is used in conjunction with the Reserve API and is used to settle previously reserved transaction.
*
* @see http://docs.amazonwebservices.com/${docPath}Settle.html
* @param mixed $request array of parameters for Amazon_FPS_Model_SettleRequest request
* or Amazon_FPS_Model_SettleRequest object itself
* @see Amazon_FPS_Model_SettleRequest
* @return Amazon_FPS_Model_SettleResponse Amazon_FPS_Model_SettleResponse
*
* @throws Amazon_FPS_Exception
*/
public function settle($request);
/**
* Settle Debt
*
* Allows a caller to initiate a transaction that atomically transfers money from a senders payment instrument to the recipient, while decreasing corresponding debt balance.
*
* @see http://docs.amazonwebservices.com/${docPath}SettleDebt.html
* @param mixed $request array of parameters for Amazon_FPS_Model_SettleDebtRequest request
* or Amazon_FPS_Model_SettleDebtRequest object itself
* @see Amazon_FPS_Model_SettleDebtRequest
* @return Amazon_FPS_Model_SettleDebtResponse Amazon_FPS_Model_SettleDebtResponse
*
* @throws Amazon_FPS_Exception
*/
public function settleDebt($request);
/**
* Write Off Debt
*
* Allows a creditor to write off the debt balance accumulated partially or fully at any time.
*
* @see http://docs.amazonwebservices.com/${docPath}WriteOffDebt.html
* @param mixed $request array of parameters for Amazon_FPS_Model_WriteOffDebtRequest request
* or Amazon_FPS_Model_WriteOffDebtRequest object itself
* @see Amazon_FPS_Model_WriteOffDebtRequest
* @return Amazon_FPS_Model_WriteOffDebtResponse Amazon_FPS_Model_WriteOffDebtResponse
*
* @throws Amazon_FPS_Exception
*/
public function writeOffDebt($request);
/**
* Verify Signature
*
* Verify the signature that FPS sent in IPN or callback urls.
*
* @see http://docs.amazonwebservices.com/${docPath}VerifySignature.html
* @param mixed $request array of parameters for Amazon_FPS_Model_VerifySignatureRequest request
* or Amazon_FPS_Model_VerifySignatureRequest object itself
* @see Amazon_FPS_Model_VerifySignatureRequest
* @return Amazon_FPS_Model_VerifySignatureResponse Amazon_FPS_Model_VerifySignatureResponse
*
* @throws Amazon_FPS_Exception
*/
public function verifySignature($request);
}

Some files were not shown because too many files have changed in this diff Show More