Search

PaymentGateway's Tags

How to Stripe Payment Integration in Laravel 7.x with Example
Laravel Stripe payment gateway has built a reputation of being facile-to-use for both developers and store owners. Because of great compatibility with Laravel, Stripe has become the go-to payment gateway for Laravel eCommerce stores. The ordinant dictation for Saas predicated platforms is incrementing day by day and nowadays building a subscription-predicated system is macrocosmic. So to make things facile on the backend like Laravel, we do require some packages that can avail us build scalable, securable, and reliable web applications that deal with payment systems. Laravel Stripe Payment Example With a host of features and simple Stripe payment gateway integration in Laravel, many development agencies have come to opt for Stripe as the default payment gateway option for all eCommerce stores they develop for their clients. Laravel Cashier makes it very simple to integrate Payment Gateway like Stripe. So let us see how we can integrate stripe in Laravel on Subscription based system. We will use the Cashier package to integrate Stripe Payment Gateway in Laravel. Another important reason for the popularity of Stripe is that it accepts all globally accepted credit and debit cards, thus facilitating payment collections from all over the world. In short, Stripe provides a complete solution for online payment processing requirements for Laravel powered eCommerce stores. Step 1: Install and configure Laravel 7 Type the following command. Go to the project folder and open the project in an editor. I am using VSCode cd stripesub && code Install the js dependencies using the following command. npm install  Install the Cashier package for Stripe dependencies. composer require laravel/cashier Also, create an authentication scaffold. php artisan make:auth Step 2: Create an essential database migrations Before using Cashier, we’ll also need to prepare the database. We need to add several columns to your users’ table and create new subscriptions and plans table to hold all of our customer’s subscriptions. So, first, go to the create_users_table.php and add the following schema. $table->string('stripe_id')->nullable()->collation('utf8mb4_bin'); $table->string('card_brand')->nullable(); $table->string('card_last_four', 4)->nullable(); $table->timestamp('trial_ends_at')->nullable(); Your schema now looks like this. public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('stripe_id')->nullable()->collation('utf8mb4_bin'); $table->string('card_brand')->nullable(); $table->string('card_last_four', 4)->nullable(); $table->timestamp('trial_ends_at')->nullable(); $table->rememberToken(); $table->timestamps(); }); } Now, create two more migrations files. php artisan make:migration create_subscriptions_table php artisan make:migration create_plans_table Now, write the schema on both of the files. First, add the following schema inside the create_subscriptions_table.php file. public function up() { Schema::create('subscriptions', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->string('name'); $table->string('stripe_id')->collation('utf8mb4_bin'); $table->string('stripe_plan'); $table->integer('quantity'); $table->timestamp('trial_ends_at')->nullable(); $table->timestamp('ends_at')->nullable(); $table->timestamps(); }); } Write the following schema inside the create_plans_table.php file. public function up() { Schema::create('plans', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('slug')->unique(); $table->string('stripe_plan'); $table->float('cost'); $table->text('description')->nullable(); $table->timestamps(); }); } Save the file and go to the terminal and migrate tables. php artisan migrate Now, add two plans manually on the plans table like this. Step 3: Get and Set Stripe API Keys First, you need to create an account on Stripe. You can do it here. Then after login to your account, you will find a Test dashboard. Now, click on the Developers link on the left sidebar. In the submenu, you can find the API keys item. Click on that item, and you will be redirected to this page. You need to add these keys inside the .env file in our project. // .env STRIPE_KEY=your key here STRIPE_SECRET=your secret here Finally, you should configure your Stripe key in your  services.php  configuration file. You can retrieve your Stripe API keys from the Stripe control panel. // services.php 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], Also, you need to add the Billable Trait inside the User.php model. // User.php use Laravel\Cashier\Billable; class User extends Authenticatable { use Billable; } Step 4: Create Plans on Stripe Dashboard You can create a plan through Laravel but that will take some time, and our motto is to accept the payment through stripe. So we will create the plans manually on Stripe Dashboard. First, go to the Billing >> Products link and right now, there are no products available. So we need to create two products. Here products mean plans. So we will create two plans. Basic Professional Create and assign the values the same as we have assigned the values on the Plans table in our Laravel application. After creating two plans, your products look like this. Step 5: Display Plans on Frontend First, define the routes for our application inside the routes >> web.php file. // web.php Route::group(['middleware' => 'auth'], function() { Route::get('/home', 'HomeController@index')->name('home'); Route::get('/plans', 'PlanController@index')->name('plans.index'); }); We have taken the auth middleware to protect the routes related to payment and home. Now, create the Plan.php model and PlanController.php file. php artisan make:model Plan php artisan make:controller PlanController // PlanController.php use App\Plan; public function index() { $plans = Plan::all(); return view('plans.index', compact('plans')); } Now, inside the resources >> views folder, create one folder called plans and inside that folder, create one file called index.blade.php file. Write the following code. @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="card"> <div class="card-header">Plans</div> <div class="card-body"> <ul class="list-group"> @foreach($plans as $plan) <li class="list-group-item clearfix"> <div class="pull-left"> <h5>{{ $plan->name }}</h5> <h5>${{ number_format($plan->cost, 2) }} monthly</h5> <h5>{{ $plan->description }}</h5> <a href="" class="btn btn-outline-dark pull-right">Choose</a> </div> </li> @endforeach </ul> </div> </div> </div> </div> </div> @endsection Now, register one user on Laravel application and go to this URL: http://stripesub.test/plans You will find the plans like this. Step 6: Show the plan So, when the user chooses the plan, we need to redirect the user to a particular plan page. Define one more route inside the routes >> web.php file. // web.php Route::group(['middleware' => 'auth'], function() { Route::get('/home', 'HomeController@index')->name('home'); Route::get('/plans', 'PlanController@index')->name('plans.index'); Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show'); }); Now, by default, RouteModelBinding works with the ID of the model. But we will not pass the ID to show the particular plan instead we will pass the slug. So we need to define it inside the Plan.php model. <?php // Plan.php namespace App; use Illuminate\Database\Eloquent\Model; class Plan extends Model { protected $fillable = [ 'name', 'slug', 'stripe_plan', 'cost', 'description' ]; public function getRouteKeyName() { return 'slug'; } } Here, we have defined the function called getRouteKeyName.  So based on this function, now we can fetch the record based on the slug and not based on the ID. That is why we have taken the slug field as a unique field in the database. Now, define the show() function inside the PlanController.php file. // PlanController.php public function show(Plan $plan, Request $request) { return view('plans.show', compact('plan')); } The next step is to create a view file called show.blade.php inside the resources >> views >> plans folder. Add the following code inside the show.blade.php file. @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="card"> <div class="card-header">{{ $plan->name }}</div> <div class="card-body"> </div> </div> </div> </div> </div> @endsection Now, we will display the Payment Form on this page. Step 7: Display the Payment Form For this example, I am using Card Element. You can find it on official Stripe Documentation. It is securely collect sensitive card details using Elements, our pre-built UI components. Now, we need to include the External JS files in our project. For that, we need to modify the resources >> views >> layouts >> app.blade.php file. <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Fonts --> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css"> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <div id="app"> <nav class="navbar navbar-expand-md navbar-light navbar-laravel"> <div class="container"> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name', 'Laravel') }} </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left Side Of Navbar --> <ul class="navbar-nav mr-auto"> </ul> <!-- Right Side Of Navbar --> <ul class="navbar-nav ml-auto"> <!-- Authentication Links --> @guest <li class="nav-item"> <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a> </li> <li class="nav-item"> @if (Route::has('register')) <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a> @endif </li> @else <li class="nav-item"> <a class="nav-link" href="{{ route('plans.index') }}">{{ __('Plans') }}</a> </li> <li class="nav-item dropdown"> <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} <span class="caret"></span> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> </div> </li> @endguest </ul> </div> </div> </nav> <main class="py-4"> @yield('content') </main> </div> <!-- Scripts --> <script src="{{ asset('js/app.js') }}"></script> @yield('scripts') </body> </html> Here, we have defined one navigation link called plans and also add one section for scripts. So, now we can add the Javascript per pagewise using the @yield directive. The next step is to write the Card Element inside the show.blade.php file. @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> <div class=""> <p>You will be charged ${{ number_format($plan->cost, 2) }} for {{ $plan->name }} Plan</p> </div> <div class="card"> <form action="#" method="post" id="payment-form"> @csrf <div class="form-group"> <div class="card-header"> <label for="card-element"> Enter your credit card information </label> </div> <div class="card-body"> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display form errors. --> <div id="card-errors" role="alert"></div> <input type="hidden" name="plan" value="{{ $plan->id }}" /> </div> </div> <div class="card-footer"> <button class="btn btn-dark" type="submit">Pay</button> </div> </form> </div> </div> </div> </div> @endsection @section('scripts') <script src="https://js.stripe.com/v3/"></script> <script> // Create a Stripe client. var stripe = Stripe('{{ env("STRIPE_KEY") }}'); // Create an instance of Elements. var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) var style = { base: { color: '#32325d', lineHeight: '18px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; // Create an instance of the card Element. var card = elements.create('card', {style: style}); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); // Handle real-time validation errors from the card Element. card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); // Handle form submission. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the user if there was an error. var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the token to your server. stripeTokenHandler(result.token); } }); }); // Submit the form with the token ID. function stripeTokenHandler(token) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); } </script> @endsection Here, we have used the Card element and Javascript to display the form. Now, add the link to this page inside the index.blade.php file. // index.blade.php <a href="{{ route('plans.show', $plan->slug) }}" class="btn btn-outline-dark pull-right">Choose</a> So, it will be redirected to the page like this. So, here we need to enter the following details. You can enter the details like the below inputs. Card Number: 4242 4242 4242 4242 Expiration Date: 10/21 or whatever you like from the future of today’s date CVC: whatever you like Zipcode: whatever you like These are dummy details, but these details generally used in a sandbox account to check the application. Right now nothing will happen because we need to define the form action to store the data inside the database tables. So let us define the post route. Step 8: Save the subscriptions and accept payment Define the final route inside the web.php file. // web.php Route::group(['middleware' => 'auth'], function() { Route::get('/home', 'HomeController@index')->name('home'); Route::get('/plans', 'PlanController@index')->name('plans.index'); Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show'); Route::post('/subscription', 'SubscriptionController@create')->name('subscription.create'); }); We have defined the POST route for subscriptions. Now, create SubscriptionController using the following command. php artisan make:controller SubscriptionController Now, add a POST route inside the show.blade.php file when we post the data to the server. // show.blade.php <form action="{{ route('subscription.create') }}" method="post" id="payment-form"> Inside that controller, we need to define one function called create(). <?php // SubscriptionController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Plan; class SubscriptionController extends Controller { public function create(Request $request, Plan $plan) { $plan = Plan::findOrFail($request->get('plan')); $request->user() ->newSubscription('main', $plan->stripe_plan) ->create($request->stripeToken); return redirect()->route('home')->with('success', 'Your plan subscribed successfully'); } } Here, we are creating the subscription for registered User and charge him. First, we have to fetch the plan according to the id. Then we need to pass that plan to the newSubscription() function and create a subscription. So, here we have used the Billable trait’s subscribedToPlan() method and pass the first parameter plan and the second parameter main. We are creating a new Subscription, if the payment made successfully then, it would redirect to the HomePage with a  success message. Write the following code inside the home.blade.php file. @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> @if(session()->get('success')) <div class="alert alert-success"> {{ session()->get('success') }} </div> @endif <div class="card"> <div class="card-header">Dashboard</div> <div class="card-body"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif Welcome to the Dashboard </div> </div> </div> </div> </div> @endsection So, if all of the configurations are right, then you should go to any of the plans and try to subscribe to the plan. If you are redirecting to the homepage, then you are almost done. You can see that one database entry inside the subscriptions table is there. Your user’s table also has been updated as you can see some field’s details are updated. You can check the Stripe Dashboard as well. As we have subscribed to the 50$ Professional Plan. Step 9: Security Tweaks Now, we need to keep in mind one thing that if the user is already subscribed to one plan, then we need the user to prevent to choose that plan. So, we need to add one condition on the choose button. So, add the condition inside the index.blade.php file. @if(!auth()->user()->subscribedToPlan($plan->stripe_plan, 'main')) <a href="{{ route('plans.show', $plan->slug) }}" class="btn btn-outline-dark pull-right">Choose</a> @endif Also, we need to add the condition inside the  PlanController.php  file’s show() function. // PlanController.php public function show(Plan $plan, Request $request) { if($request->user()->subscribedToPlan($plan->stripe_plan, 'main')) { return redirect()->route('home')->with('success', 'You have already subscribed the plan'); } return view('plans.show', compact('plan')); } Also, we need to do the same thing inside the SubscriptionController’s create() method. // SubscriptionController.php public function create(Request $request, Plan $plan) { if($request->user()->subscribedToPlan($plan->stripe_plan, 'main')) { return redirect()->route('home')->with('success', 'You have already subscribed the plan'); } $plan = Plan::findOrFail($request->get('plan')); $request->user() ->newSubscription('main', $plan->stripe_plan) ->create($request->stripeToken); return redirect()->route('home')->with('success', 'Your plan subscribed successfully'); } Save the file, and now you are good to go. Finally, the Laravel 7 Stripe Payment Example article is over. There are still so many things that we can do with the project. But for basic understanding, this is enough. Thanks.
Stripe Payment Gateway integration in Django with Example
In this tutorial I'll demonstrate how to configure an incipient Django website from scratch to accept one-time payments with Stripe. If you require avail configuring your dev environment to utilize pipenv and Python 3. Initial Setup The first step is to install Django, start a new project djangostripe, and create our first app payments. In a new command-line console, enter the following: $ pipenv install django $ pipenv shell (env) $ django-admin startproject djangostripe . (env) $ python manage.py startapp payments I've assumed the virtual environment is called (env) for simplicity but really it will be a variation of your code directory. Now add the new app to the INSTALLED_APPS configuration in settings.py. # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Local 'payments.apps.PaymentsConfig', # new ] Update the project-level urls.py file with the payments app. # urls.py from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('', include('payments.urls')), # new ] Create a urls.py file within our new app, too. (env) $ touch payments/urls.py Then populate it as follows: # payments/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), ] Now add a views.py file: # payments/views.py from django.views.generic.base import TemplateView class HomePageView(TemplateView): template_name = 'home.html' And create a dedicated templates folder and file for our homepage. (env) $ mkdir templates (env) $ touch templates/home.html <!-- templates/home.html --> Hello, World! Make sure to update the settings.py file so Django knows to look for a templates folder. # settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], # new Finally run migrate to sync our database and runserver to start Django's local web server. (env) $ python manage.py migrate (env) $ python manage.py runserver That's it! Check out http://127.0.0.1:8000/ and you'll see the homepage with our text. Add Stripe Time for Stripe. The first step is to install stripe via pipenv. $ pipenv install stripe Then go to the Stripe website and create a new account. After that you'll be redirected to the dashboard page. Click on "Developers" in the left sidebar. Then from the dropdown list click on "API keys." Each Stripe account has four API keys: two for testing and two for live in production. Each pair has a "secret key" and a "publishable key". Do not reveal the secret key to anyone; the publishable key will be embedded in the JavaScript on the page that anyone can see. Currently the toggle for "Viewing test data" in the upper right tells us we're using the test keys now. That's what we want. At the bottom of your settings.py file, add the following two lines including your own test secret and test publishable keys. Make sure to include the '' characters around the actual keys. # settings.py STRIPE_SECRET_KEY = '<your test secret key here>' STRIPE_PUBLISHABLE_KEY = '<your test publishable key here>' Stripe Checkout Ok, now that we have our API keys we need to add them to our website. We can use Stripe Checkout so we don't have to wire up all the forms ourself. Update the home.html template as follows. <!-- templates/home.html --> <h2>Buy for $5.00</h2> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ key }}" data-description="A Django Charge" data-amount="500" data-locale="auto"> </script> Now refresh the web page and a blue button appears. Click on it and a fancy form appears, styled by Stripe for us. We can test the form by using one of several test card numbers Stripe provides. Let's use 4242 4242 4242 4242. Make sure the expiration date is in the future and add any 3 numbers for the CVC. But there's a problem after clicking on the "Pay $5.00" button which Stripe highlights for us: we never passed in the key value. Right here is where many newcomers become confused. Why is the charge failing, right? The reason is that the full flow is as follows: the form is submitted in the client with our publishable key to Stripe Stripe stores the credit card information securely--we never see it ourselves--and issues us a unique token for the customer which is sent back to us next we use the token to make a charge via the secret key stored only on our server Right now we haven't included our publishable key yet, so Stripe is complaining. We can update our payments/views.py file to pass it in as the value key. We do this by overriding get_context_data and importing settings at the top. # payments/views.py from django.conf import settings # new from django.views.generic.base import TemplateView class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context Now refresh the web page and try again. It will "work" in that the button turns green. If you look at the Stripe Dashboard and click on "Logs" under "Developers" in the left menu, you can see that tokens are created. But if you then click on "Payments" in the same lefthand menu, there are no charges. So what's happening? Think back to the Stripe flow. We have used the publishable key to send the credit card information to Stripe, and Stripe has sent us back a token. But we haven't used the token yet to make a charge! We'll do that now. Charges Creating a charge is not as hard as it seems. The first step is to make our payment button a form. We include {% csrf_token %} in the form as required for security reasons in Django. <!-- templates/home.html --> <h2>Buy for $5.00</h2> <form action="{% url 'charge' %}" method="post"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ key }}" data-description="A Django Charge" data-amount="500" data-locale="auto"></script> </form> Note it will redirect to a charge page so let's create that now. $ touch templates/charge.html Add some text to it. <!-- templates/charge.html --> <h2>Thanks, you paid <strong>$5.00</strong>!</h2> Update our URL routes with the new charge/ page. # payments/urls.py from django.urls import path from . import views urlpatterns = [ path('charge/', views.charge, name='charge'), # new path('', views.HomePageView.as_view(), name='home'), ] Now for the "magic" logic which will occur in our payments/views.py file. We create a charge view that receives the token from Stripe, makes the charge, and then redirects to the charge page upon success. Import stripe on the top line, also render, and set the stripe.api_key. # payments/views.py import stripe # new from django.conf import settings from django.views.generic.base import TemplateView from django.shortcuts import render # new stripe.api_key = settings.STRIPE_SECRET_KEY # new class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context def charge(request): # new if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='usd', description='A Django charge', source=request.POST['stripeToken'] ) return render(request, 'charge.html') The charge function-based view assumes a POST request: we are sending data to Stripe here. We make a charge that includes the amount, currency, description, and crucially the source which has the unique token Stripe generated for this transaction. Then we return the request object and load the charge.html template. In the real-world you would want to include robust error handling here but we can just assume it all works for now. Ok, refresh the web page at http://127.0.0.1:8000/. Click on the button for the popup which looks the same. Use the credit card number 4242 4242 4242 4242 again and you'll end up on our charge page. To confirm a charge was actually made, go back to the Stripe dashboard under "Payments." To review, we used Stripe Checkout and our publishable key to send a customer's credit card information to Stripe. The Stripe API then sent us back a unique token for the customer, which we used alongside our secret key on the server to submit a charge. i hope you like this tutorial.
Paypal Card Payment REST API integration in Laravel 6
In this article we will share with you how to integrate paypal card payment in your laravel application. in many time you need to integrate online card payment system in your laravel project. so, this article will be help for you. right now amny payment solution is available like stripe, paypal, SecurePay, 2Checkout, Authorize.net etc.. Paypal is very simple and easy payment gateway integration and it have large document, library and packages provide on online so you can get easiest any soslution on regarding on your error or any extra help. Before you never integrate paypal card API in you laravel application then don't worry we are here show youu all step by step and very easy way. Step - 1 Create paypal sandbox account Very first step here you have one paypal sandbox account for before going live integration you can test and check all paypal card integration working fine there. simple go to this link and signup/signin your paypal sandbox account Paypal Developer Dashboard. After singup/singin in your paypal sandbox account then click on the Accounts menu which seen in left side. and then create one test bussined account and one buyer account. please seen following image for more information. [ADDCODE] After create account then click on View/Edit Account link which you can seen under Manage Accounts. after click on this then open one popup and in this popup you can get your Sandbox API Credentials. We need following Paypal Sandbox Credentials for make paypal card payment request. METHOD – The name of the API call you’re making. USER – The API username PWD – The API password SIGNATURE – The API signature VERSION – The API version You can also check full paypal document on click by this link Direct Payment Paypal API Docs. Step - 2 Create route After get you Sandbox API Credentials then create following two routes. Route::get('paypal-payment-form', 'PaypalController@index')->name('paypal-payment-form'); Route::get('paypal-payment-form-submit', 'PaypalController@payment')->name('paypal-payment-form-submit'); Step - 2 Create controller After, done above two routes then we neet to create PaypalController.php file help of following artisan command. php artisan make:controller PaypalController After run this commant your PaypalController.php file automatic created on app/Http/Controllers folder. just open it and write following code into that file. namespace App\Http\Controllers; use Illuminate\Http\Request; class PaypalController extends Controller { public function index(Request $request) { return view('paypal-payment-form'); } public function payment(Request $request) { $request_params = array ( 'METHOD' => 'DoDirectPayment', 'USER' => 'laracode101_api1.gmail.com', 'PWD' => 'BQJBSMHVP8WCEETS', 'SIGNATURE' => 'AyVuUcpetZUWCXV.EHq.qRhxEb6.AChQnxfoM9w6UJXXRBh2cH1GUawh', 'VERSION' => '85.0', 'PAYMENTACTION' => 'Sale', 'IPADDRESS' => '127.0.0.1', 'CREDITCARDTYPE' => 'Visa', 'ACCT' => '4032032452071167', 'EXPDATE' => '072023', 'CVV2' => '123', 'FIRSTNAME' => 'Yang', 'LASTNAME' => 'Ling', 'STREET' => '1 Main St', 'CITY' => 'San Jose', 'STATE' => 'CA', 'COUNTRYCODE' => 'US', 'ZIP' => '95131', 'AMT' => '100.00', 'CURRENCYCODE' => 'USD', 'DESC' => 'Testing Payments Pro' ); $nvp_string = ''; foreach($request_params as $var=>$val) { $nvp_string .= '&'.$var.'='.urlencode($val); } $curl = curl_init(); curl_setopt($curl, CURLOPT_VERBOSE, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_URL, 'https://api-3t.sandbox.paypal.com/nvp'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $nvp_string); $result = curl_exec($curl); curl_close($curl); $data = $this->NVPToArray($result); if($data['ACK'] == 'Success') { # Database integration... echo "Your payment was processed success."; } if ($data['ACK'] == 'Failure') { # Database integration... echo "Your payment was declined/fail."; } else { echo "Something went wront please try again letter."; } } public function NVPToArray($NVPString) { $proArray = array(); while(strlen($NVPString)) { // key $keypos= strpos($NVPString,'='); $keyval = substr($NVPString,0,$keypos); //value $valuepos = strpos($NVPString,'&') ? strpos($NVPString,'&'): strlen($NVPString); $valval = substr($NVPString,$keypos+1,$valuepos-$keypos-1); $proArray[$keyval] = urldecode($valval); $NVPString = substr($NVPString,$valuepos+1,strlen($NVPString)); } return $proArray; } } Here you can check following try response we will got from the paypal REST API server. Success response Array ( [TIMESTAMP] => 2012-04-16T08:15:41Z [CORRELATIONID] => 9a652cbabfdd9 [ACK] => Success [VERSION] => 85.0 [BUILD] => 2764190 [AMT] => 100.00 [CURRENCYCODE] => USD [AVSCODE] => X [CVV2MATCH] => M [TRANSACTIONID] => 6VR832690S591564M ) Fail response Array ( [TIMESTAMP] => 2012-04-16T08:18:46Z [CORRELATIONID] => 2db182b912a9 [ACK] => Failure [VERSION] => 85.0 [BUILD] => 2764190 [L_ERRORCODE0] => 10527 [L_SHORTMESSAGE0] => Invalid Data [L_LONGMESSAGE0] => This transaction cannot be processed. Please enter a valid credit card number and type. [L_SEVERITYCODE0] => Error [AMT] => 100.00 [CURRENCYCODE] => USD ) Step - 3 Create blade file After done controller file then we create one laravel blade HTML file which simple card payment design. Now we are create one simple blade file in resources/views/paypal-payment-form.blade.php file and here we are make very simple html layout for make card payment. After done this step then your card payment layout look something like, please seen following sceenshot IMAGE @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-4"> <div class="card"> <div class="card-header">{{ __('Paypal Card Payment') }}</div> <div class="card-body"> <form method="POST" action="{{ route('paypal-payment-form-submit') }}"> @csrf <div class="form-group row"> <div class="col-md-12"> <input id="card_no" type="text" class="form-control @error('card_no') is-invalid @enderror" name="card_no" value="{{ old('card_no') }}" required autocomplete="card_no" placeholder="Card No." autofocus> @error('card_no') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <div class="col-md-6"> <input id="exp_month" type="text" class="form-control @error('exp_month') is-invalid @enderror" name="exp_month" value="{{ old('exp_month') }}" required autocomplete="exp_month" placeholder="Exp. Month (Eg. 02)" autofocus> @error('exp_month') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class="col-md-6"> <input id="exp_year" type="text" class="form-control @error('exp_year') is-invalid @enderror" name="exp_year" value="{{ old('exp_year') }}" required autocomplete="exp_year" placeholder="Exp. Year (Eg. 2020)" autofocus> @error('exp_year') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <div class="col-md-12"> <input id="cvv" type="password" class="form-control @error('cvv') is-invalid @enderror" name="cvv" required autocomplete="current-password" placeholder="CVV"> @error('cvv') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row mb-0"> <div class="col-md-12"> <button type="submit" class="btn btn-primary btn-block"> {{ __('PAY NOW') }} </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection cUrl Request Data if you want direct use cUrl request in your terminal or posman then you can use following code example. curl https://api-3t.sandbox.paypal.com/nvp \ --insecure \ -d VERSION=56.0 \ -d SIGNATURE api_signature \ -d USER api_username \ -d PWD api_password \ -d METHOD=DoDirectPayment \ -d PAYMENTACTION=Sale \ -d IPADDRESS=192.168.0.1 \ -d AMT=8.88 \ -d CREDITCARDTYPE=Visa \ -d ACCT=4683075410516684 \ -d EXPDATE=042011 \ -d CVV2=123 \ -d FIRSTNAME=John \ -d LASTNAME=Smith \ -d STREET=1 Main St. \ -d CITY=San Jose \ -d STATE=CA \ -d ZIP=95131 \ -d COUNTRYCODE=US cUrl Response Data TIMESTAMP=... &ACK=Success &VERSION=56%2e0 &BUILD=1195961 &AMT=8%2e88 &CURRENCYCODE=USD &AVSCODE=X &CVV2MATCH=M &TRANSACTIONID=... &CORRELATIONID=... I hope it can help you.
Laravel 5.6 - Card Payment Integration With Instamojo Payment Gateway
Today, we are share with you how to integrate card payment in laravel using Instamojo payment API. many time you need to integrate any payment method in your laravel application. you can done payment integration like paypal, stripe, rozorpay etc... and we are also write many tutorial about payment gateway integration in your laravel application. you can check all tutorils from our payment gateway category. [ADDCODE] Here we are share one another payment gateway integration in laravel and this is instamojo payment gateway. this payment gateway easy to use in your laravel application and you can also use their many functionality. Instamojo mainly use in india. if you want integrate card payment in your laravel application then instamojo is best option for you. here we are show you how to integrate instamojo payment gateway in your laravel application start to end. simpaly follow this step. What we need for integration: First things what we need for integration instamojo payment gateway in our laravel or php application. first we are integrate instamojo in test mode then after you can switch our live integration after success done integration test integration. Now you should create one account for test integration so open this link and create your account Instamojo Test Account. some simplay details you must be fill open test account and aso live account. After you create test account successfully then open this link Get Integration Keys. and get your Api-Key and Auth-Token. get both of keys then we are move to in our write laravel application code for integrate instamojo card payment system. Live Entry Point Url https://www.instamojo.com/api/1.1/payment-requests/ Create Route: Now, create following route in your routes/web.php file. add following route in it. Route::get('payment', 'PaymentController@index')->name('payment'); Route::post('payment', 'PaymentController@payment')->name('payment'); Route::get('returnurl', 'PaymentController@returnurl')->name('returnurl'); Create PaymentController: Now, create one PaymentController.php file in app/Http/Controllers/ and simpaly add followeing code in it. namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use View; use Session; use Redirect; class PaymentController extends Controller { public function __construct() { } public function index(Request $request) { return view('paymentwithinstamojo'); } public function payment(Request $request) { $this->validate($request, [ 'amount' => 'required', 'purpose' => 'required', 'buyer_name' => 'required', 'phone' => 'required', ]); $ch = curl_init(); // For Live Payment // curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/payment-requests/'); // For Test payment curl_setopt($ch, CURLOPT_URL, 'https://test.instamojo.com/api/1.1/payment-requests/'); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Api-Key:test_ba7110d4436b456238fc630d248", "X-Auth-Token:test_8ee7a19348456600fdf9169c9c7")); $payload = Array( 'purpose' => $request->get('purpose'), 'amount' => $request->get('amount'), 'phone' => $request->get('phone'), 'buyer_name' => $request->get('buyer_name'), 'redirect_url' => url('/returnurl'), 'send_email' => false, 'webhook' => 'http://instamojo.com/webhook/', 'send_sms' => true, 'email' => 'laracode101@gmail.com', 'allow_repeated_payments' => false ); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload)); $response = curl_exec($ch); $err = curl_error($ch); curl_close($ch); if ($err) { \Session::put('error','Payment Failed, Try Again!!'); return redirect()->back(); } else { $data = json_decode($response); } if($data->success == true) { return redirect($data->payment_request->longurl); } else { \Session::put('error','Payment Failed, Try Again!!'); return redirect()->back(); } } public function returnurl(Request $request) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://test.instamojo.com/api/1.1/payments/'.$request->get('payment_id')); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Api-Key:test_ba7110d4436b456238fc630d248", "X-Auth-Token:test_8ee7a19348456600fdf9169c9c7")); $response = curl_exec($ch); $err = curl_error($ch); curl_close($ch); if ($err) { \Session::put('error','Payment Failed, Try Again!!'); return redirect()->route('payment'); } else { $data = json_decode($response); } if($data->success == true) { if($data->payment->status == 'Credit') { // Here Your Database Insert Login // dd($data); \Session::put('success','Your payment has been pay successfully, Enjoy!!'); return redirect()->route('payment'); } else { \Session::put('error','Payment Failed, Try Again!!'); return redirect()->route('payment'); } } else { \Session::put('error','Payment Failed, Try Again!!'); return redirect()->route('payment'); } } } Create View File: Now, we are create paymentwithinstamojo.blade.php in resources/views folder and add following bootstap code in this file for your design view. @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-12"> @if($message = Session::get('error')) <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Error Alert!</strong> {{ $message }} </div> @endif {!! Session::forget('error') !!} @if($message = Session::get('success')) <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Success Alert!</strong> {{ $message }} </div> @endif {!! Session::forget('success') !!} </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="card card-default"> <div class="card-header"> <div class="row"> <div class="col-md-10"> <strong>Pay With Instamojo</strong> </div> </div> </div> <div class="card-body"> <form class="form-horizontal" method="POST" action="{{ URL::route('payment') }}"> @csrf <div class="form-group"> <label for="purpose" class="col-md-12 col-form-label">Purpose</label> <div class="col-md-12"> <input id="purpose" type="text" class="form-control" name="purpose" value="" required> @if ($errors->has('purpose')) <span class="help-block"> <strong>{{ $errors->first('purpose') }}</strong> </span> @endif </div> </div> <div class="form-group"> <label for="buyer_name" class="col-md-12 col-form-label">Buyer Name</label> <div class="col-md-12"> <input id="buyer_name" type="text" class="form-control" name="buyer_name" value="" required> @if ($errors->has('buyer_name')) <span class="help-block"> <strong>{{ $errors->first('buyer_name') }}</strong> </span> @endif </div> </div> <div class="form-group"> <label for="amount" class="col-md-12 col-form-label">Amount</label> <div class="col-md-12"> <input id="amount" type="number" class="form-control" name="amount" value="" required> @if ($errors->has('amount')) <span class="help-block"> <strong>{{ $errors->first('amount') }}</strong> </span> @endif </div> </div> <div class="form-group"> <label for="phone" class="col-md-12 col-form-label">Phone No.</label> <div class="col-md-12"> <input id="phone" type="number" class="form-control" name="phone" value="" required> @if ($errors->has('phone')) <span class="help-block"> <strong>{{ $errors->first('phone') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-12 col-md-offset-3"> <button type="submit" class="btn btn-primary btn-block desabled" id="submitUser"> Submit </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection After done your payment success then open your instamojo dashboard and you can seen your payment open by this link https://test.instamojo.com/payments/ Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/payment Please also check our demo for realtime CRUD system. We are hope you like this tutorials, if any question regarding any query please post your question in our forums click on bellow link Laravelcode's Forums
PHP - How To Integrate Paypal Payment Gateway In PHP
Today, laravelcode share with you how to integrate paypal payment gateway in php with sample code. currently many payment gateway in available in market, but i thinks paypal is most populer for make payment in online and integrate in most of website and even android application also. In this tutorials we are make one simple add to cart with paypal payment ussing by simple html, css and php, simply follow this step and easaly integrate paypal in your php code. [ADDCODE] Create index.php: In the first step create index.php file in your any blank folder and put into it following code. we are using simple boostrap layout for pay with paypal and make simple add to cart design if you copy and past this following code and then run your index file your html output looking like that. show this screenshot. <!DOCTYPE html> <html> <head> <title>LaravelCode - Paypal Integration Demo In PHP</title> <link rel="stylesheet" type="text/css" href="https://laravelcode.com/css/app.css"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <?php // test url $paypalUrl='https://www.sandbox.paypal.com/cgi-bin/webscr'; // live url $paypalUrl='https://www.paypal.com/cgi-bin/webscr'; $paypalId='test-facilitator-1@gmail.com'; ?> <div id="app"> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="https://laravelcode.com/"> LaravelCode Demo </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav">   </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> </ul> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-md-12 col-md-offset-0"> <div class="panel panel-default"> <div class="panel-heading">Products List</div> <div class="panel-body"> <div class="col-md-4"> <form action="<?php echo $paypalUrl; ?>" method="post" name="frmPayPal1"> <input type="hidden" name="business" value="<?php echo $paypalId; ?>"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="item_name" value="It Solution Stuff"> <input type="hidden" name="item_number" value="2"> <input type="hidden" name="amount" value="84"> <input type="hidden" name="no_shipping" value="1"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="cancel_return" value="/cancel.php"> <input type="hidden" name="return" value="/success.php"> <figure class="snip1249"> <div class="image"> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/331810/sample85.jpg" alt="sample85"/><i class="ion-ios-star-outline"></i> </div> <figcaption> <h3>Time Piece</h3> <p>I'm killing time while I wait for life to shower me with meaning.</p> <div class="price"> <s>$99.00</s>$84.00 </div> <button class="add-to-cart">Pay By Paypal</button> </figcaption> </figure> </form> </div> </div> </div> </div> </div> </div> </div> <script src="https://laravelcode.com/js/app.js"></script> </body> </html> Create style.css: Now, create style.css file for pay by paypal product layout, and put into it simple this css code. /* Icon set - http://ionicons.com */ @import url(https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css); @import url(https://fonts.googleapis.com/css?family=Raleway:400,500); figure.snip1249 { font-family: 'Raleway', Arial, sans-serif; position: relative; float: left; overflow: hidden; margin: 10px 1%; /*min-width: 220px;*/ /*max-width: 310px;*/ /*width: 100%;*/ background: #1a1a1a; color: #ffffff; text-align: left; box-shadow: 0 0 5px rgba(0, 0, 0, 0.15); background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 100%); background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 100%); } figure.snip1249 * { -webkit-box-sizing: border-box; box-sizing: border-box; -webkit-transition: all 0.35s ease-in-out; transition: all 0.35s ease-in-out; } figure.snip1249 .image { position: relative; } figure.snip1249 img { max-width: 100%; vertical-align: top; } figure.snip1249 i { position: absolute; top: 7px; left: 12px; font-size: 32px; opacity: 0; z-index: 2; -webkit-transition-delay: 0; transition-delay: 0; } figure.snip1249 h3 { margin: 0; font-weight: 500; text-transform: uppercase; } figure.snip1249:before, figure.snip1249:after { width: 120px; height: 120px; position: absolute; top: 0; left: 0; content: ''; -webkit-transition: all 0.35s ease; transition: all 0.35s ease; z-index: 1; box-shadow: 0 0 20px rgba(0, 0, 0, 0.5); background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.35) 100%); background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.35) 100%); -webkit-transition-delay: 0.2s; transition-delay: 0.2s; } figure.snip1249:before { background-color: #20638f; -webkit-transform: skew(-45deg) translateX(-150%); transform: skew(-45deg) translateX(-150%); border-right: 1px solid #20638f; } figure.snip1249:after { background-color: #962d22; -webkit-transform: skew(-45deg) translateX(-175%); transform: skew(-45deg) translateX(-175%); border-right: 1px solid #962d22; } figure.snip1249 figcaption { padding: 25px 80px 25px 25px; background-color: #ffffff; color: #000000; position: relative; font-size: 0.9em; } figure.snip1249 figcaption p { margin-bottom: 15px; } figure.snip1249 figcaption:before { width: 150px; height: 150px; position: absolute; bottom: 0; right: 0; content: ''; z-index: 1; background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.35) 100%); background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.35) 100%); background-color: #20638f; -webkit-transform: skew(-45deg) translateX(50%); transform: skew(-45deg) translateX(50%); border-right: 1px solid #20638f; } figure.snip1249 .add-to-cart { display: inline-block; width: auto; border: 2px solid #20638f; padding: 0.4em 0.6em; color: #20638f; text-decoration: none; font-weight: 800; font-size: 0.9em; text-transform: uppercase; } figure.snip1249 .add-to-cart:hover { background-color: #20638f; color: #ffffff; } figure.snip1249 .price { position: absolute; right: 0; bottom: 0; color: #ffffff; z-index: 2; text-transform: uppercase; padding: 20px; font-weight: 800; font-size: 1.2em; text-align: center; } figure.snip1249 .price s { display: block; font-size: 0.85em; font-weight: 400; opacity: 0.8; } figure.snip1249:hover i, figure.snip1249.hover i { opacity: 0.7; -webkit-transition-delay: 0.3s; transition-delay: 0.3s; } figure.snip1249:hover h3, figure.snip1249.hover h3 { -webkit-transform: translateY(0); transform: translateY(0); opacity: 1; } figure.snip1249:hover:before, figure.snip1249.hover:before { -webkit-transition-delay: 0s; transition-delay: 0s; -webkit-transform: skew(-45deg) translateX(-50%); transform: skew(-45deg) translateX(-50%); } figure.snip1249:hover:after, figure.snip1249.hover:after { -webkit-transition-delay: 0.1s; transition-delay: 0.1s; -webkit-transform: skew(-45deg) translateX(-75%); transform: skew(-45deg) translateX(-75%); } /* Demo purposes only */ body { /*background-color: #212121;*/ } Create success.php: Now, create success.php file. if your paypal payment pay successfully then after payment user redirect on this file. you can manage here your database logic. like insert data in database and show success message to user. $itemNo = $_REQUEST['item_number']; $itemTransaction = $_REQUEST['tx']; // Paypal transaction ID $itemPrice = $_REQUEST['amt']; // Paypal received amount $itemCurrency = $_REQUEST['cc']; // Paypal received currency type $price = '20.00'; $currency='USD'; if($itemPrice==$price && $itemCurrency==$currency) { echo "Payment Successful"; } else { echo "Payment Failed"; } Create cancel.php: Last create one another file cancel.php for in-case paypal payment have some issue then user redirect on Cancel.php file after canceletion and here you can manage cancel message. echo "Payment Canceled"; We are hope you like this tutorials, if any question regarding any query please post your question in our forums click on bellow link Laravelcode's Forums
Laravel 5.5 - Razorpay Payment Gateway Integration
Today, we are share with you in this tutorial How To Integration Razorpay Payment Gateway In Laravel 5.5 with easy example and demo. Currently many payment gatway available in market like paypal, stripe, paycheckout, CCAvenue etc.., if you are built your product forr indian market then Razorpay is best for make online payment. it very easy to use in any programing language. Simple following this step and easyly integrate Razorpay in your laravel application. Create Razorpay Account First, we need to create Razorpay account fron click by this link Razorpay Account. and get your razor_key and razor_secret from the account. See following screenshot for how to create key from account. Install package Next, we need to install razorpay/razorpay laravel package in our application rub by following command. composer require razorpay/razorpay Create Config File Nex, we need to create one custom.php file in config folder. in this file we are set our Razorpay's account razor_key and razor_secret so we are use in our integration for make payment. return [ 'razor_key' => 'rzp_test_razor_key', 'razor_secret' => 'rzp_test_razor_secret' ]; Create Route Next, we need to create following two route one for show payment form and second one is post action route. so, open your routes/web.php and create following two route. // Get Route For Show Payment Form Route::get('paywithrazorpay', 'RazorpayController@payWithRazorpay')->name('paywithrazorpay'); // Post Route For Makw Payment Request Route::post('payment', 'RazorpayController@payment')->name('payment'); [ADDCODE] Create Controller Now we are create controller, so create RazorpayController.php file in your app/Http/Controllers folder. namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Razorpay\Api\Api; use Session; use Redirect; class RazorpayController extends Controller { public function payWithRazorpay() { return view('payWithRazorpay'); } public function payment() { //Input items of form $input = Input::all(); //get API Configuration $api = new Api(config('custom.razor_key'), config('custom.razor_secret')); //Fetch payment information by razorpay_payment_id $payment = $api->payment->fetch($input['razorpay_payment_id']); if(count($input) && !empty($input['razorpay_payment_id'])) { try { $response = $api->payment->fetch($input['razorpay_payment_id'])->capture(array('amount'=>$payment['amount'])); } catch (\Exception $e) { return $e->getMessage(); \Session::put('error',$e->getMessage()); return redirect()->back(); } // Do something here for store payment details in database... } \Session::put('success', 'Payment successful, your order will be despatched in the next 48 hours.'); return redirect()->back(); } } Create View Now we are create controller, so create payWithRazorpay.blade.php file in your resources/views/ folder. Info Message!! #First check jQuery should be add in head section.. @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> @if($message = Session::get('error')) <div class="alert alert-danger alert-dismissible fade in" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Error!</strong> {{ $message }} </div> @endif {!! Session::forget('error') !!} @if($message = Session::get('success')) <div class="alert alert-info alert-dismissible fade in" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Success!</strong> {{ $message }} </div> @endif {!! Session::forget('success') !!} <div class="panel panel-default"> <div class="panel-heading">Pay With Razorpay</div> <div class="panel-body text-center"> <form action="{!!route('payment')!!}" method="POST" > <!-- Note that the amount is in paise = 50 INR --> <!--amount need to be in paisa--> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="{{ Config::get('custom.razor_key') }}" data-amount="1000" data-buttontext="Pay 10 INR" data-name="Laravelcode" data-description="Order Value" data-image="yout_logo_url" data-prefill.name="name" data-prefill.email="email" data-theme.color="#ff7529"> </script> <input type="hidden" name="_token" value="{!!csrf_token()!!}"> </form> </div> </div> </div> </div> </div> @endsection Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/paywithrazorpay Testing Data Visa Card No. : 4242424242424242 Mbile No. : 9898989898 OTP No. : 123456 If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...
How to integrate paypal payment gateway in laravel 5.4
Hello, today laravelcode share with you a one of the very nice tutorials of how to integrattion paypal payment gateway in your laravel to very easy way with simple example and with working code. You are need to integration payment gateway in many laravel application and many developer guss is to hard but it is very easy and simple problem. here we are help to you how to integrate payment gateway in your laravel application with paypal. Today paypal is major and world most very usefull payment gateway which many people want to integrate with thair website. so, laravelcode show you how to integrate paypal with laravel. We are use here paypal/rest-api-sdk-php package for integrate paypal with laravel. this is very good paypal package for integrate paypal with laravel. Here i give you full example of How to integrate paypal payment gateway step by step like create laravel project, migration, model, route, blade file etc. So you have to just follow few step as listed bellow. Follow Bellow Few Step: 1)Create new Laravel Application 2)Database Configuration 3)Install Required Packages 4)Configuration paypal.php file 5)Create route 6)Create controller 7)Create view file   Step : 1 Create new laravel application Here, we are create new one laravel project by using collowing command composer create-project --prefer-dist laravel/laravel blog Step : 2 Database Configuration After create new onw laravel application then after we need to configration our database setting in .env file like that DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret Step : 3 Install Required Packages After configure .env file now we are install require package for integrate paypal payment gateway in our laravel application. we are paypal/rest-api-sdk-php package. "guzzlehttp/guzzle": "~5.2", "paypal/rest-api-sdk-php": "*", After added above two package in your laravel application's composer.json file and then after you are need to composer update using following command in your terminal or cmd sudo composer update After update composer and you get not any error during installation of package. then move to next step if incase you getting any error so, please try again. Step : 4 Configuration paypal.php file We need to create one confige file paypal.php in config folder and in this file we are set our paypal client_id and secret and more paypal configration options like this way If you are not knowing how to create paypal client_id and secret in paypal sendbox. please show this video for it How to integrate paypal with laravel /** set your paypal credential **/ 'client_id' =>'paypal client_id', 'secret' => 'paypal secret ID', /** * SDK configuration */ 'settings' => array( /** * Available option 'sandbox' or 'live' */ 'mode' => 'sandbox', /** * Specify the max request time in seconds */ 'http.ConnectionTimeOut' => 1000, /** * Whether want to log to a file */ 'log.LogEnabled' => true, /** * Specify the file that want to write on */ 'log.FileName' => storage_path() . '/logs/paypal.log', /** * Available option 'FINE', 'INFO', 'WARN' or 'ERROR' * * Logging is most verbose in the 'FINE' level and decreases as you * proceed towards ERROR */ 'log.LogLevel' => 'FINE' ), ); Step : 5 Create route No we are required three route in you routes/web.php file one is required for show paypal payment form view and one another is for make post HTTP request and therd for check our payment return status responce is true or false like this way // route for view/blade file Route::get('paywithpaypal', array('as' => 'paywithpaypal','uses' => 'PaypalController@payWithPaypal',)); // route for post request Route::post('paypal', array('as' => 'paypal','uses' => 'PaypalController@postPaymentWithpaypal',)); // route for check status responce Route::get('paypal', array('as' => 'status','uses' => 'PaypalController@getPaymentStatus',)); Step : 6 Create PaypalController [ADDCODE] Now create PaypalController.php file in app/Http/Controllers folder like this way. <?php namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; use Validator; use URL; use Session; use Redirect; use Input; /** All Paypal Details class **/ use PayPal\Rest\ApiContext; use PayPal\Auth\OAuthTokenCredential; use PayPal\Api\Amount; use PayPal\Api\Details; use PayPal\Api\Item; use PayPal\Api\ItemList; use PayPal\Api\Payer; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Api\ExecutePayment; use PayPal\Api\PaymentExecution; use PayPal\Api\Transaction; class AddMoneyController extends HomeController { private $_api_context; /** * Create a new controller instance. * * @return void */ public function __construct() { parent::__construct(); /** setup PayPal api context **/ $paypal_conf = \Config::get('paypal'); $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret'])); $this->_api_context->setConfig($paypal_conf['settings']); } /** * Show the application paywith paypalpage. * * @return \Illuminate\Http\Response */ public function payWithPaypal() { return view('paywithpaypal'); } /** * Store a details of payment with paypal. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function postPaymentWithpaypal(Request $request) { $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item_1 = new Item(); $item_1->setName('Item 1') /** item name **/ ->setCurrency('USD') ->setQuantity(1) ->setPrice($request->get('amount')); /** unit price **/ $item_list = new ItemList(); $item_list->setItems(array($item_1)); $amount = new Amount(); $amount->setCurrency('USD') ->setTotal($request->get('amount')); $transaction = new Transaction(); $transaction->setAmount($amount) ->setItemList($item_list) ->setDescription('Your transaction description'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(URL::route('status')) /** Specify return URL **/ ->setCancelUrl(URL::route('status')); $payment = new Payment(); $payment->setIntent('Sale') ->setPayer($payer) ->setRedirectUrls($redirect_urls) ->setTransactions(array($transaction)); /** dd($payment->create($this->_api_context));exit; **/ try { $payment->create($this->_api_context); } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { \Session::put('error','Connection timeout'); return Redirect::route('paywithpaypal'); /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/ /** $err_data = json_decode($ex->getData(), true); **/ /** exit; **/ } else { \Session::put('error','Some error occur, sorry for inconvenient'); return Redirect::route('paywithpaypal'); /** die('Some error occur, sorry for inconvenient'); **/ } } foreach($payment->getLinks() as $link) { if($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } /** add payment ID to session **/ Session::put('paypal_payment_id', $payment->getId()); if(isset($redirect_url)) { /** redirect to paypal **/ return Redirect::away($redirect_url); } \Session::put('error','Unknown error occurred'); return Redirect::route('paywithpaypal'); } public function getPaymentStatus() { /** Get the payment ID before session clear **/ $payment_id = Session::get('paypal_payment_id'); /** clear the session payment ID **/ Session::forget('paypal_payment_id'); if (empty(Input::get('PayerID')) || empty(Input::get('token'))) { \Session::put('error','Payment failed'); return Redirect::route('paywithpaypal'); } $payment = Payment::get($payment_id, $this->_api_context); /** PaymentExecution object includes information necessary **/ /** to execute a PayPal account payment. **/ /** The payer_id is added to the request query parameters **/ /** when the user is redirected from paypal back to your site **/ $execution = new PaymentExecution(); $execution->setPayerId(Input::get('PayerID')); /**Execute the payment **/ $result = $payment->execute($execution, $this->_api_context); /** dd($result);exit; /** DEBUG RESULT, remove it later **/ if ($result->getState() == 'approved') { /** it's all right **/ /** Here Write your database logic like that insert record or value in database if you want **/ \Session::put('success','Payment success'); return Redirect::route('paywithpaypal'); } \Session::put('error','Payment failed'); return Redirect::route('paywithpaypal'); } } Step : 7 Create view file Now, we are create one resources/views/paywithpaypal.blade.php for display paypal form @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> @if ($message = Session::get('success')) <div class="custom-alerts alert alert-success fade in"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button> {!! $message !!} </div> <?php Session::forget('success');?> @endif @if ($message = Session::get('error')) <div class="custom-alerts alert alert-danger fade in"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button> {!! $message !!} </div> <?php Session::forget('error');?> @endif <div class="panel-heading">Paywith Paypal</div> <div class="panel-body"> <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" > {{ csrf_field() }} <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}"> <label for="amount" class="col-md-4 control-label">Amount</label> <div class="col-md-6"> <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus> @if ($errors->has('amount')) <span class="help-block"> <strong>{{ $errors->first('amount') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Paywith Paypal </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/paywithpaypal I hope it can help you...