GithubHelp home page GithubHelp logo

shakurov / laravel-coinbase Goto Github PK

View Code? Open in Web Editor NEW
43.0 4.0 24.0 56 KB

Laravel wrapper for the Coinbase Commerce API

License: MIT License

PHP 100.00%
php laravel laravel-coinbase coinbase coinbase-commerce package laravel-package

laravel-coinbase's Introduction

Laravel wrapper for the Coinbase Commerce API

This package is abandoned and no longer maintained. The author suggests using the antimech/coinbase package instead.

Installation

You can install the package via composer:

composer require shakurov/coinbase

The service provider will automatically register itself.

You must publish the config file with:

php artisan vendor:publish --provider="Shakurov\Coinbase\CoinbaseServiceProvider" --tag="config"

This is the contents of the config file that will be published at config/coinbase.php:

return [
    'apiKey' => env('COINBASE_API_KEY'),
    'apiVersion' => env('COINBASE_API_VERSION'),
    
    'webhookSecret' => env('COINBASE_WEBHOOK_SECRET'),
    'webhookJobs' => [
        // 'charge:created' => \App\Jobs\CoinbaseWebhooks\HandleCreatedCharge::class,
        // 'charge:confirmed' => \App\Jobs\CoinbaseWebhooks\HandleConfirmedCharge::class,
        // 'charge:failed' => \App\Jobs\CoinbaseWebhooks\HandleFailedCharge::class,
        // 'charge:delayed' => \App\Jobs\CoinbaseWebhooks\HandleDelayedCharge::class,
        // 'charge:pending' => \App\Jobs\CoinbaseWebhooks\HandlePendingCharge::class,
        // 'charge:resolved' => \App\Jobs\CoinbaseWebhooks\HandleResolvedCharge::class,
    ],
    'webhookModel' => Shakurov\Coinbase\Models\CoinbaseWebhookCall::class,
];

In the webhookSecret key of the config file you should add a valid webhook secret. You can find the secret used at the webhook configuration settings on the Coinbase Commerce dashboard.

Next, you must publish the migration with:

php artisan vendor:publish --provider="Shakurov\Coinbase\CoinbaseServiceProvider" --tag="migrations"

After the migration has been published you can create the coinbase_webhook_calls table by running the migrations:

php artisan migrate

Finally, take care of the routing: At the Coinbase Commerce dashboard you must add a webhook endpoint, for example: https://example.com/api/coinbase/webhook

Usage

Charges

List charges:

$charges = Coinbase::getCharges();

Create a charge:

$charge = Coinbase::createCharge([
    'name' => 'Name',
    'description' => 'Description',
    'local_price' => [
        'amount' => 100,
        'currency' => 'USD',
    ],
    'pricing_type' => 'fixed_price',
]);

Show a charge:

$charge = Coinbase::getCharge($chargeId);

Cancel a charge:

$charge = Coinbase::cancelCharge($chargeId);

Resolve a charge:

$charge = Coinbase::resolveCharge($chargeId);

Checkouts

List checkouts:

$checkouts = Coinbase::getCheckouts();

Create a checkout:

$checkout = Coinbase::createCheckout([
    'name' => 'Name',
    'description' => 'Description',
    'requested_info' => [],
    'local_price' => [
        'amount' => 100,
        'currency' => 'USD',
    ],
    'pricing_type' => 'fixed_price',
]);

Show a checkout:

$checkout = Coinbase::getCheckout($checkoutId);

Update a checkout:

$checkout = Coinbase::updateCheckout($checkoutId, [
    'name' => 'New Name',
    'description' => 'New Description',
    'local_price' => [
        'amount' => 200,
        'currency' => 'USD',
    ],
    'requested_info' => [
        'name',
    ],
]);

Delete a checkout:

$checkout = Coinbase::deleteCheckout($checkoutId);

Invoices

List invoices:

$invoices = Coinbase::getInvoices();

Create an invoice:

$invoice = Coinbase::createInvoice([
    'business_name' => 'Business Name',
    'customer_email' => '[email protected]',
    'customer_name' => 'Customer Name',
    'local_price' => [
        'amount' => 100,
        'currency' => 'USD',
    ],
    'memo' => 'A memo/description for the invoice',
]);

Show an invoice:

$invoice = Coinbase::getInvoice($invoiceId);

Void an invoice:

$invoice = Coinbase::voidInvoice($invoiceId);

Resolve an invoice:

$invoice = Coinbase::resolveInvoice($invoiceId);

Events

List events:

$events = Coinbase::getEvents();

Show an event:

$event = Coinbase::getEvent($eventId);

Webhooks

Coinbase Commerce will send out webhooks for several event types. You can find the full list of events types in the Coinbase Commerce documentation.

Coinbase Commerce will sign all requests hitting the webhook url of your app. This package will automatically verify if the signature is valid. If it is not, the request was probably not sent by Coinbase Commerce.

