Web push notification example with PHP backend - notifications

I am looking for an example for web push notification with JS code and PHP backend. Can anyone share example code or a tutorial?

Here's a basic example that uses web-push-php : https://github.com/Minishlink/web-push-php-example
Main PHP code is:
<?php
require __DIR__ . '/vendor/autoload.php';
use Minishlink\WebPush\WebPush;
$auth = array(
'VAPID' => array(
'subject' => 'https://github.com/Minishlink/web-push-php-example/',
'publicKey' => 'BCmti7ScwxxVAlB7WAyxoOXtV7J8vVCXwEDIFXjKvD-ma-yJx_eHJLdADyyzzTKRGb395bSAtxlh4wuDycO3Ih4',
'privateKey' => 'HJweeF64L35gw5YLECa-K7hwp3LLfcKtpdRNK8C_fPQ', // in the real world, this would be in a secret file
),
);
$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
$subscription['endpoint'],
"Hello!", // payload
$subscription['key'],
$subscription['token'],
true // flush
);
// handle eventual errors here, and remove the subscription from your server if it is expired
Hope this helps :)

Related

"Attempt to read property \"id\" on null", Create access token error with laravel passport, laravel 9, php 8.2.2

devs,
so I have been struggling with this problem for about 10 hours now, and I can't seem to find a solution online, worst is that I don't even know why it happens.
I am working on a project which uses PHP LARAVEL as the backend and I started writing the API for the flutter frontend to consume then I ran into this error while trying to test the API endpoint for registering and logging in.
The problem is the process fails with this error when I try to generate or create a token for the registered user or logged-in user.
Here a snapshot of my register function
public function store(Request $request)
{
$validated = Validator::make($request->all(),[
"email" => "required|email",
"password" => 'required',
"first_name"=> "required",
"last_name" => "required",
"phone_number" => 'required',
]);
if ($validated->fails()) {
return response()->json(['errors' => "Invalide credentials"], 403);
}
$user = User::create(
// [
// 'first_name' => $request->first_name,
// 'last_name'=> $request->last_name,
// 'email' => $request->email,
// 'password' => bcrypt($request->password),
// 'phone_number' => $request->phone_number,
// ]
$request->toArray()
);
Auth::guard('api')->check($user);
// $newUser = User::find($user->id);
$token = $user->createToken('authToken')->accessToken;
// return $token;
return response(['token' => $token, 'first_name'=>$user->first_name, 'email'=>$user->email ], 200);
}
The login and register functions all look the same at this point.
Error-causing code is :
$token = $user->createToken('authToken')->accessToken;
Please I am open to your suggestions, thanks.
I finally found a solution for this error and I believe it will help anyone out there with a similar problem.
The problem originates from the fact that your application is unable to asign a unique id to your client, remember your website or mobile app is a client to the backend with also(your mobile app or website) might have other users, so laravel passport will need to identify it with a unique id, below are some of the steps i used to fix this error.
First it originates because during the passport installation, i forgot to install
Blockquote
--uuids
If you have a similar error, follow the steps below to fix:
NOTE: You must have laravel passport installed already, if not, them follow the complete installtion guide Here
Step 1:
Install passport uuids
php artisan passport:install --uuids
Your result will look something like
After creating, the uuid for your application, you will have to include it in your .env file as such:
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=986eb40c-0458-4b6e-bead-ea2fc4987033
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=VXLdTpqWK9i3CBqFwZgje5fuerQ5Uf2lvwXJqBoP
And there you go, you can now try to do what you couldn't do before.

Bigcommerce API start

