📜 ⬆️ ⬇️

We create a website using Laravel and Recurly. Part 1

Planning and processing payments is easy, but receiving regular payments is not easy. Difficulties can arise very quickly. You must decide how to handle failures, payment data should be constantly up to date, and keep the data on the site up to date. And perhaps the most important question is to keep your users informed of billing information on the site.
Fortunately, Recurly is a service that performs most of the tasks associated with processing regular payments. Using JavaScript libraries, you can create secure forms for sending and updating payment information, including all important payment card data.
After you determine the amount and frequency of payments, Recurly takes care of scheduling and accepting payments until the client unsubscribes. Recurly also takes into account changes in tariff plans, payments, making and deducting additional payments.
In the first article of the two, I will show you how to create a paid subscription using a website created using the Laravel php framework and the Recurly payment acceptance service. We will start by creating a website with simple registration, authorization and user rights. Then we will add payment processing, link it with the registration process, which will allow users to buy different tariff plans.

Install the application.


Let's start creating an application by creating a new folder for the project and running the following command:
composer create-project laravel/laravel recurly --prefer-dist 

This command will create a new Laravel application, use Composer, download the framework and all necessary dependencies. Later we will need several libraries, so add the following lines to composer.json and run composer.phar update
 "machuga/authority": "dev-develop", "machuga/authority-l4" : "dev-master", "recurly/recurly-client": "2.1.*@dev" 

The Authority library, which will be used to create user roles and access rights, and the Recurly library will be downloaded.
Then, you need to configure the connection to the database by specifying the value of the scheme, user, password and address to the database in the file app / config / database.php. Laravel works out of the box with the following databases: MySql, Posrges, SQLite and SQL Server.
We will also need a table with users. Instead of doing everything “hands”, we use the migration mechanism provided by Laravel. Run the following command:
 php artisan migrate:make create_users_table 

This command will create a migration file in the app / database / migrations folder.
 public function up() { Schema::create('users', function($table) { $table->increments('id'); $table->string('email')->unique(); $table->string('name'); $table->string('password'); $table->timestamps(); }); } public function down() { Schema::drop('users'); } 

Let's go back to the command line and execute:
 php artisan migrate 

We look in the database and see that Laravel has created a table with users.

Create user roles and permissions.


To determine the type of user and rights for this user, we will set the users role. We have already downloaded the Authoriry library using composer, and now we have to complete a few more steps to set up the roles completely.
In the file app / config / app.php, add the following line:
 'Authority\AuthorityL4\AuthorityL4ServiceProvider', 

Add the following line to aliases:
 'Authority' => 'Authority\AuthorityL4\Facades\Authority', 

and publish the Authority settings file with the following command:
 php artisan config:publish machuga/authority-l4 

Let's go back to the settings file later. And now, we need to create several additional tables in the database. Fortunately, Laravel contains its own migrations for them. Run them with the following command:
 php artisan migrate --package="machuga/authority-l4" 

You will see that 3 additional tables have been created: permissions , roles , role_user .
Now we need to create a model for working with roles and access rights. Until we change them and leave them very simple. In app / models / Role.php :
 <?php class Role extends Eloquent { } 

In the file: app / models / Permission.php :
 <?php class Permission extends Eloquent { } 

Now we have to change the User model, it has already been created, and we will add a user connection with their roles and access rights. Add the following lines to app / models / User.php :
 public function roles() { return $this->belongsToMany('Role'); } public function permissions() { return $this->hasMany('Permission'); } public function hasRole($key) { foreach($this->roles as $role){ if ($role->name === $key) { return true; } } return false; } 

And now fill the database with some data. Open the file app / database / seeds / DatabaseSeeder.php and paste the following:
 <?php class DatabaseSeeder extends Seeder { public function run() { Eloquent::unguard(); $this->call('UserTableSeeder'); $this->command->info('User table seeded!'); $this->call('RoleTableSeeder'); $this->command->info('Role table seeded!'); } } class UserTableSeeder extends Seeder { public function run() { DB::table('users')->delete(); User::create(array( 'email' => 'joe.bloggs@example.com', 'name' => 'Joe Bloggs', 'password' => Hash::make('password') )); } } class RoleTableSeeder extends Seeder { public function run() { DB::table('roles')->delete(); Role::create(array('name' => 'admin')); Role::create(array('name' => 'pending')); Role::create(array('name' => 'member')); Role::create(array('name' => 'bronze')); Role::create(array('name' => 'silver')); Role::create(array('name' => 'gold')); } } 

Next, fill the database by running the following command:
 php artisan db:seed 

')

Create a template