Unless something goes terribly wrong, this package will always respond with a 200 to webhook requests. Sending a 200 will prevent Coinbase Commerce from resending the same event over and over again. All webhook requests with a valid signature will be logged in the coinbase_webhook_calls table. The table has a payload column where the entire payload of the incoming webhook is saved.

If the signature is not valid, the request will not be logged in the coinbase_webhook_calls table but a Shakurov\Coinbase\Exceptions\WebhookFailed exception will be thrown. If something goes wrong during the webhook request the thrown exception will be saved in the exception column. In that case the controller will send a 500 instead of 200.

There are two ways this package enables you to handle webhook requests: you can opt to queue a job or listen to the events the package will fire.

Handling webhook requests using jobs

If you want to do something when a specific event type comes in you can define a job that does the work. Here's an example of such a job:

<?php

namespace App\Jobs\CoinbaseWebhooks;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Shakurov\Coinbase\Models\CoinbaseWebhookCall;

class HandleCreatedCharge implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        CoinbaseWebhookCall $webhookCall,
    ) {}

    public function handle(): void
    {
        // do your work here
        
        // you can access the payload of the webhook call with `$this->webhookCall->payload`
    }
}

We highly recommend that you make this job queueable, because this will minimize the response time of the webhook requests. This allows you to handle more Coinbase Commerce webhook requests and avoid timeouts.

After having created your job you must register it at the jobs array in the coinbase.php config file. The key should be the name of the coinbase commerce event type where but with the . replaced by _. The value should be the fully qualified classname.

// config/coinbase.php

'jobs' => [
    'charge:created' => \App\Jobs\CoinbaseWebhooks\HandleCreatedCharge::class,
],

Handling webhook requests using events

Instead of queueing jobs to perform some work when a webhook request comes in, you can opt to listen to the events this package will fire. Whenever a valid request hits your app, the package will fire a coinbase::<name-of-the-event> event.

The payload of the events will be the instance of CoinbaseWebhookCall that was created for the incoming request.

Let's take a look at how you can listen for such an event. In the EventServiceProvider you can register listeners.

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'coinbase::charge:created' => [
        App\Listeners\ChargeCreatedListener::class,
    ],
];

Here's an example of such a listener:

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Shakurov\Coinbase\Models\CoinbaseWebhookCall;

class ChargeCreatedListener implements ShouldQueue
{
    public function handle(CoinbaseWebhookCall $webhookCall): void
    {
        // do your work here

        // you can access the payload of the webhook call with `$webhookCall->payload`
    }   
}

We highly recommend that you make the event listener queueable, as this will minimize the response time of the webhook requests. This allows you to handle more Coinbase Commerce webhook requests and avoid timeouts.

The above example is only one way to handle events in Laravel. To learn the other options, read the Laravel documentation on handling events.

Advanced usage

Retry handling a webhook

All incoming webhook requests are written to the database. This is incredibly valuable when something goes wrong while handling a webhook call. You can easily retry processing the webhook call, after you've investigated and fixed the cause of failure, like this:

use Shakurov\Coinbase\Models\CoinbaseWebhookCall;

CoinbaseWebhookCall::find($id)->process();

Performing custom logic

You can add some custom logic that should be executed before and/or after the scheduling of the queued job by using your own model. You can do this by specifying your own model in the model key of the coinbase config file. The class should extend Shakurov\Coinbase\Models\CoinbaseWebhookCall.

Here's an example:

use Shakurov\Coinbase\Models\CoinbaseWebhookCall;

class MyCustomWebhookCall extends CoinbaseWebhookCall
{
    public function process(): void
    {
        // do some custom stuff beforehand
        
        parent::process();
        
        // do some custom stuff afterwards
    }
}

License

The MIT License (MIT). Please see License File for more information.

Backers

laravel-coinbase's People

Contributors

alexstewartja avatar antimech avatar azcpavel avatar jeybin avatar pierre-pizzetta avatar shakurov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

laravel-coinbase's Issues

Webhook call returning code 0, Undefined index

Required Information

  • Operating system: Linux
  • PHP version: 7.3.x
  • Laravel version: 8.x
  • Laravel Coinbase Commerce wrapper version:

Expected behaviour

webhook calls should return no exception errors if verified

Actual behaviour

webhook calls are returning exceptions "Undefined index"

Steps to reproduce

Extra details

