PHPackages                             devinweb/laravel-youcan-pay - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. devinweb/laravel-youcan-pay

ActiveLibrary[Payment Processing](/categories/payments)

devinweb/laravel-youcan-pay
===========================

YouCanPay packages for Laravel that provides an easy way to reach the best experience.

0.4.3(2y ago)111.1k1MITPHPPHP ^7.4|^8.0CI failing

Since Nov 22Pushed 2y ago1 watchersCompare

[ Source](https://github.com/devinweb/laravel-youcan-pay)[ Packagist](https://packagist.org/packages/devinweb/laravel-youcan-pay)[ Docs](https://github.com/devinweb/laravel-youcan-pay)[ RSS](/packages/devinweb-laravel-youcan-pay/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (7)Dependencies (7)Versions (10)Used By (0)

[![Laravel YouCanPay](/art/socialcard.png)](/art/socialcard.png)

[ ![](https://camo.githubusercontent.com/7f0f73e8916d2fd3fcf57806fa8debe82552596c3edd8a533c1e33e426ad6e12/68747470733a2f2f636f6465636f762e696f2f67682f646576696e7765622f6c61726176656c2d796f7563616e2d7061792f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d324b5245334c32494d46)](https://codecov.io/gh/devinweb/laravel-youcan-pay)[![Latest Version on Packagist](https://camo.githubusercontent.com/065d38c90c9c460254813b959338cad7fa2502fc7d94964f1bca20dd28f28e6b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646576696e7765622f6c61726176656c2d796f7563616e2d7061792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/devinweb/laravel-youcan-pay)[![Total Downloads](https://camo.githubusercontent.com/9cf06bac2e2dbacc1c5df493449504a6f0e2d3e9377dff669c49ccbb46c31cef/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646576696e7765622f6c61726176656c2d796f7563616e2d706179)](https://packagist.org/packages/devinweb/laravel-youcan-pay)[ ![GitHub Actions](https://github.com/devinweb/laravel-youcan-pay/actions/workflows/main.yml/badge.svg)](https://github.com/devinweb/laravel-youcan-pay/actions/workflows/main.yml/badge.svg)[ ![Psalm](https://github.com/devinweb/laravel-youcan-pay/actions/workflows/Psalm.yml/badge.svg)](https://github.com/devinweb/laravel-youcan-pay/actions/workflows/Psalm.yml)

Laravel YouCayPay
=================

[](#laravel-youcaypay)

- [Introduction](#Introduction)
- [Installation](#Installation)
- [Database Migrations](#Database-Migrations)
- [Configuration](#configuration)
    - [Billable Model](#Billable-Model)
    - [YouCanPay Keys](#YouCanPay-Keys)
- [Usage](#Usage)
    - [Customers](#Customers)
        - [Retrieving Customers](#Retrieving-Customers)
        - [Generate Token](#Generate-Token)
        - [Generate Payment URL](#Generate-Payment-URL)
    - [Tokenization](#Create-a-payment)
        - [Get Token id](#Get-token-id)
        - [Get Payment url](#Get-Payment-url)
        - [Customer info](#Customer-info)
        - [Metadata](#Metadata)
    - [Generate Payment form](#generate-payment-form)
    - [Handling YouCanPay Webhooks](#Handling-YouCanPay-Webhooks)
        - [Webhooks URl](#Webhooks-URl)
        - [Webhook Events](#Webhook-Events)
        - [Verify webhook signature manually](#Verify-webhook-signature-manually)
        - [Validate webhook signature manually](#validate-webhook-signature-manually)
    - [Commands](#commands)
- [Testing and test cards](#Testing-and-test-cards)

Introduction
------------

[](#introduction)

Laravel YouCanPay provides an easy experience, to generate the payment form, and process all the operations related to the payment.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require devinweb/laravel-youcan-pay
```

Database Migrations
-------------------

[](#database-migrations)

LaravelYouCanPay package provides its own database to manage the user transactions in different steps, the migrations will create a new `transactions` table to hold all your user's transactions.

```
php artisan migrate
```

If you need to overwrite the migrations that ship with LaravelYouCanPay, you can publish them using the vendor:publish Artisan command:

```
php artisan vendor:publish --tag="youcanpay-migrations"
```

Configuration
-------------

[](#configuration)

To publish the config file you can use the command

```
php artisan vendor:publish --tag="youcanpay-config"
```

then you can find the config file in `config/youcanpay.php`

### Billable Model

[](#billable-model)

If you want the package to manage the transactions based on the user model, add the `Billable` trait to your user model. This trait provides various methods to perform transaction tasks, such as creating a transaction, getting `paid`, `failed` and `pending` transactions.

```
use Devinweb\LaravelYouCanPay\Traits\Billable;

class User extends Authenticatable
{
    use Billable;
}
```

LaravelYouCanPay assumes your user model will be `App\Models\User`, if you use a different user model namespace you should specify it using the method `useCustomerModel` method. This method should typically be called in the boot method of your `AppServiceProvider` class

```
use App\Models\Core\User;
use Devinweb\LaravelYouCanPay\LaravelYouCanPay;;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    LaravelYouCanPay::useCustomerModel(User::class);
}
```

If you need in each transaction the package uses the billing data for each user, make sure to include a `getCustomerInfo()` method in your user model, which returns an array that contains all the data we need.

```
/**
 * Get the customer info to send them when we generate the form token.
 *
 * @return array
 */
public function getCustomerInfo()
{
    return [
      'name'         => $this->name,
      'address'      => '',
      'zip_code'     => '',
      'city'         => '',
      'state'        => '',
      'country_code' => 'MA',
      'phone'        => $this->phone,
      'email'        => $this->email,
    ];
}
```

### YouCanPay Keys

[](#youcanpay-keys)

Next, you should configure your environment in your application's `.env`

```
# YouCanPay env keys
SANDBOX_MODE=
PRIVATE_KEY=
PUBLIC_KEY=
CURRENCY=MAD
SUCCCESS_REDIRECT_URI=
FAIL_REDIRECT_URI=
```

Customers
---------

[](#customers)

### Retrieving Customers

[](#retrieving-customers)

You can retrieve a customer by their YouCanPay ID using the `findBillable` method. This method will return an instance of the billable model:

```
use Devinweb\LaravelYouCanPay\Facades\LaravelYouCanPay;

$user = LaravelYouCanPay::findBillable($order_id);
```

### Generate Token

[](#generate-token)

If you need to generate the token form the user model the cutomer info will be attached directly from `getCustomerInfo` method

```
$data= [
  'order_id' => '123',
  'amount' => 2000 // amount=20*100
];

$token = $user->getPaymentToken($data, $request);
```

If you need to add the metadata you can use

```
$data= [
  'order_id' => '123',
  'amount' => 2000 // amount=20*100
];

$metadata = [
  'key' => 'value'
];

$token = $user->getPaymentToken($data, $request, $metadata);
```

If you need to get the payment url as well from the user model you can use `getPaymentURL` method with the same parameters below.

```
$payment_url = $user->getPaymentURL($data, $request, $metadata);
```

### Generate Payment URL

[](#generate-payment-url)

Usage
-----

[](#usage)

Before starting using the package make sure to update your `config/youcanpay.php` with the correct values provided by YouCanPay.

### Tokenization

[](#tokenization)

#### Get Token id

[](#get-token-id)

The first step we need is to create a token based on the credentails get it from YouCanPay dashboard using `getId()` method.

> **Note**
> The amount should be \* 100, Exemple if your Product price=20$ you should send
>  **amount** = 20\*100 = 200 with **currency**='USD'

```
use Devinweb\LaravelYouCanPay\Facades\LaravelYouCanPay;
use Illuminate\Support\Str;

public function tokenization(Request $request)
{
    $order_data = [
        'order_id' => (string) Str::uuid(),
        'amount' => 200
    ];

    $token= LaravelYouCanPay::createTokenization($order_data, $request)->getId();
    $public_key = config('youcanpay.public_key');
    $isSandbox = config('youcanpay.sandboxMode');
    $language = config('app.locale');

    // You can at this point share a lot of data with the front end,
    // the idea behind this is making the backend manage the environment keys,
    // we don't need to store the keys in many places.
    return response()->json(compact('token', 'public_key', 'isSandbox', 'language'));
}
```

#### Get payment url

[](#get-payment-url)

Standalone Integration, you can generate the payment url using the method `getPaymentUrl()`

```
$paymentUrl= LaravelYouCanPay::createTokenization($data, $request)->getPaymentURL();
```

Then you can put that url in your html page

```
Pay Now
```

#### Customer info

[](#customer-info)

If you need to add the customer data during the tokenization, Please keep these array keys(`name`, `address`, `zip_code`, `city`, `state`, `country_code`, `phone` and `email`). you can use

```
use Devinweb\LaravelYouCanPay\Facades\LaravelYouCanPay;

$customerInfo = [
  'name'         => '',
  'address'      => '',
  'zip_code'     => '',
  'city'         => '',
  'state'        => '',
  'country_code' => '',
  'phone'        => '',
  'email'        => '',
];

$token= LaravelYouCanPay::setCustomerInfo($customerInfo)->createTokenization($data, $request)->getId();
```

#### Metadata

[](#metadata)

You can use the metadata to send data that can be retrieved after the response or in the webhook.

```
use Devinweb\LaravelYouCanPay\Facades\LaravelYouCanPay;

$customerInfo = [
  'name'         => '',
  'address'      => '',
  'zip_code'     => '',
  'city'         => '',
  'state'        => '',
  'country_code' => '',
  'phone'        => '',
  'email'        => '',
];

$metadata = [
  // Can you insert what you want here...
  'key' => 'value'
];

$token= LaravelYouCanPay::setMetadata($metadata)
                          ->setCustomerInfo($customerInfo)
                          ->createTokenization($data, $request)->getId();
```

### Generate Payment form

[](#generate-payment-form)

At this point we receive the token from our backend, so in our blade or any other html page, you can put at the `head` this script

```

  ...

  ...

```

Then to display the form your logic it's will be looks like the code below

```

  // Create a YouCan Pay instance.
  const ycPay = new YCPay(
    // String public_key (required): Login to your account.
    // Go to Settings and open API Keys and copy your key.
    "public_key",
    // Optional options object
    {
      formContainer: "#payment-card",
      // Defines what language the form should be rendered in, supports EN, AR, FR.
      locale: "en",

      // Whether the integration should run in sandbox (test) mode or live mode.
      isSandbox: false,

      // A DOM selector representing which component errors should be injected into.
      // If you omit this option, you may alternatively handle errors by chaining a .catch()
      // On the pay method.
      errorContainer: "#error-container",
    }
  );

  // Select which gateways to render
  ycPay.renderAvailableGateways(["CashPlus", "CreditCard"]);

  // Alternatively, you may use gateway specific render methods if you only need one.
  ycPay.renderCreditCardForm();

```

To start the payment you need an action, you can use a button

```
document.getElementById("pay").addEventListener("click", function () {
  // execute the payment
  ycPay.pay(tokenId).then(successCallback).catch(errorCallback);
});

function successCallback(response) {
  //your code here
}

function errorCallback(response) {
  //your code here
}
```

For more information please check this [link](https://github.com/NextmediaMa/youcan-payment-php-sdk).

### Handling YouCanPay Webhooks

[](#handling-youcanpay-webhooks)

YouCan Pay uses webhooks to notify your application when an event happens in your account. Webhooks are useful for handling reactions to asynchronous events on your backend, such as successful payments, failed payments, successful refunds, and many other real time events. A webhook enables YouCan Pay to push real-time notifications to your application by delivering JSON payloads over HTTPS.

> #### Webhooks and CSRF Protection
>
> [](#webhooks-and-csrf-protection)
>
> YouCanPay webhooks need to reach your URI without any obstacle, so you need to disable CSRF protection for the webhook URI, to do that make sure to add your path to the exception array in your application's `App\Http\Middleware\VerifyCsrfToken` middleware.
>
> ```
> protected $except = [
>    'youcanpay/*',
> ]
> ```

#### Webhooks URL

[](#webhooks-url)

To ensure your application can handle YouCanPay webhooks, be sure to configure the webhook URL in the YouCanPay control panel. By default the package comes with a webhook build-in using the URL `youcanpay/webhook` you can find it by listing all the routes in your app using `php artisan route:list`, This webhook validates the signature related to the payload received, and dispatches an event.

#### Webhooks Middleware

[](#webhooks-middleware)

If you need to attempt the webhook signature validation before processing any action, you can use the middleware `verify-youcanpay-webhook-signature`, that validates the signature related to the payload received from YouCanPay.

```
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class WebHookController extends Controller
{
    /**
     * Create a new WebhookController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('verify-youcanpay-webhook-signature');
    }
    //...
}
```

#### Webhook Events

[](#webhook-events)

LaravelYouCanPay handles the common YouCanPay webhook events, if you need to handle the webhook events that you need you can listen to the event that is dispatched by the package.

- Devinweb\\LaravelYouCanPay\\Events\\WebhookReceived

You need to register a listener that can handle the event:

```
