Laravel Firebase Data Sync Fail - php

Integrating Firebase in "RESTFUL API" for the first time. The data had to sync into two databases i.e. MySQL and Firebase but the data didn't sync in Firebase.
Installation of firebase sync trait
composer require mpociot/laravel-firebase-sync
The configuration code to integrate Firebase into my API :-
'firebase' => [
'api_key' => 'AIzaSyCbOasfdsfdsfds',
'auth_domain' => 'restasdsaful-asdfs.firebaseapp.com',
'projectId' => 'restful-23aasdfsf60',
'messagingSenderId' => '8445794551330',
'database_url' => 'https://restful-sdfsdf23a60.firebaseio.com',
'secret' => 'mZ93YRkZ9ZErQvvtJyFKmRopsdfcwUEE5ImoMW89hWB',
'storage_bucket' => 'restfulas-23a60asda.appspot.com',
],
Note: for security reason I have changed values of configuration attributes.
Path where Firebase had been configured. config/services.php
The process that I applied for Syncronizing the Model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mpociot\Firebase\SyncsWithFirebase;
class Demo extends Model
{
use SyncsWithFirebase;
protected $fillable = ['task','is_done'];
protected $visible = ['id', 'task', 'is_done'];
}
Please suggest a solution if there's any error in my code or any alternatives for this kind of problem. Thanks in Advance!!.

You can do like this:
use Firebase\Firebase;
class FirebaseController extends Controller
{
public function storeTask(Request $request){
$FIREBASE_URL = 'your_url_key;
$FIREBASE_SECRET = 'your_firebase_secret_key';
$fb = Firebase::initialize($FIREBASE_URL, $FIREBASE_SECRET);
$fb = new Firebase([ 'base_url' => $FIREBASE_URL, 'token' => $FIREBASE_SECRET,]);
$nodeSetContent = $fb->push('msg', $request->all());
return response()->json(['data'=>$nodeSetContent]);
}
}
you can take reference from this link (https://github.com/eelkevdbos/firebase-php)

Related

Laravel 6 - Pass a parameter to $app->when()->needs()->give()

I am trying to use this package to push notifications to users via OneSignal. However I needed to make a little change. My API serves two (related) apps and I have two OneSignal configs. I am trying to override its ServiceProvider (using this technique).
The ServiceProvider presents itself as follows
<?php
namespace NotificationChannels\OneSignal;
use Berkayk\OneSignal\OneSignalClient;
use Illuminate\Support\ServiceProvider;
use NotificationChannels\OneSignal\Exceptions\InvalidConfiguration;
class OneSignalServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
$this->app->when(OneSignalChannel::class)
->needs(OneSignalClient::class)
->give(function () {
$oneSignalConfig = config('services.onesignal');
if (is_null($oneSignalConfig)) {
throw InvalidConfiguration::configurationNotSet();
}
return new OneSignalClient(
$oneSignalConfig['app_id'],
$oneSignalConfig['rest_api_key'],
''
);
});
}
}
The behavior that I want to change is located in the line
$oneSignalConfig = config('services.onesignal');
As it assumes that my config/services.php has the following entry (stated in the doc) :
// config/services.php
...
'onesignal' => [
'app_id' => env('ONESIGNAL_APP_ID'),
'rest_api_key' => env('ONESIGNAL_REST_API_KEY')
],
...
Whereas I want to set my config/services.php as follows
// config/services.php
...
'onesignal' => [
'app1' => [
'app_id' => env('ONESIGNAL_1_APP_ID'),
'rest_api_key' => env('ONESIGNAL_1_REST_API_KEY')
],
'app2' => [
'app_id' => env('ONESIGNAL_2_APP_ID'),
'rest_api_key' => env('ONESIGNAL_2_REST_API_KEY')
],
],
...
And I want somehow to tell my ServiceProvider (through some kind of parameter) to either do
$oneSignalConfig = config('services.onesignal.app1');
OR
$oneSignalConfig = config('services.onesignal.app2');
But I didn't find any way to pass a parameter to the class, the boot function or the give method (and if I understood well I shouldn't even be doing that).
The only way I could think of is to create two classes that extend the OneSignalChannel::class
and duplicate code in the boot function so it becomes as follows :
public function boot()
{
$this->app->when(FirstOneSignalChannel::class)
->needs(OneSignalClient::class)
->give(function () {
$oneSignalConfig = config('services.onesignal.app1');
if (is_null($oneSignalConfig)) {
throw InvalidConfiguration::configurationNotSet();
}
return new OneSignalClient(
$oneSignalConfig['app_id'],
$oneSignalConfig['rest_api_key'],
''
);
});
$this->app->when(SecondOneSignalChannel::class)
->needs(OneSignalClient::class)
->give(function () {
$oneSignalConfig = config('services.onesignal.app2');
if (is_null($oneSignalConfig)) {
throw InvalidConfiguration::configurationNotSet();
}
return new OneSignalClient(
$oneSignalConfig['app_id'],
$oneSignalConfig['rest_api_key'],
''
);
});
}
The difference in the when provoking a difference in the config but it seems a lot of duplication and not extensible (what if I had three apps).
Should I use this method, or is there a way to pass a parameter to this ServiceProvider or is there another solution ?
https://stackoverflow.com/a/34224082/10371024
I could see what you need, but to pass parameter to boot method is not a good idea according to Laravel architecture. You may try to get what you want with using events as Vladislav suggested.