first of all, sorry for this silly question
but I am new to use big commerce API and I searched and found many threads but not works for me .
the composer created a directory vendor
then its root I have to create a file index.php and put this code but it's showing me the blank page
<?php
require 'vendor/autoload.php';
use Bigcommerce\Api\Client as Bigcommerce;
Bigcommerce::configure(array(
'store_url' => 'https://store-xxxx.mybigcommerce.com/api/v2/',
'username' => 'xxxx',
'api_key' => 'xxxx'
));
Bigcommerce::verifyPeer(false);
$ping = Bigcommerce::getTime();
if ($ping) echo $ping->format('H:i:s');
$filter = array("page" => 3, "limit" => 30);
$products = Bigcommerce::getProducts($filter);
?>
Please, someone, explain all steps with the easy understandable process ?
Sometimes it's giving
Fatal error: Class 'Bigcommerce_Api' not found in C:\xampp\htdocs\bigcommerceapi\index.php on line 30
I followed this community
https://c9.io/oschino/bigcommerce-api-php-oauth
when I clicking the single file link it's showing 404 not found where from I can download big commerce.php file
Also, I want to know if composer created a whole PHP API then is it it is necessary to download big commerce PHP API from Github ?
I have checked the folder structure and files are same in vendor folder and big commerce git hub files.
Please help
I got solution the bigcoomerce store URL call process is now changed
I changed
Bigcommerce::configure(array(
'store_url' => 'https://store-xxxx.mybigcommerce.com/api/v2/',
'username' => 'xxxx',
'api_key' => 'xxxx'
));
to like this
Bigcommerce::configure(array(
'store_url' => 'https://store-xxxx.mybigcommerce.com',
'username' => 'xxxx',
'api_key' => 'xxxx'
));

Github api with PHP

Im new in php and im trying to make a script who will create a new repository in github and catch a document that i have in my pc and make a commit in this new repository. This script will be executed in cmd. I search for github api and I have downloaded any folders with several files, i installed some things with a composer, but i cant create a new instance of github in my php.
I don't know anything about this, I spend two days in this and i cant write a function to talk with github. In the site of github developer I dont understand anything, I really need to do this, and im very lost. Im using PhpStorm 6.0.3.
What i cant understand:
1- The api is a folder with a lot of files? Or is a library who is imported in the phpstorm? How i put this in the phpstorm for i can get the methods and create my functions?
2- Where i get the methods for talk with the github api? Where i can see them? In github developer i dont understand nothing.
I see a question similar, but dont help me much.
Please help me
EDIT
I downloaded an api, and i use the composer require, apparently everything is fine, but when i execute some file to test the api, the same error pops up. The program cant find some files that is in the project, in the same folder.
Ex: PHP Fatal error: Interface 'Github\Api\ApiInterface' not found in D:\php-github-api-master\lib\Github\Api\AbstractApi.php on line 15
In anothers files the same error appears, i put "use" referecing the files that im trying to use, but dont work. Ex: use Github\Api\ApiInterface;
EDIT
This code will create a new repository right? When i execute this code I get the error above, Class 'Github\Api\AbstractApi' not found, but the class is in there.
class Repo extends AbstractApi
{
public function create(
$name,
$description = '',
$homepage = '',
$public = true,
$organization = null,
$hasIssues = false,
$hasWiki = false,
$hasDownloads = false,
$teamId = null,
$autoInit = false
) {
$path = null !== $organization ? 'orgs/'.$organization.'/repos' : 'user/repos';
$parameters = array(
'name' => $name,
'description' => $description,
'homepage' => $homepage,
'private' => !$public,
'has_issues' => $hasIssues,
'has_wiki' => $hasWiki,
'has_downloads' => $hasDownloads,
'auto_init' => $autoInit
);
if ($organization && $teamId) {
$parameters['team_id'] = $teamId;
}
return $this->post($path, $parameters);
}
}
Thanks,
Johann.
I finish my script, everything was done correct, sorry for my obviosly questions and thanks for who was answer me. My code:
<?php
include "vendor/autoload.php";
$client = new \Github\Client();
$username = "JohannLucas";
$password = "mypassword";
$method = Github\Client::AUTH_HTTP_PASSWORD;
//authenticate
$client->authenticate($username, $password, $method);
//Apagar Repositório
//$client->api('repo')->remove('JohannLucas', 'teste');
//Criar Repositório
$client->api('repo')->create('olamundo', 'Repositorio criado com o github api', 'http://my-repo-homepage.org', true);
//Commit
$committer = array('name' => 'JohannLucas', 'email' => 'johann.lucas#hotmail.com');
$path = "teste.txt";
$commitMessage = "Commit do teste.txt";
$content = "Olá Mundo!";
$branch = "master";
$repo = "olamundo";
$fileInfo = $client->api('repo')->contents()->create('JohannLucas', 'olamundo', $path, $content, $commitMessage, $branch, $committer);
print_r("Foi!");
Thanks!
Johann