{"code":0,"message":"Undefined index: metadata","trace":"#0 \/home\/i

Logo Proporsal for Laravel-Coinbase

Greetings @shakurov ,

I was passing by (this repository) and tought I'd like to collaborate by proposing a logo
if that's something that may interest you! let me know!

I'm a Graphic Designer and an Open Source enthusiastic
looking to improve my portfolio and collaborate to really cool projects like this one!

Best Regards,
-Luigi.

createCheckout fails with "type":"invalid_request","message":"Requested info must specify desired customer info fields"

Required Information

  • Operating system: Windows
  • PHP version: 7.4.2
  • Laravel version: 8.16.1
  • Laravel Coinbase Commerce wrapper version: 0.7.7

Expected behaviour

Actual behaviour

Simple call to API

$checkout = Coinbase::createCheckout([
    'name' => 'Name',
    'description' => 'Description',
    'local_price' => [
        'amount' => 100,
        'currency' => 'USD',
    ],
    'pricing_type' => 'fixed_price',
]);

results in error:

[2021-07-13 15:35:43] local.ERROR: Client error: `POST https://api.commerce.coinbase.com/checkouts?name=Name&description=Description&local_price%5Bamount%5D=100&local_price%5Bcurrency%5D=USD&pricing_type=fixed_price` resulted in a `400 Bad Request` response:
{"error":{"type":"invalid_request","message":"Requested info must specify desired customer info fields"}}

even though 'request_info' is optional per https://commerce.coinbase.com/docs/api/#create-a-checkout

Steps to reproduce

Generic install on generic laravel create controller with the following function

public function createCheckout(Request $request){
    $checkout = Coinbase::createCheckout([
        'name' => 'Name',
        'description' => 'Description',
        'local_price' => [
            'amount' => 100,
            'currency' => 'USD',
        ],
        'pricing_type' => 'fixed_price',
    ]);

    return $checkout;
}

Extra details

Charge and Events api's work as expected.

Using curl works fine:

COINBASE_COMMERCE_API_KEY=aaaaa-bbbbb-ccccc-ddddd
curl -X POST https://api.commerce.coinbase.com/checkouts \
-H "Content-Type: application/json" \
-H "X-CC-Api-Key: $COINBASE_COMMERCE_API_KEY" \
-H "X-CC-Version: 2018-03-22" \
-d '{"name": "The Sovereign Individual", "description": "Mastering the Transition to the Information Age", "local_price": {"amount": "1.00", "currency": "USD"}, "pricing_type": "fixed_price", "requested_info": ["email"]}'

and once I create it with Curl, getCheckouts works fine too.

How to execute queued Jobs

How do I execute queued jobs for this package because i can't find any documentation on an artisan command to handle that

Controller for webhook

Hi,

How exactly could I make the controller that handles the Endpoint?

I have created the jobs for each type of event that is sent by the Coinbase.

What I want to achive is how to get the data what is sent by the webhook, access the data to check the event type to send it to the job.

Thanks for the help!

Abandoned?

Hi,
It was updated long time ago and the pull requests are ignored.

So therefore I am asking if it is abandoned or not?

Drop PHP 7.x support

Latest PHP 7.x (7.4) version security support has ended 7 months ago (28 Nov 2022). It was not safe to use this version back then, even more so today. Also this minimum version requirement blocks the way for using modern development techniques.

Variable payment always shows donation when completed?

I am developing a website with wallet feature. User can add any amount to their wallet, which can be used to play games or buy stuffs on the website. The site accepts cryptocurrency as their main payment.

ISSUE:
I have used shakurov/laravel-coinbase to accept the cryptocurrency payment. I am creating charges using "no_price" as pricing type. And when user pays using cryptocurrency, the completed screen shows "Thank you for your donation". I cannot find how to update this text creating charges.
Please help!!

Illuminate\Database\Eloquent\ModelNotFoundException

Required Information

  • Operating system:
  • PHP version: 7.2
  • Laravel version: 6.0
  • Laravel Coinbase Commerce wrapper version: v0.7.6

Expected behaviour

job handler will work

Actual behaviour

sometimes exception appears, sometimes it works

dispatch(new HandleCreatedCharge(CoinbaseWebhookCall::findOrFail($test)));

Steps to reproduce

post method to charge:create

Extra details

public function test()
{
    $charge = Coinbase::createCharge([
        'name' => 'jajaja',
        'description' => 'jeje',
        'local_price' => [
            'amount' => 100,
            'currency' => 'USD',
        ],
        'pricing_type' => 'fixed_price',
    ]);

    $test = $charge['data']['id'];


    // error here ->>
    dispatch(new HandleCreatedCharge(CoinbaseWebhookCall::findOrFail($test)));
}
$e: Illuminate\Database\Eloquent\ModelNotFoundException
$e->model "Shakurov\Coinbase\Models\CoinbaseWebhookCall"
$e->message "No query results for model [Shakurov\Coinbase\Models\CoinbaseWebhookCall] 289c9315-0ff8-4fef-be8f-7e13aae6090f"

Laravel 8.x compatibility

Our library needs to be keep up to date with industry. Here is some things we need to do:

  • Opt for PHP ^7.3|^8.0 composer dependency
  • Opt for PHPUnit ^9.3.3 composer dependency
  • Opt for Testbench ^6.0.0 composer dependency
  • Opt for Guzzle ^7.0.1 composer dependency
  • Remove Laravel 5 from tags in composer.json as it's gonna be compatible with newer versions

Each dependency requires to follow it's upgrade guide to avoid breaking changes. All tests must pass.

PRs are welcome!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.