Posted on Leave a comment

Get Your Daily Stripe Balance Using Laravel Task Scheduler

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Laravel Task Scheduler

I create many apps that use the Uber business model for paying out contractors using Stripe, and I make money by using application fees. I like to get my daily account available and pending balances from Stripe. Using Laravel’s built in task scheduler this is trivial. Laravel provides a way to define all of your application’s scheduled jobs within Laravel itself, so that you only have to manage one cron tab * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1 it’s pretty awesome!

Install Dependencies

I will assume you have created a new Laravel install. I  need the Stripe PHP composer module for this to work. Go to the root of your application and type the following command composer require stripe/stripe-php now you have all the necessary components installed.

Define Schedule

All schedules are defined in schedule() method of the App\Console\Kernel located at app/console/kernel.php. I want to make a stripe call to retrieve my balance, both available and pending.

<?php
namespace App\Console;
use Mail;
use Carbon\Carbon;
use DB;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\Inspire::class,
    ];
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
        \Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
       $balance = \Stripe\Balance::retrieve();
       $emailText = "As of {Carbon::today()->toDayDateTimeString()}  your available balance is {$balance->available->amount} and your pending balance is {$balance->pending->amount}";
Mail::raw('Text to e-mail', function ($message) {
    //
    
 $message->from('financial@app.com', 'Your Application');
            $message->to(env('EMAIL_ADDRESS'),env('EMAIL_NAME'))->subject('Your Daily Stripe Balance!');
}); })->daily();  } }

With this piece of code I am now getting daily emails with the date, my available balance, and my pending balance. If you liked this please share and subscribe to my blog posts via email to the right!

Posted on Leave a comment

API Authentication In Laravel 5.2

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Hours Saved!

Token based API authentication is something you are inevitably going to encounter if you plan on working with web/mobile apps (unless you are coding under a rock). The benefits are great, in fact here are six of them; However it can be a nightmare if you need to create your own token authentication server. As of Laravel 5.2, there is a new auth guard called conveniently api this guard allows us to check an api_token parameter against an api_token field on our users table in our database.

API Configuration

Almost everything is configured right out of the box, open up config/auth.php and you will see this block of code

  /*
 |--------------------------------------------------------------------------
 | Authentication Guards
 |--------------------------------------------------------------------------
 |
 | Next, you may define every authentication guard for your application.
 | Of course, a great default configuration has been defined for you
 | here which uses session storage and the Eloquent user provider.
 |
 | All authentication drivers have a user provider. This defines how the
 | users are actually retrieved out of your database or other storage
 | mechanisms used by this application to persist your user's data.
 |
 | Supported: "session", "token"
 |
 */
 'guards' => [
 'web' => [
 'driver' => 'session',
 'provider' => 'users',
 ],
 'api' => [
 'driver' => 'token',
 'provider' => 'users',
 ],
 ],

By default Laravel 5.2 uses the web guard, which is the traditional session based model. This model is great for a traditional web application but not suitable for API architecture. The next guard is the api this guard is suitable for routes that need to be consumed by mobile apps and the like. The reason why you would want to do this is because when you are making request from your client-side app, each request is mutually exclusive of the requests before and after it, thus each one requires authentication. In the traditional session based flow, user data is saved on the server and that session data is used in every request, not only is this approach not scalable, it isn’t efficient or as secure as one might think. API token authentication is faster, scalable, and more secure. The biggest benefit of all is that you can now use this token in other applications to access your own API if you so choose. If you would like to see an example leave a comment of what kind of app you would like to see this implemented in and I will write it, record it, and blog it!

Posted on Leave a comment

Write An Charity App With Laravel and Stripe – Models

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Laravel Models

In this segment we will focus on creating the model needed for the application. If you remember in the last post on migrations, we created one migration to represent the charities. Now we will utilize Laravel’s powerful Eloquent ORM, which will allow us to represent our database using PHP objects.
Creating Laravel models is actually very simple when done via Artisan. Head to the project root in the command line and enter the following command

