Initial Commit

This commit is contained in:
2024-02-08 12:07:49 -07:00
parent 5813b1109f
commit 43077b57ed
5471 changed files with 682195 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2012 - 2Checkout.com, Inc.
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.
+310
View File
@@ -0,0 +1,310 @@
2Checkout PHP Library
=====================
This library provides developers with a simple set of bindings to the 2Checkout Payment API, Hosted Checkout, Instant Notification Service and Admin API.
To use, download or clone the repository.
```shell
git clone https://github.com/2Checkout/2checkout-php.git
```
Require in your php script.
```php
require_once("/path/to/2checkout-php/lib/Twocheckout.php");
```
All methods return an Array by default or you can set the format to 'json' to get a JSON response.
**Example:**
```php
<?php
Twocheckout::format('json');
```
Credentials and Options
-----------------
Methods are provided to set the following credentials and options.
```php
<?php
// Your sellerId(account number) and privateKey are required to make the Payment API Authorization call.
Twocheckout::privateKey('BE632CB0-BB29-11E3-AFB6-D99C28100996');
Twocheckout::sellerId('901248204');
// Your username and password are required to make any Admin API call.
Twocheckout::username('testlibraryapi901248204');
Twocheckout::password('testlibraryapi901248204PASS');
// If you want to turn off SSL verification (Please don't do this in your production environment)
Twocheckout::verifySSL(false); // this is set to true by default
// To use your sandbox account set sandbox to true
Twocheckout::sandbox(true);
// All methods return an Array by default or you can set the format to 'json' to get a JSON response.
Twocheckout::format('json');
```
Full documentation for each binding is provided in the **[wiki](https://github.com/2Checkout/2checkout-php/wiki)**.
Example Payment API Usage
-----------------
*Example Request:*
```php
<?php
Twocheckout::privateKey('BE632CB0-BB29-11E3-AFB6-D99C28100996');
Twocheckout::sellerId('901248204');
try {
$charge = Twocheckout_Charge::auth(array(
"sellerId" => "901248204",
"merchantOrderId" => "123",
"token" => 'MjFiYzIzYjAtYjE4YS00ZmI0LTg4YzYtNDIzMTBlMjc0MDlk',
"currency" => 'USD',
"total" => '10.00',
"billingAddr" => array(
"name" => 'Testing Tester',
"addrLine1" => '123 Test St',
"city" => 'Columbus',
"state" => 'OH',
"zipCode" => '43123',
"country" => 'USA',
"email" => 'testingtester@2co.com',
"phoneNumber" => '555-555-5555'
),
"shippingAddr" => array(
"name" => 'Testing Tester',
"addrLine1" => '123 Test St',
"city" => 'Columbus',
"state" => 'OH',
"zipCode" => '43123',
"country" => 'USA',
"email" => 'testingtester@2co.com',
"phoneNumber" => '555-555-5555'
)
));
$this->assertEquals('APPROVED', $charge['response']['responseCode']);
} catch (Twocheckout_Error $e) {
$this->assertEquals('Unauthorized', $e->getMessage());
}
```
*Example Response:*
```php
Array
(
[validationErrors] =>
[exception] =>
[response] => Array
(
[type] => AuthResponse
[lineItems] => Array
(
[0] => Array
(
[options] => Array
(
)
[price] => 10.00
[quantity] => 1
[recurrence] =>
[startupFee] =>
[productId] =>
[tangible] => N
[name] => 123
[type] => product
[description] =>
[duration] =>
)
)
[transactionId] => 205181140830
[billingAddr] => Array
(
[addrLine1] => 123 Test St
[addrLine2] =>
[city] => Columbus
[zipCode] => 43123
[phoneNumber] => 555-555-5555
[phoneExtension] =>
[email] => testingtester@2co.com
[name] => Testing Tester
[state] => OH
[country] => USA
)
[shippingAddr] => Array
(
[addrLine1] => 123 Test St
[addrLine2] =>
[city] => Columbus
[zipCode] => 43123
[phoneNumber] =>
[phoneExtension] =>
[email] =>
[name] => Testing Tester
[state] => OH
[country] => USA
)
[merchantOrderId] => 123
[orderNumber] => 205181140821
[recurrentInstallmentId] =>
[responseMsg] => Successfully authorized the provided credit card
[responseCode] => APPROVED
[total] => 10.00
[currencyCode] => USD
[errors] =>
)
)
```
Example Admin API Usage
-----------------
*Example Request:*
```php
<?php
Twocheckout::username('testlibraryapi901248204');
Twocheckout::password('testlibraryapi901248204PASS');
$args = array(
'sale_id' => 4834917619
);
try {
$result = Twocheckout_Sale::stop($args);
} catch (Twocheckout_Error $e) {
$e->getMessage();
}
```
*Example Response:*
```php
<?php
[response_code] => OK
[response_message] => Array
(
[0] => 4834917634
[1] => 4834917646
[2] => 4834917658
)
```
Example Checkout Usage:
-----------------------
*Example Request:*
```php
<?php
$params = array(
'sid' => '1817037',
'mode' => '2CO',
'li_0_name' => 'Test Product',
'li_0_price' => '0.01'
);
Twocheckout_Charge::form($params, 'auto');
```
*Example Response:*
```php
<form id="2checkout" action="https://www.2checkout.com/checkout/spurchase" method="post">
<input type="hidden" name="sid" value="1817037"/>
<input type="hidden" name="mode" value="2CO"/>
<input type="hidden" name="li_0_name" value="Test Product"/>
<input type="hidden" name="li_0_price" value="0.01"/>
<input type="submit" value="Click here if you are not redirected automatically" /></form>
<script type="text/javascript">document.getElementById('2checkout').submit();</script>
```
Example Return Usage:
---------------------
*Example Request:*
```php
<?php
$params = array();
foreach ($_REQUEST as $k => $v) {
$params[$k] = $v;
}
$passback = Twocheckout_Return::check($params, "tango");
```
*Example Response:*
```php
<?php
[response_code] => Success
[response_message] => Hash Matched
```
Example INS Usage:
------------------
*Example Request:*
```php
<?php
$params = array();
foreach ($_POST as $k => $v) {
$params[$k] = $v;
}
$passback = Twocheckout_Notification::check($params, "tango");
```
*Example Response:*
```php
<?php
[response_code] => Success
[response_message] => Hash Matched
```
Exceptions:
-----------
Twocheckout_Error exceptions are thrown by if an error has returned. It is best to catch these exceptions so that they can be gracefully handled in your application.
*Example Usage*
```php
<?php
Twocheckout::username('testlibraryapi901248204');
Twocheckout::password('testlibraryapi901248204PASS');
$params = array(
'sale_id' => 4774380224,
'category' => 1,
'comment' => 'Order never sent.'
);
try {
$sale = Twocheckout_Sale::refund($params);
} catch (Twocheckout_Error $e) {
$e->getMessage();
}
```
Full documentation for each binding is provided in the **[wiki](https://github.com/2Checkout/2checkout-php/wiki)**.
@@ -0,0 +1,54 @@
<?php
abstract class Twocheckout
{
public static $sid;
public static $privateKey;
public static $username;
public static $password;
public static $verifySSL = true;
public static $baseUrl = 'https://www.2checkout.com';
public static $error;
public static $format = 'array';
const VERSION = '0.4.0';
public static function sellerId($value = null) {
self::$sid = $value;
}
public static function privateKey($value = null) {
self::$privateKey = $value;
}
public static function username($value = null) {
self::$username = $value;
}
public static function password($value = null) {
self::$password = $value;
}
public static function verifySSL($value = null) {
if ($value == 0 || $value == false) {
self::$verifySSL = false;
} else {
self::$verifySSL = true;
}
}
public static function format($value = null) {
self::$format = $value;
}
}
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutAccount.php');
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutPayment.php');
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutApi.php');
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutSale.php');
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutProduct.php');
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutUtil.php');
require(dirname(__FILE__) . '/Twocheckout/Api/TwocheckoutError.php');
require(dirname(__FILE__) . '/Twocheckout/TwocheckoutReturn.php');
require(dirname(__FILE__) . '/Twocheckout/TwocheckoutNotification.php');
require(dirname(__FILE__) . '/Twocheckout/TwocheckoutCharge.php');
require(dirname(__FILE__) . '/Twocheckout/TwocheckoutMessage.php');
@@ -0,0 +1,25 @@
<?php
class Twocheckout_Company extends Twocheckout
{
public static function retrieve()
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/acct/detail_company_info';
$result = $request->doCall($urlSuffix);
return Twocheckout_Util::returnResponse($result);
}
}
class Twocheckout_Contact extends Twocheckout
{
public static function retrieve()
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/acct/detail_contact_info';
$result = $request->doCall($urlSuffix);
return Twocheckout_Util::returnResponse($result);
}
}
@@ -0,0 +1,55 @@
<?php
class Twocheckout_Api_Requester
{
public $baseUrl;
public $environment;
private $user;
private $pass;
private $sid;
private $privateKey;
function __construct() {
$this->user = Twocheckout::$username;
$this->pass = Twocheckout::$password;
$this->sid = Twocheckout::$sid;
$this->baseUrl = Twocheckout::$baseUrl;
$this->verifySSL = Twocheckout::$verifySSL;
$this->privateKey = Twocheckout::$privateKey;
}
function doCall($urlSuffix, $data=array())
{
$url = $this->baseUrl . $urlSuffix;
$ch = curl_init($url);
if (isset($data['api'])) {
unset( $data['api'] );
$data['privateKey'] = $this->privateKey;
$data['sellerId'] = $this->sid;
$data = json_encode($data);
$header = array("content-type:application/json","content-length:".strlen($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
} else {
$header = array("Accept: application/json");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}");
}
if ($this->verifySSL == false) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, "2Checkout PHP/0.1.0%s");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($ch);
curl_close($ch);
if ($resp === FALSE) {
throw new Twocheckout_Error("cURL call failed", "403");
} else {
return utf8_encode($resp);
}
}
}
@@ -0,0 +1,14 @@
<?php
class Twocheckout_Error extends Exception
{
public function __construct($message, $code = 0)
{
parent::__construct($message, $code);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
@@ -0,0 +1,24 @@
<?php
class Twocheckout_Payment extends Twocheckout
{
public static function retrieve()
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/acct/list_payments';
$result = $request->doCall($urlSuffix);
$response = Twocheckout_Util::returnResponse($result);
return $response;
}
public static function pending()
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/acct/detail_pending_payment';
$result = $request->doCall($urlSuffix);
$response = Twocheckout_Util::returnResponse($result);
return $response;
}
}
@@ -0,0 +1,42 @@
<?php
class Twocheckout_Product extends Twocheckout
{
public static function create($params=array())
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/products/create_product';
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
public static function retrieve($params=array())
{
$request = new Twocheckout_Api_Requester();
if(array_key_exists("product_id",$params)) {
$urlSuffix = '/api/products/detail_product';
} else {
$urlSuffix = '/api/products/list_products';
}
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
public static function update($params=array())
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/products/update_product';
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
public static function delete($params=array())
{
$request = new Twocheckout_Api_Requester();
$urlSuffix = '/api/products/delete_product';
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
}
@@ -0,0 +1,96 @@
<?php
class Twocheckout_Sale extends Twocheckout
{
public static function retrieve($params=array())
{
$request = new Twocheckout_Api_Requester();
if(array_key_exists("sale_id",$params) || array_key_exists("invoice_id",$params)) {
$urlSuffix = '/api/sales/detail_sale';
} else {
$urlSuffix = '/api/sales/list_sales';
}
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
public static function refund($params=array()) {
$request = new Twocheckout_Api_Requester();
if(array_key_exists("lineitem_id",$params)) {
$urlSuffix ='/api/sales/refund_lineitem';
$result = $request->doCall($urlSuffix, $params);
} elseif(array_key_exists("invoice_id",$params) || array_key_exists("sale_id",$params)) {
$urlSuffix ='/api/sales/refund_invoice';
$result = $request->doCall($urlSuffix, $params);
} else {
$result = Twocheckout_Message::message('Error', 'You must pass a sale_id, invoice_id or lineitem_id to use this method.');
}
return Twocheckout_Util::returnResponse($result);
}
public static function stop($params=array()) {
$request = new Twocheckout_Api_Requester();
$urlSuffix ='/api/sales/stop_lineitem_recurring';
if(array_key_exists("lineitem_id",$params)) {
$result = $request->doCall($urlSuffix, $params);
} elseif(array_key_exists("sale_id",$params)) {
$result = Twocheckout_Sale::retrieve($params);
if (!is_array($result)) {
$result = Twocheckout_Util::returnResponse($result, 'array');
}
$lineitemData = Twocheckout_Util::getRecurringLineitems($result);
if (isset($lineitemData[0])) {
$stoppedLineitems = array();
foreach( $lineitemData as $value )
{
$params = array('lineitem_id' => $value);
$result = $request->doCall($urlSuffix, $params);
$result = json_decode($result, true);
if ($result['response_code'] == "OK") {
$stoppedLineitems[] = $value;
}
}
$result = Twocheckout_Message::message('OK', $stoppedLineitems);
} else {
throw new Twocheckout_Error("No recurring lineitems to stop.");
}
} else {
throw new Twocheckout_Error('You must pass a sale_id or lineitem_id to use this method.');
}
return Twocheckout_Util::returnResponse($result);
}
public static function active($params=array()) {
if(array_key_exists("sale_id",$params)) {
$result = Twocheckout_Sale::retrieve($params);
if (!is_array($result)) {
$result = Twocheckout_Util::returnResponse($result, 'array');
}
$lineitemData = Twocheckout_Util::getRecurringLineitems($result);
if (isset($lineitemData[0])) {
$result = Twocheckout_Message::message('OK', $lineitemData);
return Twocheckout_Util::returnResponse($result);
} else {
throw new Twocheckout_Error("No active recurring lineitems.");
}
} else {
throw new Twocheckout_Error("You must pass a sale_id to use this method.");
}
}
public static function comment($params=array()) {
$request = new Twocheckout_Api_Requester();
$urlSuffix ='/api/sales/create_comment';
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
public static function ship($params=array()) {
$request = new Twocheckout_Api_Requester();
$urlSuffix ='/api/sales/mark_shipped';
$result = $request->doCall($urlSuffix, $params);
return Twocheckout_Util::returnResponse($result);
}
}
@@ -0,0 +1,74 @@
<?php
class Twocheckout_Util extends Twocheckout
{
static function returnResponse($contents, $format=null) {
$format = $format == null ? Twocheckout::$format : $format;
switch ($format) {
case "array":
$response = self::objectToArray($contents);
self::checkError($response);
break;
case "force_json":
$response = self::objectToJson($contents);
break;
default:
$response = self::objectToArray($contents);
self::checkError($response);
$response = json_encode($contents);
$response = json_decode($response);
}
return $response;
}
public static function objectToArray($object)
{
$object = json_decode($object, true);
$array=array();
foreach($object as $member=>$data)
{
$array[$member]=$data;
}
return $array;
}
public static function objectToJson($object)
{
return json_encode($object);
}
public static function getRecurringLineitems($saleDetail) {
$i = 0;
$invoiceData = array();
while (isset($saleDetail['sale']['invoices'][$i])) {
$invoiceData[$i] = $saleDetail['sale']['invoices'][$i];
$i++;
}
$invoice = max($invoiceData);
$i = 0;
$lineitemData = array();
while (isset($invoice['lineitems'][$i])) {
if ($invoice['lineitems'][$i]['billing']['recurring_status'] == "active") {
$lineitemData[] = $invoice['lineitems'][$i]['billing']['lineitem_id'];
}
$i++;
};
return $lineitemData;
}
public static function checkError($contents)
{
if (isset($contents['errors'])) {
throw new Twocheckout_Error($contents['errors'][0]['message']);
} elseif (isset($contents['exception'])) {
throw new Twocheckout_Error($contents['exception']['errorMsg'], $contents['exception']['errorCode']);
}
}
}
@@ -0,0 +1,69 @@
<?php
class Twocheckout_Charge extends Twocheckout
{
public static function form($params, $type='Checkout')
{
echo '<form id="2checkout" action="'.Twocheckout::$baseUrl.'/checkout/purchase" method="post">';
foreach ($params as $key => $value)
{
echo '<input type="hidden" name="'.htmlspecialchars($key, ENT_QUOTES, 'UTF-8').'" value="'.htmlspecialchars($value, ENT_QUOTES, 'UTF-8').'"/>';
}
if ($type == 'auto') {
echo '<input type="submit" value="Click here if you are not redirected automatically" /></form>';
echo '<script type="text/javascript">document.getElementById("2checkout").submit();</script>';
} else {
echo '<input type="submit" value="'.$type.'" />';
echo '</form>';
}
}
public static function direct($params, $type='Checkout')
{
echo '<form id="2checkout" action="'.Twocheckout::$baseUrl.'/checkout/purchase" method="post">';
foreach ($params as $key => $value)
{
echo '<input type="hidden" name="'.$key.'" value="'.$value.'"/>';
}
if ($type == 'auto') {
echo '<input type="submit" value="Click here if the payment form does not open automatically." /></form>';
echo '<script type="text/javascript">
function submitForm() {
document.getElementById("tco_lightbox").style.display = "block";
document.getElementById("2checkout").submit();
}
setTimeout("submitForm()", 2000);
</script>';
} else {
echo '<input type="submit" value="'.$type.'" />';
echo '</form>';
}
echo '<script src="'.Twocheckout::$baseUrl.'/static/checkout/javascript/direct.min.js"></script>';
}
public static function link($params)
{
$url = Twocheckout::$baseUrl.'/checkout/purchase?'.http_build_query($params, '', '&amp;');
return $url;
}
public static function redirect($params)
{
$url = Twocheckout::$baseUrl.'/checkout/purchase?'.http_build_query($params, '', '&amp;');
header("Location: $url");
}
public static function auth($params=array())
{
$params['api'] = 'checkout';
$request = new Twocheckout_Api_Requester();
$result = $request->doCall('/checkout/api/1/'.self::$sid.'/rs/authService', $params);
return Twocheckout_Util::returnResponse($result);
}
}
@@ -0,0 +1,13 @@
<?php
class Twocheckout_Message
{
public static function message($code, $message)
{
$response = array();
$response['response_code'] = $code;
$response['response_message'] = $message;
$response = json_encode($response);
return $response;
}
}
@@ -0,0 +1,20 @@
<?php
class Twocheckout_Notification extends Twocheckout
{
public static function check($insMessage=array(), $secretWord)
{
$hashSid = $insMessage['vendor_id'];
$hashOrder = $insMessage['sale_id'];
$hashInvoice = $insMessage['invoice_id'];
$StringToHash = strtoupper(md5($hashOrder . $hashSid . $hashInvoice . $secretWord));
if ($StringToHash != $insMessage['md5_hash']) {
$result = Twocheckout_Message::message('Fail', 'Hash Mismatch');
} else {
$result = Twocheckout_Message::message('Success', 'Hash Matched');
}
return Twocheckout_Util::returnResponse($result);
}
}
@@ -0,0 +1,21 @@
<?php
class Twocheckout_Return extends Twocheckout
{
public static function check($params=array(), $secretWord)
{
$hashSecretWord = $secretWord;
$hashSid = $params['sid'];
$hashTotal = $params['total'];
$hashOrder = $params['order_number'];
$StringToHash = strtoupper(md5($hashSecretWord . $hashSid . $hashOrder . $hashTotal));
if ($StringToHash != $params['key']) {
$result = Twocheckout_Message::message('Fail', 'Hash Mismatch');
} else {
$result = Twocheckout_Message::message('Success', 'Hash Matched');
}
return Twocheckout_Util::returnResponse($result);
}
}