Blocking access via HTTP Authentication with Zend Framework 2

I'm trying to implement HTTP-based authentication through a Zend\Authentication\Adapter\Http as explained in the ZF2 documentation about the HTTP Authentication Adapter.
I want to block every incoming request until the user agent is authenticated, however I'm unsure about how to implement this in my module.
How would I setup my Zend\Mvc application to deny access to my controllers?
What you are looking for is probably a listener attached to the Zend\Mvc\MvcEvent::EVENT_DISPATCH event of your application.
In order, here's what you have to do to block access to any action through an authentication adapter. First of all, define a factory that is responsible for producing your authentication adapter:
namespace MyApp\ServiceFactory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Authentication\Adapter\Http as HttpAdapter;
use Zend\Authentication\Adapter\Http\FileResolver;
class AuthenticationAdapterFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$authConfig = $config['my_app']['auth_adapter'];
$authAdapter = new HttpAdapter($authConfig['config']);
$basicResolver = new FileResolver();
$digestResolver = new FileResolver();
$basicResolver->setFile($authConfig['basic_passwd_file']);
$digestResolver->setFile($authConfig['digest_passwd_file']);
$adapter->setBasicResolver($basicResolver);
$adapter->setDigestResolver($digestResolver);
return $adapter;
}
}
This factory will basically give you a configured auth adapter, and abstract its instantiation logic away.
Let's move on and attach a listener to our application's dispatch event so that we can block any request with invalid authentication headers:
namespace MyApp;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\EventManager\EventInterface;
use Zend\Mvc\MvcEvent;
use Zend\Http\Request as HttpRequest;
use Zend\Http\Response as HttpResponse;
class MyModule implements ConfigProviderInterface, BootstrapListenerInterface
{
public function getConfig()
{
// moved out for readability on SO, since config is pretty short anyway
return require __DIR__ . '/config/module.config.php';
}
public function onBootstrap(EventInterface $event)
{
/* #var $application \Zend\Mvc\ApplicationInterface */
$application = $event->getTarget();
$serviceManager = $application->getServiceManager();
// delaying instantiation of everything to the latest possible moment
$application
->getEventManager()
->attach(function (MvcEvent $event) use ($serviceManager) {
$request = $event->getRequest();
$response = $event->getResponse();
if ( ! (
$request instanceof HttpRequest
&& $response instanceof HttpResponse
)) {
return; // we're not in HTTP context - CLI application?
}
/* #var $authAdapter \Zend\Authentication\Adapter\Http */
$authAdapter = $serviceManager->get('MyApp\AuthenticationAdapter');
$authAdapter->setRequest($request);
$authAdapter->setResponse($response);
$result = $adapter->authenticate();
if ($result->isValid()) {
return; // everything OK
}
$response->setBody('Access denied');
$response->setStatusCode(HttpResponse::STATUS_CODE_401);
$event->setResult($response); // short-circuit to application end
return false; // stop event propagation
}, MvcEvent::EVENT_DISPATCH);
}
}
And then the module default configuration, which in this case was moved to MyModule/config/module.config.php:
return array(
'my_app' => array(
'auth_adapter' => array(
'config' => array(
'accept_schemes' => 'basic digest',
'realm' => 'MyApp Site',
'digest_domains' => '/my_app /my_site',
'nonce_timeout' => 3600,
),
'basic_passwd_file' => __DIR__ . '/dummy/basic.txt',
'digest_passwd_file' => __DIR__ . '/dummy/digest.txt',
),
),
'service_manager' => array(
'factories' => array(
'MyApp\AuthenticationAdapter'
=> 'MyApp\ServiceFactory\AuthenticationAdapterFactory',
),
),
);
This is the essence of how you can get it done.
Obviously, you need to place something like an my_app.auth.local.php file in your config/autoload/ directory, with the settings specific to your current environment (please note that this file should NOT be committed to your SCM):
<?php
return array(
'my_app' => array(
'auth_adapter' => array(
'basic_passwd_file' => __DIR__ . '/real/basic_passwd.txt',
'digest_passwd_file' => __DIR__ . '/real/digest_passwd.txt',
),
),
);
Eventually, if you also want to have better testable code, you may want to move the listener defined as a closure to an own class implementing the Zend\EventManager\ListenerAggregateInterface.
You can achieve the same results by using ZfcUser backed by a Zend\Authentication\Adapter\Http, combined with BjyAuthorize, which handles the listener logic on unauthorized actions.
Answer of #ocramius is accept answer But you forget to describe How to write two files basic_password.txt and digest_passwd.txt
According to Zend 2 Official Doc about Basic Http Authentication:
basic_passwd.txt file contains username, realm(the same realm into your configuration) and plain password -> <username>:<realm>:<credentials>\n
digest_passwd.txt file contains username, realm(the same realm into your configuration) and password hashing Using MD5 hash -> <username>:<realm>:<credentials hashed>\n
Example:
if basic_passwd.txt file:
user:MyApp Site:password\n
Then digest_passwd.txt file:
user:MyApp Site:5f4dcc3b5aa765d61d8327deb882cf99\n
Alternatively you can use Apache Resolver for HTTP Adapter
use Zend\Authentication\Adapter\Http\ApacheResolver;
$path = 'data/htpasswd';
// Inject at instantiation:
$resolver = new ApacheResolver($path);
// Or afterwards:
$resolver = new ApacheResolver();
$resolver->setFile($path);
According to https://zendframework.github.io/zend-authentication/adapter/http/#resolvers