Laravel notification won't send

I try to send notification to Twitter when new post created but I'm getting:
Couldn't post Notification. Response: Bad Authentication data.
Codes
Notification class
use NotificationChannels\Twitter\TwitterChannel;
use NotificationChannels\Twitter\TwitterStatusUpdate;
use App\Post;
class PostPublished extends Notification
{
use Queueable;
public function via($notifiable)
{
return [TwitterChannel::class, TelegramChannel::class];
}
public function toTwitter($post)
{
$title = $post->title;
$slug = $post->slug;
$image = $post->image;
return new TwitterStatusUpdate($title .' https://domain.co/blog/'. $slug, [$image]);
}
Post controller
use Illuminate\Notifications\Notifiable;
use App\Notifications\PostPublished;
$post->save();
$post->notify(new \App\Notifications\PostPublished($post));
Post model
use Illuminate\Notifications\Notifiable;
use Notifiable;
Question
Why I'm getting this error?
How to fix it?
It is definitely something wrong with your configuration or your tokens. It looks to me as if something is not set up properly. In your config/services.php file do you have the following?
'twitter' => [
'consumer_key' => env('TWITTER_CONSUMER_KEY'),
'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
'access_token' => env('TWITTER_ACCESS_TOKEN'),
'access_secret' => env('TWITTER_ACCESS_SECRET')
]
Please check to ensure all of these are set correctly using tinker. In the terminal type php artisan tinker and then check each of the following one line at a time:
env('TWITTER_CONSUMER_KEY'),
env('TWITTER_CONSUMER_SECRET'),
env('TWITTER_ACCESS_TOKEN'),
env('TWITTER_ACCESS_SECRET')
SOLVED
All I needed to do was :
php artisan config:cach
composer dump-autoload
now it's working like charm.
Note it can be type error in any part of .env file, not only twitter access tokens and key, for example:
APP_NAME=Name of your App
instead of:
APP_NAME="Name of your App"

Elastic search configurations not working in laravel v5.3

I have setup new laravel v5.3 project and install elastic search driver to implement elastic search via composer. But when I reload my page then I always receive This page isn’t working even the elastic search is running on my system below is my complete code that I code.
composer.json
"require": {
"php": ">=5.6.4",
"elasticsearch/elasticsearch": "^6.0",
"laravel/framework": "5.3.*"
},
web.php
Route::get('/',array('uses' => 'ElasticSearch#addPeopleList'));
Controller
<?php
namespace App\Http\Controllers;
class ElasticSearch extends Controller
{
// elastic
protected $elastic;
//elastic cliend
protected $client;
public function __construct(Client $client)
{
$this->client = ClientBuilder::create()->build();
$config = [
'host' =>'localhost',
'port' =>9200,
'index' =>'people',
];
$this->elastic = new ElasticClient($config);
}
public function addPeopleList(){
echo "<pre>";
print_r($this->$elastic);
exit;
}
}
But when I refresh the page then This page isn’t working i received this message and page not loaded one thing that I want to let you know that I made no changes in app.php file of configuration. Please eduacate to solve this issue.
if You want to instantiate an elastic client with some configuration, You should use method ClientBuilder::fromConfig(array $config).
In your case it should be
<?php
$client = ClientBuilder::fromConfig([
'hosts' => [ 'localhost:9200' ]
]);
As You can notice above hosts must be provided as array.
Also I'm not sure that Elasticsearch client that You use have ElasticClient class.
Also if You provided actual code from your controller than it contains an error. You should call class properties like that: print_r($this->client) (without $ near the property name).
Finaly your controller should looks like this:
<?php
namespace App\Http\Controllers;
use Elasticsearch\ClientBuilder;
class ElasticSearch extends Controller
{
/**
* #var \Elasticsearch\Client
*/
protected $client;
public function __construct()
{
$this->client = ClientBuilder::fromConfig([
'hosts' => [
'localhost:9200',
],
]);
}
public function addPeopleList(){
echo "<pre>";
print_r($this->client);
exit;
}
}
And to add a document to the index You need to call this command according to the official documentation
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);
Official documentation can be found here https://github.com/elastic/elasticsearch-php
P.S. Sorry for my English. It is far from perfect.

Lumen 5.5 Socialite Providers doesn't works with setConfig()