php artisan make:model Charity

afterwards open the newly created file app/Charity.php and add the following contents


<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Charity extends Model
{
//
protected $table = 'charities';
protected $fillable = [
'user_id',
'name',
'description',
'monthly_amount'
];
}

 
The $table variable let’s Eloquent know which table to associate the model with; It is usually not needed, however I prefer to put it in. Next is a $fillable array that holds every attribute needed on a POST request to create a new record. If you look, you will see that there are 2 more Laravel models in the app/ directory. Check them out and read them over and get a good understanding of what’s going on.
app/User.php


<?php
namespace App;
use Laravel\Cashier\Billable;
use Laravel\Spark\Teams\CanJoinTeams;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as BaseUser;
use Laravel\Spark\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatable;
use Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatableContract;
class User extends BaseUser implements TwoFactorAuthenticatableContract
{
use Billable, TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'email',
'name',
'password',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'using_two_factor_auth'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'card_brand',
'card_last_four',
'extra_billing_info',
'password',
'remember_token',
'stripe_id',
'stripe_subscription',
'two_factor_options',
];
}

app/Team.php
 


<?php
namespace App;
use Laravel\Spark\Teams\Team as SparkTeam;
class Team extends SparkTeam
{
//
}
Posted on Leave a comment

Learning Laravel – Installation

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Getting Started Learning Laravel

So you have decided that learning Laravel is worth your time, GOOD FOR YOU! Now you have to go through the task of actually installing and configuring the software on your machine. If you use Laravel Homestead, then all of your system requirements are handled out of the box (I highly recommend this approach), if you choose not to use the VM, make sure your machine satisfies the following requirements:

  • PHP >= 5.5.9
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension

Utilizing Composer

Laravel leverages Composer for all of it’s PHP dependency management. You may ask what is dependency management? Laravel utilizes a plethora of different components in order to make it function. It would be a nightmare if you as the developer is left in charge on managing all of these dependencies, with updates and patches and whatnot. This is where Composer comes in and makes your life pleasant. Composer keeps everything up-to-date, if a package requires other packages then Composer will handle all of the downloads. It’s like gem for Ruby or NPM for Node. If you don’t already have it installed it is quite easy, go to your command line and enter the following command.

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

This will install composer globally so you can just type

composer <command>

if you run into any errors, then try running with the sudo command.
The first thing that we will do is install the Laravel installer with composer:

composer global require "laravel/installer"

Before you do anything else, make sure you put ~/.composer/vendor/bin in your PATH . Now you can start a new Laravel application by issuing the command

laravel new <app> 

doing so will create a new Laravel app creating a folder in the process where is your application’s name.

Posted on 2 Comments

Write An Charity App With Laravel and Stripe – Migrations

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Laravel Migrations

In this segment we are going to focus on prepping our database. Migrations are a way for you as a developer to manage the schemas for your application’s database tables. This is also where you define the skeleton of your Eloquent models, since their attributes are based off the table they correspond to. For a more in depth understanding of migrations and how they work, go through my Learning Laravel posts.

Command Line Time

Head to the command line and go to the root of the project we created in the last post.  Using the artisan CLI tool, we will generate some migrations. Enter the following command

php artisan make:migration create_charities_table --create=charities

