PHP code example of tuurbo / amazon-payment

1. Go to this page and download the library: Download tuurbo/amazon-payment library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tuurbo / amazon-payment example snippets




return [

    ...

    'amazonpayment' => [
        'sandbox_mode' => true,
        'store_name' => 'ACME Inc',
        'statement_name' => 'AcmeInc 555-555-5555',
        'client_id' => '',
        'seller_id' => '',
        'access_key' => '',
        'secret_key' => '',
    ]
];



$config = [
    'sandbox_mode' => true,
    'client_id' => '',
    'seller_id' => '',
    'access_key' => '',
    'secret_key' => '',
    'store_name' => 'ACME Inc',
    'statement_name' => 'AcmeInc 555-555-5555'
];

$amazonPayment = new Tuurbo\AmazonPayment\AmazonPayment(
    new Tuurbo\AmazonPayment\AmazonPaymentClient(
        new GuzzleHttp\Client, $config
    ),
    $config
);

try {

    $response = $amazonPayment->setOrderDetails(...);

} catch (\Exception $e) {

    // catch errors

}



if (Input::has('amazon_id') && Input::has('access_token')) {
    try {
        AmazonPayment::login(Input::get('access_token'));
        $amazon = AmazonPayment::getLoginDetails(Input::get('access_token'));

        // check if user has already logged in with Amazon
        $user = User::where('amazon_id', $amazon['user_id'])->first();

        // Update and login Amazon user
        if ($user) {
            $validator = Validator::make([
                'email' => $amazon['email'],
            ], [
                'email' => 'unique:user,email,'.$user->id,
            ]);

            $user->last_login = new Datetime;

            // update their current amazon email
            if ($validator->passes()) {
                $user->email = $amazon['email'];
            }

            $user->save();

            Auth::loginUsingId($user->id);

            return Redirect::intended('/account');
        }

        // if they dont have an amazon linked account,
        // check if there amazon email is already taken
        $user = \User::where('email', $amazon['email'])->first();

        // email address is already taken
        // this is optional if you only except amazon logins
        if ($user) {

            // redirect to a page to link their amazon account
            // to their non-amazon account that they already have on your site.
            // example...
            $credentials = Crypt::encrypt(json_encode([
                'amazon_id' => $amazon['user_id'],
                'amazon_email' => $amazon['email'],
            ]));

            // redirect and then decrypt the data and make them put in the their non-amazon password to merge their amazon account.
            return Redirect::to('/register/connect-amazon/'.$credentials);
        }

    } catch (\Exception $e) {

        Session::forget('amazon');

        return Redirect::to('/login')
            ->with('failure_message', 'There was an error trying to login with your Amazon account.');
    }

    // If no user already exists, create a new amazon user account
    $user = new \User;
    $user->amazon_id = $amazon['user_id'];
    $user->email = $amazon['email'];
    $user->name = $amazon['name'];
    $user->signup_at = 'normal amazon account';
    $user->save();

    Auth::user()->loginUsingId($user->id);

    return Redirect::intended('/account');
}




// get access token
$accessToken = $_GET['access_token'];

try {
    // get user details, use them if needed
	$amazonUser = AmazonPayment::getLoginDetails($accessToken);

} catch (\Exception $e) {

    // Redirect back to cart page if error
	return Redirect::to('/cart')
        ->with('failure_message', 'Failed to connect to your Amazon account. Please try again.');
}

// Laravel Auth example:
// login user if their Amazon user_id is found in your users table
// Obviously for this to work, you would have created the user entry at some other point in your app, maybe the account register page or something
$user = User::where('amazon_id', $amazonUser['user_id'])->first();

// If user is found, log them in
if ($user) {
    Auth::loginUsingId($user->id);
}

return View::make(...);



// If using Laravel "Input::get('...')" can be used in place of "$_POST['...']"

// get access token
$accessToken = $_POST['access_token'];

// get amazon order id
$amazonReferenceId = $_POST['reference_id'];

try {

    // get user details
    $amazonUser = AmazonPayment::getLoginDetails($accessToken);

} catch (\Exception $e) {

    // Redirect back to cart page if error
    return Redirect::to('/cart')
        ->with('failure_message', 'Failed to connect to your Amazon account. Please try again.');

}

// (optional) Wrap your Order transaction with the below code to revert the order if the amazon payment fails.
// DB::beginTransaction();

// create customers order
$order = new Order;
$order->email = $amazonUser['email'];
$order->amazon_id = $amazonReferenceId;
$order->grand_total = 109.99;
$order->etc...
$order->save();

try {

	// set amazon order details
	AmazonPayment::setOrderDetails([
	    'referenceId' => $amazonReferenceId,
	    'amount' => 109.99,
	    'orderId' => $order->id,
        // optional note from customer
	    'note' => $_POST['note']
	]);

	// comfirm the amazon order
	AmazonPayment::confirmOrder([
	    'referenceId' => $amazonReferenceId,
	]);

	// get amazon order details and
	// save the response to your customers order
	$amazon = AmazonPayment::getOrderDetails([
	    'referenceId' => $amazonReferenceId,
	]);

    $address = $amazon['details']['Destination']['PhysicalDestination'];

    // Update the order address, city, etc...
    $order->shipping_city = $address['City'];
    $order->shipping_state = $address['StateOrRegion'];
    $order->save();


// log error.
// tell customer something went wrong.
// maybe delete `$order->delete()` or rollback `DB::rollback();` your websites internal order in the database since it wasn't approved by Amazon

} catch (\Tuurbo\AmazonPayment\Exceptions\OrderReferenceNotModifiableException $e) {
    // DB::rollback();

    return Redirect::to('/secure/cart')->with('warning_message', 'Your order has already been placed and is not modifiable online. Please call '.config('site.company.phone').' to make changes.');
} catch (\Exception $e) {
    // DB::rollback();

    return Redirect::to('/secure/cart')->with('warning_message', 'There was an error with your order. Please try again.');
}

// DB::commit();

// other checkout stuff...



AmazonPayment::setOrderDetails()
AmazonPayment::getOrderDetails()
AmazonPayment::confirmOrder()
AmazonPayment::authorize()
AmazonPayment::authorizeAndCapture()
AmazonPayment::capture()
AmazonPayment::closeOrder()
AmazonPayment::cancelOrder()
AmazonPayment::refund()
AmazonPayment::login()
AmazonPayment::getLoginDetails()
AmazonPayment::script()

'providers' => [
   'Tuurbo\AmazonPayment\AmazonPaymentServiceProvider'
]