I use Laravel Socialite Providers (https://socialiteproviders.github.io/) to login user on Lumen 5.5 API.
setConfig() method, to force config, doesn't works for me...
Here below, my error and my code. The problem is that I do not know why I have this error.
Display Error:
Type error: Argument 1 passed to
Laravel\Socialite\SocialiteManager::formatConfig() must be of the type
array, null given, called in
/home/vagrant/www/project1/api.website.app/vendor/laravel/socialite/src/SocialiteManager.php
on line 125
PHP code:
$clientId = env('TWITTER_KEY');
$clientSecret = env('TWITTER_SECRET');
$redirectUrl = env('TWITTER_REDIRECT_URI');
$additionalProviderConfig = [];
$config = new SocialiteConfig($clientId, $clientSecret, $redirectUrl, $additionalProviderConfig);
return Socialite::with('twitter')->stateless()->setConfig($config)->redirect();
You need to configure services configuration first! Create a services.php file inside config folder (you may create this one if you don't have it already).
File services.php
return [
'twitter' => [
'client_id' => env('TWITTER_KEY'),
'client_secret' => env('TWITTER_SECRET'),
'redirect' => env('TWITTER_REDIRECT_URI'),
]
];
Your code should be like this:
use Laravel\Socialite\Facades\Socialite;
// You may not this one, read below explanation
app()->configure('services');
return Socialite::with('twitter')->stateless()->redirect();
It is better if you move the configure line to bootstrap/app.php file:
// Just right before register SocialiteProvider
$app->configure('services');
$app->register(SocialiteProviders\Manager\ServiceProvider::class);
If you have moved this configure, your code now should be:
use Laravel\Socialite\Facades\Socialite;
return Socialite::with('twitter')->stateless()->redirect();
PS:
If you have call to undefined stateless method, it means you don't set the listener yet, you can read here. Open your App\Providers\EventServiceProvider, add this line:
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
'SocialiteProviders\Manager\SocialiteWasCalled' => [
'SocialiteProviders\Twitter\TwitterExtendSocialite#handle',
]
];
}
And don't forget to add this line to your bootstrap/app.php file:
$app->register(App\Providers\EventServiceProvider::class);

Laravel 5 authenticate users through external API

I'd like to know is it possible to extend the built-in authentication to use an external API to authenticate a user? I'm a Laravel newbie, so I'd appreciate your help.
I'm making a custom app in Laravel 5.2 for my client, but I don't a direct access to their database server and I can only call their API to get users' details.
Thanks.
If I understood correctly you want to log users from APIs like facebook, twitter or github for example ? If that's so you need to use a laravel package named Socialite, here is the link to download and use it :
https://github.com/laravel/socialite
run on your command this :
composer require laravel/socialite
Next you need to tell laravel you want to use this package, so you need to add this in config/app.php :
'providers' => [
// Other service providers...
Laravel\Socialite\SocialiteServiceProvider::class,
],
and this is the aliases :
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
Basically, you'll need to create an app on the developers site, i'll take facebook for this example.You need to go to this site :
https://developers.facebook.com/, create an account and you'll get your app url and secret key. You'll use it on your .env and config/services files.
In your config/services file add this after stripe :
'facebook' => [
'client_id' => env('FACEBOOK_ID'),
'client_secret' => env('FACEBOOK_SECRET'),
'redirect' => env('FACEBOOK_URL'),
],
And in your .env file :
FACEBOOK_ID=*your facebook id*
FACEBOOK_SECRET=*your facebook secret*
FACEBOOK_URL=http://yourwebsite.com/callback
Next you'll need a controller to handle the auth process, create something like SocialAuthController and put this in :
public function redirect()
{
return Socialite::driver('facebook')->redirect();
}
public function callback() {
$user = $this->findOrCreateFbUser(Socialite::driver('facebook')->user());
session([
'user' => $user
]);
return redirect()->route('/');
}
public function logout() {
session()->forget('user');
return redirect()->route('home');
}
protected function findOrCreateFbUser($fbUser) {
// the data you want to get from facebook
$fbData = [
'facebook_id' => $fbUser->id,
'avatar' => $fbUser->avatar,
'username' => $fbUser->name,
'email' => $fbUser->email,
];
$user = \App\User::where('facebook_id', $fbData['facebook_id'])->first();
if(!$user) $user = \App\User::create($fbData);
$user->update([
'avatar' => $fbUser->avatar,
'username' => $fbUser->name,
'email' => $fbUser->email
]);
return $user;
}
Of course you need to add a facebook_id field in your user database and model.
In User.php :
protected $fillable = [
'facebook_id',
'username',
'email',
'avatar'
];
I know this solution isn't really dynamic as it is for only one api, i'm still pretty new at Laravel too and this is my first answer to a stackoverflowquestion, but this did the trick for me :) If I forgot something don't hesitate to tell me so i can update this answer..
I also suggest you follow Jeffrey Way's tutorial on social auth on the Laracasts website, it's very instructive and clear, i could manage it thanks to him !

Categories