PHP: how to send push notifications to Apple device - php

Our iOS app should receive push notification. Following this tutorial I implemented these methods in application delegate:
didRegisterForRemoteNotificationsWithDeviceToken
and
didFailToRegisterForRemoteNotificationsWithError
which are called by didFinishLaunchingWithOptions and it seems that the device is correctly registered in our MySQL service. Moreover, I have just created a pem sandbox certification that I will use for testing. Now, I need to know what I should do at the backend in PHP. Which code is required? We are using Zend framework so I should implement function preparetosend_apple()in my mapper and sendtoappleAction() in our controller but I don't know where to start from and how to test it. Thank you!

First thing is sending push notification directly from application is not a good idea as this call can be blocking one (means the rest of the codeblock will wait for its completion). So I suggest using background processor/message queuing services (like gearman, zero mq, etc.).
Secondly easiest solution will be using Parse like services. Parse allows registering the app using the certificates you mentioned and has SDK for php (composer based).
In the background service you just call the API from SDK. Like:
use Parse\ParseClient;
use Parse\ParseInstallation;
use Parse\ParsePush;
ParseClient::initialize($appId, $restKey, $masterKey, $curlDebug);
...
...
...
Using channel in parse
$response = ParsePush::send(array(
"channels" => ["channel-$userId"],
"data" => $data,
));
OR using custom query
$query = ParseInstallation::query();
$query->equalTo('userId', "user-$userId");
$response = ParsePush::send(array(
"where" => $query,
"data" => $data,
));
The best part of using parse - I will say using other interesting features like -- broadcast messages, device listings, etc.
Hope this may help you.

Related

ZF2 Soap Request - Send parameters

I am trying to send a SOAP request to a client's API endpoint. I am not at all familiar with SOAP, so having quite a difficult time getting this to work.
From the client's documentation
The requested ticket can be used to call all the API web methods subsequently.
public string RequestTicket(
string username,
string password
);
URL
https://www.clientsurl.net/api/v01_00/APIService.asmx?wsdl
Parameters
string username
string password
I am able to create the WSDL
$client = new Client('https://www.clientsurl.ca/api/v01_00/APIService.asmx?wsdl', ['soap_version' => SOAP_1_1]);
but not sure how to send the parameters through
$params = [
'username' => 'myusername'
'password' => 'mypassword'
];
I am also not sure what the relevance of RequestTicket is. Am I supposed to add it to the url?
The answer is probably very simple, but after tons of searching I couldn't find anything. Please help.
I have write a method to send a request
protected function soapRequest(string $method, array $arguments)
{
try {
$client = new \Zend\Soap\Client($this->getWsdl(),
[
'soap_version' => SOAP_1_1,
'cache_wsdl' => WSDL_CACHE_NONE
]);
$result = $client->{$method}($arguments);
return $result->return;
} catch (\SoapFault $s) {
...
} catch (\Exception $e) {
...
}
}
You must have a Soap method to send yours parameters.
If you don't know the method name, I advise you to run SoapUI application, very useful for debugging soap requests.
A SOAP service has a set of operations that you can call over the network. These operations can also have parameters. Basically, it's just like calling a method with parameters in code just that the invocation happens over the network with the method name and parameters being marshaled into an XML that respects the rules of the SOAP protocol.
To call the SOAP service, you can either make a HTTP request of type POST to the service's endpoint (i.e. https://www.clientsurl.ca/api/v01_00/APIService.asmx) or you can use a SOAP client. A SOAP client is some code that you can generate from the WSDL of the SOAP web service, or is some code that can dynamically read the WSDL and provide you some ways to invoke the operations described there. As opposed to making a POST HTTP request, the client takes care of these details for you and allows you to make the call over the network just like you call a local method in your code.
To call an operation of the SOAP service in your client code you have to invoke a method with parameters. The name of the method and its parameters (what names and what types) are described by the WSDL of the service.
With that being said, I'll add some details about what you posted in your question.
The requested ticket can be used to call all the API web methods subsequently.
Some service operations can require authentication in order to be be allowed to invoke them. Just like you need a username and password to access protected sections of a website for example. For a SOAP web service, his can happen in a few ways, the most common two being:
you send the username and password with each call to the web service (somehow; can be as SOAP headers, as HTTP headers with BASIC Authentication, etc).
the service exposes a method that you have to call with username and password just like point 1), but then returns an access token of some sort that you then need to provide to the rest of the web service's operations. This is just like a Login page on a website where you authenticate with username and password and then you get back a SessionID that you can use on all other requests until you decide to log out.
It seems that your service uses the second approach, and RequestTicket seems to be the operation that you need to call in order to be able to call the rest of the operations after that.
I am able to create the WSDL
You do not create the WSDL, the WSDL already exists for the web service. Also make sure you do not make a confusion between the SOAP web service and its WSDL. The code you show just creates a SOAP client from the WSDL (what I described above) to allow you to invoke operations on it.
I am also not sure what the relevance of RequestTicket is. Am I supposed to add it to the url?
Most likely RequestTicket is an operation of the web service. You should look inside the WSDL to see if it's described there. The WSDL is a little tough to swallow if you are not familiar with how it works, so your best bet is to use a tool like SoapUI to feed it the web service WSDL and have SoapUI generate sample requests for the web service. You can then also use SoapUI to test the web service to make sure you understand how it works before you try to replicate the same calls with your PHP code.