This will create a new migration file in the database/migrations folder. Open it up and copy the following code


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCharitiesTable extends Migration {
/**
* Run the migrations.
*
* @return void */
  public function up() {
         Schema::create('charities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('name');
            $table->string('description');
            $table->decimal('monthly_amount',5,2);
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('charities');
    }
}

The first thing we add is a foreign key constraint, so that we can easily identify which charities belong to which user, this will become more apparent in the models post. The next three should be self explanatory; We are collecting the name, description and monthly donation amount for the charity. The monthly_amount will also serve as the amount that is charged for one-time donations. If you noticed there are multiple migrations in the database/migrations folder. We can leave these alone for now, but it would be well worth the time to go through and really understand what those files are doing. In any case when you are ready head back to your command line and issue the following command:

 php artisan migrate

Your database is now migrated. If you received any error, make sure your database details are correct in your .env file located at the root of your project directory. Next we will build our Eloquent models. Stay tuned, and remember if you like what you read SHARE IT, and follow me on Twitter @mastashake08

Posted on Leave a comment

Write An Charity App With Laravel and Stripe – Getting Started

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Laravel and Stripe, What Are We Writing?

In this fourteen part series we will be creating a charity app using Laravel and Stripe. The premise is, users join and add charities they own, and add a bank account for funds to be deposited into. Other patrons go to the charity’s page and can either give an one-time charitable donation, or they may choose to make a recurring donation of $1.00 or more either daily/weekly/monthly. The main purpose of this app is to teach the fundamentals of Stripe and Stripe Connect. By the end of this series you should understand:

  • How to create a Stripe managed account through Stripe Connect
  • Collect payments on your users’ behalf
  • Pay funds out to users’ bank account
  • Some experience with Laravel Spark

Getting Started

Let’s create a new Laravel installation by issuing the following command in your terminal

laravel new ParkerCharity

afterwards cd into your app and run

spark install

 
Answer no to the first question asking if you want to run your migrations, and yes to the other two. That’s it for that, next step is MIGRATIONS!

Posted on Leave a comment

Writing Your Own Personal Cloud Music Player – Part 1

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Cloud Based Music Storage

Wouldn’t it be great if you had your own cloud based music player that played all of your music from your server? It’s surprisingly simple to get a basic version of that up with Lumen and Ionic, which I will now show you.
Getting Started
As before I am going to assume you have the environment set up to being development, if not take a moment and read this post. Start with creating a new project


lumen new MusicStorage

Next we need to add a dependency for CORS, if you have followed any of my previous posts this will look familiar


composer require "palanik/lumen-cors:dev-master"

This app will need to provide CORS on all requests so we need to register a global middleware, open up bootstrap/app.php and in the Register Middleware section uncomment the $app->middleware block and make it look like this:


$app->middleware([
// // IlluminateCookieMiddlewareEncryptCookies::class,
// // IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
// // IlluminateSessionMiddlewareStartSession::class,
// // IlluminateViewMiddlewareShareErrorsFromSession::class,
// // LaravelLumenHttpMiddlewareVerifyCsrfToken::class,
palaniklumenMiddlewareLumenCors::class,]);

Since we are here anyway, might as well configure some things. Uncomment these two lines Dotenv::load(DIR.’/../’);
and $app->withFacades(); this will allow us to use the .env file to set app variables and allow us to use some useful Facades that we are definitely going to need.
Migrations
Luckily this app only has one migration, and that is for a files table that only holds id, name, and timestamps. Nice and smooth like. issue this command in your terminal


php artisan make:migration add_files_table --create=files

now open up your newly created migration and paste in the following code:


public function up() {
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('files');
}
}

  • Don’t forget to run your migrations with the command php artisan migrate:install
    Controllers

Like our migration we only have one controller, add a new file in your app/Http/Controllers folder called FileController.php and add the following contents


<?php namespace AppHttpControllers;
use LaravelLumenRoutingController as BaseController;
use IlluminateSupportFacadesStorage;
use IlluminateSupportFacadesFile;
use DB;
use Request;
class FileController extends BaseController { public function saveFile() { $file = Request::file('file'); $name = $file->getClientOriginalName();<br ?--> $name = str_replace(' ', '_', $name);
Storage::put('music/'.$name, file_get_contents($file->getRealPath()));
DB::table('files')->insert(
['name' => $name ]
);
return response()->json('success');
}
public function deleteFile($name)
{
Storage::delete('music/'.$name);
return response()->json('success');
}
public function getFileList(){
$files = Storage::files('music');
$response = [];
foreach($files as $file){
$file = str_replace('music/', '', $file);
array_push($response,[
'file' =>$file
]);
}
return response()->json($response);
}
public function viewFile($name){
$name = 'music/'.$name;
return response()->make(Storage::get($name), 200, [
'Content-Type' => Storage::mimeType($name),
'Content-Disposition' => 'inline; '.$name,
]);
}
}