Now we will create a common template for the pages. Download for this Twitter Bootstrap and put the source in the public folder, and the js-files in the folder - public / js / libs /
Create the file app / views / layouts / default.blade.php with the following code:
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Subscription Site Tutorial</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="/css/bootstrap.css" rel="stylesheet"> <link href="/css/style.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="#">Subscription Site Tutorial</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container"> @if(Session::has('success')) <div class="alert alert-success"> <button type="button" class="close" data-dismiss="alert">Ă—</button> {{ Session::get('success') }} </div> @endif @if(Session::has('error')) <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">Ă—</button> {{ Session::get('error') }} </div> @endif @yield('content') </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="/js/libs/bootstrap.min.js"></script> </body> </html> 

This is the basic template for our site, the page content will be displayed in the line @yield ('content') .
Next, create the file public / css / style.css :
 body { padding-top: 50px; } p.logged-in { color: white; margin-top: 0.5em; } 

And finally, let's create the main page of our site. Create the file app / views / home / index.blade.php :
 @extends('layouts.default') @section('content') <h1>Subscription Site Tutorial</h1> @stop 

@extends tells Laravel to use the default template we just created.
Do not forget to change the routing of our site in the file app / routes.php :
 Route::get('/', function() { return View::make('home/index'); }); 

Create an authorization mechanism


We have users, and now we have to give them the opportunity to log in. In the app / routse.php file , add the path to the login page:
 Route::get('/auth/login', function() { return View::make('auth/login'); }); 

We will now create a mapping in the app / views / auth / login.blade.php file . .blacde means that we use the Blade template engine that comes with Laravel.
 @extends('layouts.default') @section('content') <h1>Please Log in</h1> {{ Form::open(array('url' => 'auth/login')) }} {{ Form::label('email', 'E-Mail Address') }} {{ Form::text('email') }} {{ Form::label('password', 'Password') }} {{ Form::password('password') }} <div class="form-actions"> {{ Form::submit('Login', array('class' => 'btn btn-primary')) }} </div> {{ Form::close() }} <p>Not a member? <a href="/user/register">Register here</a>.</p> @stop 

If you go to the address / auth / logn you will see a simple login form. To process the input, we will need to process the POST data. Authorization in Laravel is simple:
 Route::post('/auth/login', function() { $email = Input::get('email'); $password = Input::get('password'); if (Auth::attempt(array('email' => $email, 'password' => $password))) { return Redirect::to('/')->with('success', 'You have been logged in'); } else { return Redirect::to('auth/login')->with('error', 'Login Failed'); } return View::make('auth/login'); }); 

All the magic is in the Auth :: request () method; if the authorization is successful, a session is created and an instance of the User object is available through the static Auth :: user () method.
Logout method:
 Route::get('/auth/logout', function() { Auth::logout(); return Redirect::to('/')->with('success', 'You have successfully logged out'); }); 


Basic registration


Our last task, in this part, is to create a registration process. Create a path for registration in the app / routse / php file:
 Route::get('/user/register', function() { return View::make('user/register/index'); }); 

Create a view in the /app/views/user/register/index.blade.php file:
 @extends('layouts.default') @section('content') {{ Form::open(array('url' => 'user/register')) }} {{ Form::label('email', 'E-Mail Address') }} {{ Form::text('email') }} {{ $errors->first('email') }} {{ Form::label('name', 'Your name') }} {{ Form::text('name') }} {{ $errors->first('name') }} {{ Form::label('password', 'Password') }} {{ Form::password('password') }} {{ $errors->first('password') }} {{ Form::label('password_confirmation', 'Repeat') }} {{ Form::password('password_confirmation') }} <div class="form-actions"> {{ Form::submit('Register', array('class' => 'btn btn-primary')) }} </div> {{ Form::close() }} @stop 

I will note a few points:

We now turn to the processing of POST data:
 Route::post('/user/register', function() { $validator = Validator::make( Input::all(), array( 'name' => array('required', 'min:5'), 'email' => array('required', 'email', 'unique:users'), 'password' => array('required', 'confirmed') ) ); if ($validator->passes()) { $user = new User(); $user->name = Input::get('name'); $user->email = Input::get('email'); $user->password = Hash::make(Input::get('password')); $user->save(); $role_pending = Role::where('name', '=', 'pending')->first(); $user->roles()->attach($role_pending); Auth::login($user); return Redirect::to('/')->with( 'success', 'Welcome to the site, . Auth::user()->name . '!' ); } else { return Redirect::to('user/register')->with( 'error', 'Please correct the following errors:' )->withErrors($validator); } }); 

This is a fairly simple way. We create a validator and pass POST data to it (Input :: all ()) and define the rules for validation. If validation has passed, you create a new user, assign roles to it, authorize it, and redirect it to the main page.
If the validation fails, we redirect the user back to the form, create an error message, and pass error messages from the validator that will be available from the view in the $ errors variable.

Conclusion


In this part, we step by step created the "skeleton" of the application, to work with paid subscriptions. In the next part, we will integrate Recurly to use subscriptions.

Source: https://habr.com/ru/post/195690/


All Articles