CapsuleCRM API ColdFusion Wrapper

Looking for a ColdFusion version of the following PHP API wrapper for CapsuleCRM:
<?php
// The data you want to send to Capsule CRM in xml format
// SEE http://capsulecrm.com/help/page/javelin_api_party
I'm understanding that this variable contains the XML string...
$myxml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
<person>\n
<title>Mr</title>\n
<firstName>Test12</firstName>\n
<lastName>Tester12</lastName>\n
<jobTitle>Chairman</jobTitle>\n
<organisationName>Big Company</organisationName>\n
<about>Testing</about>\n
</person>";
// The URL to connect with (note the /api/ that's needed and note it's person rather than party)
// SEE: http://capsulecrm.com/help/page/api_gettingstarted/
$capsulepage = 'https://sample.capsulecrm.com/api/person';
However, I don't know how to initiate cURL in ColdFusion.
// Initialise the session and return a cURL handle to pass to other cURL functions.
$ch = curl_init($capsulepage);
What does the 'curl_setopt_array' function do exactly? Is there a CF equivalent?
// set appropriate options NB these are the minimum necessary to achieve a post with a useful response
// ...can and should add more in a real application such as
// timeout CURLOPT_CONNECTTIMEOUT
// and useragent CURLOPT_USERAGENT
// replace 1234567890123456789 with your own API token from your user preferences page
$options = array(CURLOPT_USERPWD => '1234567890123456789:x',
CURLOPT_HTTPHEADER => array('Content-Type: text/xml'),
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $myxml
);
curl_setopt_array($ch, $options);
// Do the POST and collect the response for future printing etc then close the session
$response = curl_exec($ch);
$responseInfo = curl_getinfo($ch);
curl_close($ch);
?>
I could be wrong, but that looks like a basic http post. The equivalent in CF is cfhttp. To pass parameters/headers (ie curl_setopt_array) use cfhttpparam.