Skip to content

Instantly share code, notes, and snippets.

@akmalhazim
Created May 17, 2019 12:50
Show Gist options
  • Save akmalhazim/bbc3ea8d251930e59cc2c326e5ad04ba to your computer and use it in GitHub Desktop.
Save akmalhazim/bbc3ea8d251930e59cc2c326e5ad04ba to your computer and use it in GitHub Desktop.
<?php
namespace App\Jobs\PaymentMethod;
use App\Jobs\Job;
use App\PaymentMethod;
use App\User;
use Braintree_Gateway;
class DeleteCard extends Job
{
protected $deletePaymentMethod;
protected $user;
private $gateway;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct( PaymentMethod $deletePaymentMethod, User $user = null)
{
$this->deletePaymentMethod = $deletePaymentMethod;
$this->user = $user;
$this->gateway = new Braintree_Gateway([
'environment' => config('braintree.environment', 'sandbox'),
'merchantId' => config('braintree.merchant_id'),
'publicKey' => config('braintree.public_key'),
'privateKey' => config('braintree.private_key')
]);
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$deleteToken = $this->deletePaymentMethod->token;
// execute delete request to BT first.
$result = $this->gateway->paymentMethod()->delete($deleteToken);
if ( $result->success ) {
// check if the card is a default one and a user is set during instanciate.
$default = $this->deletePaymentMethod->default;
if ( $default && $this->user ) {
// see if user owns any cards left. Select based on latest.
$paymentMethodNew = $this->user->paymentMethods()->latest()->first();
// if there is any cards own by the user.
if ( $paymentMethodNew ) {
// send api request
$result = $this->gateway->customer()->update($this->user->braintree_id, [
'defaultPaymentMethodToken' => $paymentMethodNew->token
]);
// update local db
$paymentMethodNew->update([
'default' => true
]);
}
}
} else {
// send alert to developer.
abort(500, 'We encountered abnormal behaviours while communicating with our Payment Gateway provider.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment