Registration in Notification Hub with PHP Backend - php

For user requeriments the backend must be PHP and the app client is in Ionic 2. Based on:
https://msdn.microsoft.com/en-us/library/azure/dn223265.aspx
https://github.com/Azure/azure-notificationhubs-samples/tree/master/notificationhubs-rest-php
https://github.com/webwarejp/notificationhubs-rest-php
Create Registration Notification Hub Azure PHP Important
I created this method in php API:
$uri = $this->endpoint . $this->hubPath . "/registrations".NotificationHub::API_VERSION;
/* print($uri); */
$ch = curl_init($uri);
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '. $token,
'Content-Type: '."application/atom+xml;type=entry;charset=utf-8",
'x-ms-version: 2015-01',
'Content-Length: 0'
];
$body = $this->getXmlAndroid($registrationId, $tag);
print_r($body);
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $body
));
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
print_r(curl_error($ch));
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
print_r($info);
curl_close($ch);
The getXmlAndroid method is simple return xml format with GCM ID
private function getXmlAndroid($registrationId){
return '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<GcmRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<GcmRegistrationId>'.$registrationId.'</GcmRegistrationId>
</GcmRegistrationDescription>
</content>
</entry>';
}
I get the GcmRegistrationId with this function in Ionic 2 app.
import { Push, PushObject, PushOptions } from '#ionic-native/push';
....
const options: PushOptions = {
android: { senderID: 'MyIDFirebaseProject'},
ios: { alert: 'true', badge: true, sound: 'false'},
windows: {}
};
pushObject.on('registration').subscribe((registration: any) => {
console.log(registration.registrationId);
});
The problem is always request to Registration method in Notification API return
[http_code] => 400
Where 400 means the "Invalid request body. The registration could not be created because the request was malformed.". I don't understand why this happen.

Why you send Content-Length: 0 header? It may cause a problem.

Related

How to get emails sent from gmail API