The methods should be pretty self-explanatory. Let’s map these to some routes, open up app/Http/routes.php and copy:


<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It is a breeze. Simply tell Lumen the URIs it should respond to | and give it the Closure to call when that URI is requested. | */ $app->get('/', 'FileController@getFileList');<br ?--> $app->get('{name}', 'FileController@viewFile');
$app->post('add','FileController@saveFile');
$app->get('delete/{name}', 'FileController@deleteFile');

Your backend is complete, soon I will upload part 2 – The Ionic App. Stay tuned!

Posted on 2 Comments

Creating A POS System With Lumen and Ionic – Part 2

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Before We Begin

Have you already have the Lumen back end micro service up and running? If not head over to part 1 and write your own implementation. Alternatively you can clone the repository from GitHub. Now with that working, let us begin!

Ionic

As with part 1 I will assume you already have the environment set up to begin Ionic development. If you don’t, please head over and read my previous Ionic tutorial. Otherwise let’s create a new project

ionic start ParkerPay

cd into the new application and install the dependencies

bower install ngCordova  

cordova plugin add https://github.com/Paldom/SpinnerDialog.git


cordova plugin add cordova-plugin-dialogs

This will install ngCordova which will allow us to access native APIs via plugins, the two plugins are for accessing native spinner dialogs and alert dialogs. Now let’s edit the application logic, head over to www/js/app.js and paste the following code:


angular.module('parker-pay', ['ionic','ngCordova'])


.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})


.controller('HomeCtrl', function($scope,$http,$cordovaSpinnerDialog,$cordovaDialogs){
$scope.charge = {};
$scope.createToken = function(){
$cordovaSpinnerDialog.show("Processing Payment","Please wait....", true);
Stripe.setPublishableKey('STRIPE PUBLISHABLE KEY');
Stripe.card.createToken({
number: $scope.charge.number,
cvc: $scope.charge.cvc,
exp_month: $scope.charge.exp_month,
exp_year: $scope.charge.exp_year
}, $scope.stripeResponseHandler);
};


$scope.stripeResponseHandler = function(status, response){
if (response.error) {
// Show the errors on the form
$cordovaSpinnerDialog.hide();
$cordovaDialogs.alert('There was an error', 'Alert', 'OK')
.then(function() {
// callback success
});


} else {
// response contains id and card, which contains additional card details
var token = response.id;
//console.log()
// Insert the token into the form so it gets submitted to the server
var data = {token:token,amount:$scope.charge.amount,description:$scope.charge.description}
// and submit


$http.post('http://payment.jyroneparker.com/charge',data).success(function(dta){
console.log(dta);
$cordovaSpinnerDialog.hide();
// beep 1 time
$cordovaDialogs.beep(1);
$cordovaDialogs.alert('Payment was a success.', 'Alert', 'OK')
.then(function() {
// callback success
});

}).error(function(dta){
console.log(dta);
$cordovaSpinnerDialog.hide();
alert('There was an error.');


$cordovaDialogs.alert('There was an error', 'Alert', 'OK')
.then(function() {
// callback success
});


//$cordovaSpinnerDialog.hide();
});
}
}
})

Be sure to put your Stripe key in. Last thing to do programmatically speaking, is to edit the index.html file. Paste the following code:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>

<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->


<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>


<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>


<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="parker-pay" ng-controller="HomeCtrl">