How to send data from laravel to a redis queue implemented using Bull queue

I have implemented Bull queue in nestjs project but want producer to be a laravel project.
I use following command to produce
Redis::command('zadd', ['bull:test:delayed', 1, $data]);
and at consumer use
#Processor('test')
export class ConsumerProcessor {
#Process({concurrency:13})
handle(j: Job<unknown>) {
this.logger.log(j.id);
}
}
The $data added at producer is accessible via job.id, how can I access it using job.data and have a unique id? What changes needs to be done at producer side?
Below code works:
A="some unique identifier";
Redis::command("hmset",['bull:<queuename>:<A>', "data" , json_encode($data)]);
Redis::command('zadd', ['bull:<queuename>:delayed', 1, A]);
I used https://github.com/HackThisSite/PHP-Bull-Scheduler to add jobs (works only with Predis)
Also tried https://github.com/ilzrv/php-bull-queue today to get phpredis support (requires php7.4+)

Laravel 7 - Use REST API instead of a database

I am using a rest api to store/retrieve my data which is stored in a postgres database. The api is not laravel, its an external service!
Now i want to create a website with laravel (framework version 7.3.0) and i'm stuck on how to implement the api calls correctly.
For example: i want to have a custom user provider with which users can log-in on the website. But the validation of the provided credentials is done by the api not by laravel.
How do i do that?
Just make a Registration controller and a Login Controller by "php artisan make:controller ControllerName" and write Authentication logics there.
In previous versions of Laravel you had a command like "php artisan make:auth" that will make everything needed to do these operations. But in Laravel 7.0 you need to install a package called laravel/ui.
Run "composer required laravel/ui" to install that package
Then run "php artisan ui bootstrap --auth"
and now, you are able to run "php artisan make:auth"
This command will make whole Registration (Signup) and Login system for you.
and in orer to work with REST, you may need to know REST (Http) verbs. Learn about GET, POST, PUT, PATH, DELETE requests and how to make those request with PHP and Laravel collection methods. Learn about JSON parsing, encoding, and decoding. Then you can work with REST easily. and work without any template codes from other packages.
Thank you so much. I hope this answer give you some new information/thought. Thanks again.
Edit:
This might not be the best way. But this is what I did at that time. I tried curl and guzzle to build the request with session cookie and everything in the header to make it look like a request from a web browser. Couldn't make it work.
I used the web socket's channel id for the browser I want the changes to happen and concatenated it with the other things, then encrypted it with encrypt($string). After that, I used the encrypted string to generate a QR code.
Mobile app (which was already logged in as an authenticated used) scanned it and made a post request with that QR string and other data. Passport took care of the authentication part of this request. After decrypting the QR string I had the web socket's channel id.
Then I broadcasted in that channel with proper event and data. Caught that broadcast in the browser and reloaded that page with JavaScript.
/*... processing other data ...*/
$broadcastService = new BroadcastService();
$broadcastService->trigger($channelId, $eventName, encrypt($$data));
/*... returned response to the mobile app...*/
My BroadcastService :
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Pusher\Pusher;
use Pusher\PusherException;
class BroadcastService {
public $broadcast = null;
public function __construct() {
$config = config('broadcasting.connections.pusher');
try {
$this->broadcast = new Pusher($config['key'], $config['secret'], $config['app_id'], $config['options']);
} catch (PusherException $e) {
Log::info($e->getMessage());
}
}
public function trigger($channel, $event, $data) {
$this->broadcast->trigger($channel, $event, $data);
}
}
In my view :
<script src="{{asset('assets/js/pusher.js')}}"></script>
<script src="{{asset('assets/js/app.js')}}" ></script>
<script>
<?php
use Illuminate\Support\Facades\Cookie;
$channel = 'Channel id';
?>
Echo.channel('{{$channel}}')
.listen('.myEvent' , data => {
// processing data
window.location.reload();
});
</script>
I used Laravel Echo for this.
Again this is not the best way to do it. This is something that just worked for me for that particular feature.
There may be a lot of better ways to do it. If someone knows a better approach, please let me know.
As of my understanding, you are want to implement user creation and authentication over REST. And then retrieve data from the database. Correct me if I'm wrong.
And I'm guessing you already know how to communicate over API using token. You are just stuck with how to implement it with laravel.
You can use Laravel Passport for the authentication part. It has really good documentation.
Also, make use of this medium article. It will help you to go over the step by step process.