I have a script that get incoming emails to my gmail but now i also want to get emails that i send via email.
Here is the code that i have to get incoming emails
Please let me know what i need for outgoing emails as well
At the moment this code runs via pub sub on console.google.com
$ch = curl_init('https://www.googleapis.com/gmail/v1/users/me/messages?labelIds=Label_56&maxResults=10');
curl_setopt_array($ch, array(
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '. $tokenval,
'Content-Type: application/json',
),
));
// execute request and get response
$result = curl_exec($ch);
$allmessages = json_decode($result);
$allmessage = $allmessages->messages;
for($i=0;$i<count( $allmessage);$i++)
{
//echo $allmessage[$i]->id;
$checkoldmsgid = $this->Customer_m->getCount('messages',array('massageid'=>$allmessage[$i]->id ));
if( $checkoldmsgid ==0)
{
$ch = curl_init('https://www.googleapis.com/gmail/v1/users/me/messages/'.$allmessage[$i]->id);
curl_setopt_array($ch, array(
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '. $tokenval,
'Content-Type: application/json'
),
));
// execute request and get response
$resultm = curl_exec($ch);
$msgval = json_decode($resultm);
$sendernum =explode('#',$msgval->payload->headers[19]->value);
$recivernum =explode('#',$msgval->payload->headers[0]->value);
$createdat = date('Y-m-d H:i:s',strtotime($msgval->payload->headers[18]->value));
$massage = $msgval->snippet;
$single_message = $service->users_messages->get("me", $allmessage[$i]->id);
$payload = $single_message->getPayload();
$body = $payload->getBody();
$FOUND_BODY = $this->decodeBody($body['data']);
You'll probably want to use the SENT system label (instead of the Label_56 one) in your curl_init() call:
SENT
Applied automatically to messages that are sent with drafts.send
or messages.send, inserted with messages.insert and the
user's email in the From header, or sent by the user through the
web interface.

Gmail API Not Reading Full email

Ok so i am using Pub/Sub subscrition and using Push into an endpoint URL to read email from gmail.
It works perfect for short emails but once and email is over mayber200 characters it only reads first 100 or so characters.
Here is the screen shot on my google api console
and here is the code in the receiver file
$ch = curl_init('https://www.googleapis.com/gmail/v1/users/me/messages?labelIds=Label_56&maxResults=5');
curl_setopt_array($ch, array(
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '. $tokenval,
'Content-Type: application/json',
),
));
// execute request and get response
$result = curl_exec($ch);
$allmessages = json_decode($result);
$allmessage = $allmessages->messages;
for($i=0;$i<count( $allmessage);$i++)
{
$checkoldmsgid = $this->Customer_m->getCount('messages',array('massageid'=>$allmessage[$i]->id ));
if( $checkoldmsgid ==0)
{
$ch = curl_init('https://www.googleapis.com/gmail/v1/users/me/messages/'.$allmessage[$i]->id);
curl_setopt_array($ch, array(
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '. $tokenval,
'Content-Type: application/json'
),
));
// execute request and get response
$resultm = curl_exec($ch);
$msgval = json_decode($resultm);
$sendernum =explode('#',$msgval->payload->headers[19]->value);
$recivernum =explode('#',$msgval->payload->headers[0]->value);
$createdat = date('Y-m-d H:i:s',strtotime($msgval->payload->headers[18]->value));
Is there a line of code that i need to enter to read full emails?
According to the documentation, you can pass an optional parameter for the format:
Acceptable values are:
"full": Returns the full email message data with body content parsed in the payload field; the raw field is not used. (default)
"metadata": Returns only email message ID, labels, and email headers.
"minimal": Returns only email message ID and labels; does not return the email headers, body, or payload.
"raw": Returns the full email message data with body content in the raw field as a base64url encoded string; the payload field is not used.
Try changing your endpoint to include the format parameter:
$id = $allmessage[$i]->id;
$endpoint = "https://www.googleapis.com/gmail/v1/users/me/messages/$id?format=full";
$ch = curl_init($endpoint);

Create Registration Notification Hub Azure PHP

I'm trying to create registration using REST API NotificationHub AZURE from PHP API Microsoft
¿Anyone know how it's done?
Regards and thanks!
Generally speaking, there are 3 main steps required to access Notification Hubs REST endpoints:
Parse the connection string
Generate the authorization token
Perform the HTTP call
You can refer to https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-php-backend-how-to/ for more detail.
Meanwhile, you can directly use these PHP sample provided by Azure Team in your application, which can implement your requirements easily.
# build uri
$uri = $this->endpoint . $this->hubPath . "/registrations" . NotificationHub::API_NEW_VERSION;
$ch = curl_init();
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '. $token,
'Content-Type: application/xml',
'x-ms-version: 2015-01'
];
$request_body = self::requestBodyRegistration($device_type, $tagsOrTagExpression, $device_code );
if( is_null( $request_body ) )
{
return null;
}
curl_setopt_array($ch, array(
CURLOPT_URL => $uri,
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $request_body
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
curl_close($ch);
private function requestBodyRegistration($device_type, $tagsOrTagExpression, $device_code )
{
switch ($device_type) {
case 'apple':
return '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<Tags>'. $tagsOrTagExpression .'</Tags>
<DeviceToken>'. $device_code .'</DeviceToken>
</AppleRegistrationDescription>
</content>
</entry>';
case 'gcm':
return '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<GcmRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<Tags>'. $tagsOrTagExpression .'</Tags>
<GcmRegistrationId>'. $device_code .'</GcmRegistrationId>
</GcmRegistrationDescription>
</content>
</entry>';
default:
return null;
}
}

Using curl instead of http request 2 in PHP

I'm trying to use curl instead of the http request 2 pear module in PHP to query the plivo api. They have an existing library for easily making calls to their API but it uses a pear module called http request2. I don't really know how to install a pear module on a server so I thought of just rewriting some parts of their library to just use curl.
Here's the part of their code that I specifically want to modify:
function __construct($auth_id, $auth_token, $url="https://api.plivo.com", $version="v1") {
if ((!isset($auth_id)) || (!$auth_id)) {
throw new PlivoError("no auth_id");
}
if ((!isset($auth_token)) || (!$auth_token)) {
throw new PlivoError("no auth_token");
}
$this->version = $version;
$this->api = $url."/".$this->version."/Account/".$auth_id;
$this->auth_id = $auth_id;
$this->auth_token = $auth_token;
}
private function request($method, $path, $params=array()) {
$url = $this->api.rtrim($path, '/').'/';
if (!strcmp($method, "POST")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
$req->setHeader('Content-type: application/json');
if ($params) {
$req->setBody(json_encode($params));
}
} else if (!strcmp($method, "GET")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
$url = $req->getUrl();
$url->setQueryVariables($params);
} else if (!strcmp($method, "DELETE")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
$url = $req->getUrl();
$url->setQueryVariables($params);
}
$req->setAdapter('curl');
$req->setConfig(array(
'timeout' => 30,
'ssl_verify_peer' => FALSE,
));
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
$req->setHeader(array(
'Connection' => 'close',
'User-Agent' => 'PHPPlivo',
));
$r = $req->send();
$status = $r->getStatus();
$body = $r->getbody();
$response = json_decode($body, true);
return array("status" => $status, "response" => $response);
}
public function get_account($params=array()) {
return $this->request('GET', '', $params);
}
And here's the code that I have so far:
<?php
$curl = curl_init();
$curl_options = array(
CURLOPT_URL => 'https://api.plivo.com/v1/Account/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_USERPWD => 'auth_id:auth_token',
CURLOPT_HTTPHEADER => array("Connection: close", "User-Agent: PHPPlivo"),
CURLOPT_TIMEOUT => 30
);
curl_setopt_array($curl, $curl_options);
$response = curl_exec($curl);
curl_close($curl);
?>
I don't really know what's going on behind the scenes but this specific code is telling me that its using basic authentication using the values for the auth id and auth token:
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
So I also set it using curl:
CURLOPT_USERPWD => 'auth_id:auth_token',
I'm pretty much stuck. All I get as a respose is the following:
{
"error": "not found"
}
It doesn't really make much sense into what I have missed or done wrong. Please help. Thank you in advance!
Below are the things you need to handle to sync your new code with old one:
If you are using GET method
CURLOPT_URL => 'https://api.plivo.com/v1/Account/'.http_build_query($params),
CURLOPT_HTTPHEADER => array("User-Agent: PHPPlivo"),
If you are using POST method
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_HTTPHEADER => array("Content-type: application/json", "User-Agent: PHPPlivo"),
Yea... The PEAR dependency is definitely overkill for Plivo's wrapper. So that was one of the first modifications I made to the code.
Check out:
https://github.com/ashbeats/Plivo-Curl-Based-Wrapper/
Only difference is the RestAPI::request() method.

Perform soap request via https with self-signed certificate by cURL

I'm trying to perform soap request to web-service written on C# via https. Server uses self-signed certificate.
After many failed attempts with usage of SoapClient I decided to use pure cURL to perfrom request.
My code:
<?php
header('Content-Type: text/plain; charset=utf-8');
$url = 'https://ip:8443/ServiceName';
$admin = 'login';
$password = 'haShedPassw0rdHere';
$post =
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
// Soap service params xml
</soap:Body>
</soap:Envelope>';
$headers = array(
'Content-type: text/xml;charset="utf-8"',
'Accept: text/xml',
'Cache-Control: no-cache',
'Pragma: no-cache',
'SOAPAction: https://ip:8443/ServiceName',
'Content-length: ' . strlen($post),
);
$curl = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => $admin . ':' . $password,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10
);
curl_setopt_array($curl, $options);
var_dump($response = curl_exec($curl));
?>
Response:
string(370) "
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
a:InvalidSecurity
</faultcode>
<faultstring xml:lang="ru-RU">
Ошибка при проверке безопасности сообщения.
</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>"
Where:
Ошибка при проверке безопасности сообщения.
Means something like:
Communication security check error.
What have I tried:
POST request with a self-signed certificate
How to consume a WCF Web Service that uses custom username validation with a PHP page?
Php SoapClient stream_context option
SOAP authentication with PHP
How can I send SOAP XML via Curl and PHP?
And more of them.
Question: What am I doing wrong?
Regards.
P.S.: Tested with PHP 5.3, PHP 5.4.14, PHP 5.5.1. Results are same.
UPDv1:
C# Source, provided by service support team:
private void Button_SetData_Click(object sender, EventArgs e)
{
eLeed.WebServiceClient client =
new eLeed.WebServiceClient();
client.ClientCredentials.UserName.UserName = "login";
client.ClientCredentials.UserName.Password = "haShedPassw0rdHere";
Stream input = null;
input = GetQuery("ServiceMethod", TextBox_Command.Text);
XmlDocument response = new XmlDocument();
response.PreserveWhitespace = true;
response.Load(client.SetDataContractor(input));
ExeResponse(response);
input.Close();
client.Close();
}
Well, this button is actually working. But how perform something like that in php with cURL ? Especially, how to pass those two lines:
client.ClientCredentials.UserName.UserName = "login";
client.ClientCredentials.UserName.Password = "haShedPassw0rdHere";
Therefore, shouldn't it return message like "invalid credentials" or something?
The error doesnt seem to be on the client side but on the server side. The server says that some security check failed. If it was a client error, you would get nothing but an error by cURL. You get an XML answer.
You should look at the server side.

Categories