<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Parker Pay</h1>
</ion-header-bar>
<ion-content
<div class="list list-inset">
<label class="icon icon-left ion-pricetag item item-input">
<input ng-model="charge.amount" type="text" placeholder=" Amount">
</label>
<label class="icon icon-left ion-card item item-input">
<input ng-model="charge.number" type="text" placeholder=" Card Number">
</label>
<label class="ion-calendar icon icon-left item item-input">
<input ng-model="charge.exp_month" type="text" placeholder=" Exp. Month">
</label>
<label class="icon icon-left ion-calendar item item-input">
<input ng-model="charge.exp_year" type="text" placeholder=" Exp Year">
</label>
<label class="icon icon-left ion-card item item-input">
<input ng-model="charge.cvc" type="text" placeholder=" CVC">
</label>
<label class="icon icon-left ion-edit item item-input">
<input ng-model="charge.description" type="text" placeholder=" Description">
</label>
</div>
<div class="row">
<button ng-click="createToken()" class="col-offset-33  icon icon-left ion-social-usd button button-positive">
Charge
</button>
</div>
</ion-content>
</ion-pane>
</body>
</html>

Next add your preferred platform by running

ionic platform add <PLATFORM> 

, connect your device and run ionic run <PLATFORM> , THAT’S IT YOU ARE NOW TAKING PAYMENTS!! See how easy that was? You are on your way to being an Artisan! Be sure to check the code out on GitHub

Posted on Leave a comment

Creating A POS System With Lumen and Ionic – Part 1

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Your Very Own POS

I use Stripe all the time in my web and mobile applications to accept payments. It’s great I love it, I don’t have to worry about PCI compliance and they have a kick ass API. In this new programming series I will be showing you how to create your own full stack solution for accepting payments with Stripe. In order to accomplish this it requires a Lumen back end micro service, and an Ionic mobile app, ready? Good! LET’S GET STARTED!!
 

Part 1 – Lumen Back End

If you haven’t read my past Lumen tutorial take the time to read it….or not completely up to you, in either case I am assuming you have the environment to run the following command:

 lumen new StripeServer

before we do anything else, we need to install our dependencies. Kindly input the following commands into your terminal:

composer require stripe/stripe-php palanik/lumen-cors illuminate/mail guzzlehttp/guzzle

The first dependency is for Stripe (So we can take payments), the other is for CORS (we will need this for our mobile app consumption), the last two are for email alerts.
Next we need to create controllers to handle our requests create two controllers: ChargeController.php and WebHookController.php. Inside of ChargeController.php paste the following code:


<?php

namespace AppHttpControllers;

 

use IlluminateHttpRequest;


class ChargeController extends Controller
{
public function charge(Request $request){
StripeStripe::setApiKey(env('STRIPE_KEY'));
StripeCharge::create(array(
"amount" => $request->input('amount'),
"currency" => "usd",
"source" => $request->token,
"description" => $request->input('description')
));
return response()->json(['success'=>'true']);
}}

This controller only has one method. See? It’s not that scary. We are making use of the Stripe Charge API to create a credit card charge, then returning a json response letting us know everything is ok. Now let’s move on to the WebHookController :