How to use OVH Api with Laravel

I'm working on an application that sends SMS to the customers we got.
I'm currently looking the doc (https://docs.ovh.com/fr/sms/envoyer_des_sms_avec_lapi_ovh_en_php/) => it's in french.
They're using a PHP Wrapper, but I really don't know how I can integrate the API to my Laravel Project.
Does someone know how it's working ?
First of all, install the package
composer require ovh/php-ovh-sms
Then, on the controller, you can use the API easily as stated in the documentation.
use \Ovh\Sms\SmsApi;
// Informations about your application
// You may set them to 'NULL' if you are using
// a configuraton file
$applicationKey = "your_app_key";
$applicationSecret = "your_app_secret";
$consumerKey = "your_consumer_key";
$endpoint = 'ovh-eu';
// Init SmsApi object
$Sms = new SmsApi( $applicationKey, $applicationSecret, $endpoint, $consumerKey );
// Get available SMS accounts
$accounts = $Sms->getAccounts();
dd($accounts);
There is a Laravel notification channel specifically for this provider, this will make the whole process much easier, it will allow you to use Laravel's built in notifications functionality without having to write provider specific code.
http://laravel-notification-channels.com/ovh-sms/

Creating a web service in PHP

I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc. Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq
I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
$rest = new RestServer(Hello);
$rest->handle();
Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World
(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.
I would suggest you go for Yii it is worth of learning. You can easily establish it in this.
Web Service. Yii provides CWebService and CWebServiceAction to simplify the work of implementing Web service in a Web application. Web service relies on SOAP as its foundation layer of the communication protocol stack.
Easiest way in PHP is to use GET/POST as data-in and echo as data-out.
Here's a sample:
<?php if(empty($_GET['method'])) die('no method specified');
switch($_GET['method']){
case 'add': {
if(empty($_GET['a']) || empty($_GET['b'])) die("Please provide two numbers. ");
if(!is_numeric($_GET['a']) || !is_numeric($_GET['b'])) die("Those aren't numbers, please provide numbers. ");
die(''.($_GET['a']+$_GET['b']));
break;
}
}
Save this as test.php and go to http://localhost/test.php?method=add&a=2&b=3 (or wherever your webserver is) and it should say 5.
PHP does have native support for a SOAP server ( The SoapServer class manual shows it) and I've found it pretty simple to use.
Creating a REST style API is pretty easy if you use a framework. I don't want to get into a debate about which framework is better but CakePHP also supports output as XML and I'm pretty sure others will as well.
If you're coming from a Microsoft background just be careful about thinking about "datasets". They are a very specific Microsoft thing and have been a curse of mine in the past. It's probably not going to be an issue for you, but you may want to just see the differences between Microsoft and open implementations.
And of course PHP has a native json_encode() function.
You can check out this nice RESTful server written for Codeigniter, RESTful server.
It does support XML, JSON, etc. responses, so I think this is your library.
There is even a nice tutorial for this on the Tutsplus network -
Working with RESTful Services in CodeIgniter
You can also try PHP REST Data Services https://github.com/chaturadilan/PHP-Data-Services
You can use any existing PHP framework like CodeIgniter or Symfony or CakePHP to build the webservices.
You can also use plain PHP like disscussed in this example

Categories