<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesMail;
class WebHookController extends Controller
{
public function handleStripe(Request $request){
switch($request->type){
case 'charge.succeeded':
$number = $request->data['object']['amount'] / 100;
Mail::raw('Charge succeeded in amount of $'. money_format('%i', $number) . "n",
function($msg) {
$msg->to([env('PHONE_ADDRESS')]);
$msg->from([[env('MAIL_FROM_ADDRESS')]);
});
break;
case 'charge.failed':
$number = $request->data['object']['amount'] / 100;
Mail::raw('Charge failed in amount of $'. money_format('%i', $number) . "n",
function($msg) {
$msg->to([[env('PHONE_ADDRESS')]);
$msg->from([[env('MAIL_FROM_ADDRESS')]);
});
break;
}
}
}

Here we are sending text message alerts when we get pinged by one of Stripe’s webhook events. Here we are only looking for 2 Stripe events but feel free to add whatever you want. For a more in depth tutorial on sending text messages with Laravel click here. Lastly we need edit the routes file, open routes.php and add the following routes:


$app->post('stripe', 'WebHookController@handleStripe');
$app-> post('charge',['middleware' => 'cors', 'uses' => 'ChargeController@charge']);

Back end is finished, just be sure to edit your .env file. You can view the source code here.

Posted on 1 Comment

Creating A Todo App With SMS Alerts In Laravel 5 – Part 3

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

Delayed Responses

So now we have Facebook integration in our Laravel app, but there is one problem, the Laravel app sends the SMS alert right away. We want to give the users the option to select when the text message goes out. In order to do this we will implement Laravel queues to achieve this task. We will make a new job and move the TodoCreatedListener code into that new job. Let’s get started.
Enter this command into the terminal to create a new job


php artisan make:job SendText --queued

this scaffolds a new job class for you, open that class and copy the following code


 <? php
namespace AppJobs;
use AppJobsJob;
use Mail;
use IlluminateQueueSerializesModels;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsBusSelfHandling;
use IlluminateContractsQueueShouldQueue;
class SendText extends Job implements SelfHandling, ShouldQueue {
use InteractsWithQueue, SerializesModels;
 public $text;
public $phone;
/** * Create a new job instance.
 * * @return void */
public function __construct($text,$phone) {
//
$this->text = $text;
 $this->phone = $phone;
 }
/**
 * Execute the job.
 *
 * @return void
 */
 public function handle()
 {
Mail::raw($this->text, function ($message){
 $message->from(env('MAIL_USERNAME','john.smith@email.com'));
 $message->to($this->phone);
 //var_dump($this->phone); exit();
 });
 }
 }

Notice it’s the code from the TodoCreatedListener with a minor changes. Now you can go to that class and change the code to this:

<? php namespace AppListeners;
use Mail;
use AppEventsTodoCreatedEvent;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchesJobs;
use AppJobsSendText;
 class TodoCreatedListener implements ShouldQueue {
use DispatchesJobs;
/** * Create the event listener.
* * @return void */
public function __construct() { // }
/** * Handle the event.
* * @param TodoCreatedEvent $event
* @return void */
public function handle(TodoCreatedEvent $event) {
//set todo
$text = $event->todo->content;
$job = (new SendText($text,$event->phone))->delay($event->timer);
$this->dispatch($job);
}
 }

Notice the delay($event->timer)? That allows us to programmatically delay the job until the user’s desired time. Head over to the TodoController class and modify the store method to look like this:


/**
 * Store a newly created resource in storage.
 *
 * @param IlluminateHttpRequest $request
 * @return IlluminateHttpResponse
 */
 public function store(Request $request)
 {
 //create Todo Model and
 $todo = new Todo;
 if ($request->session()->has('user')) {
 $user = $request->session()->get('user');
 //var_dump($user); exit();
 $todo->facebook_id = $user[0]['id'];
 //var_dump($todo->facebook_id);exit();
 }
 $todo->content = $request->content;
 $todo->save();
 //var_dump($todo);exit();
 //launch event
$phone = $request->phone . $request->gateway;
 //dd($phone);
 $timer = $request->timer;
 event(new TodoCreatedEvent($todo,$phone,$timer));
 //(new SendText($todo->content,$phone))->delay(30);
 return redirect('/');
 }

That takes care of the backend, don’t forget to run a queue listener to handle the jobs. Now head over to the welcome view and in the forms add these fields (or whatever times you want):
Now
1 Minute
5 minutes
10 minutes
15 Minutes
30 Minutes
1 Hour
12 Hours
24 Hours
To see the live version of the Laravel click here, and don’t forget to check the Github.