Google Cloud Messaging (GCM) Notification receiving with logs detail - php

I have implement the gcm to send notification to my application and its really working perfect.
I am getting notification on device but issue is that I am getting logs detail may be in notification message instead of only human readable message that I am pushing.
Here is my code that I am using to send notification:
$gcmApiKey = GOOGLE_API_KEY;
$pushApi = new PushAPI();
$sender = new \PHP_GCM\Sender($gcmApiKey);
$message = new \PHP_GCM\Message("1", $messsageVal);
try {
$multicastResult = $sender->sendMulti($message, $deviceRegistrationId, 2);
$results = $multicastResult->getResults();
for ($i = 0; $i < count($deviceRegistrationId); $i++) {
$regId = $deviceRegistrationId[$i];
$result = $results[$i];
$messageId = $result->getMessageId();
if ($messageId != null) {
$canonicalRegId = $result->getCanonicalRegistrationId();
if ($canonicalRegId != null) {
// same device has more than on registration id: update it
}
} else {
$error = $result->getErrorCodeName();
if ($error == \PHP_GCM\Constants::$ERROR_NOT_REGISTERED) {
$pushApi->clearDeviceByDeviceId($regId);
}
}
}
} catch (\InvalidArgumentException $e) {
// $deviceRegistrationId was null
} catch (PHP_GCM\InvalidRequestException $e) {
// server returned HTTP code other than 200 or 503
} catch (\Exception $e) {
// message could not be sent
}
Here is the link of whole API that I am using. PHP_GCM
I try to google it but I didn't get anything to rectify this.
Any help will be appreciated.

You have to parse your response same as you parse a webservice response and show only the msg.
Try getting the message from the received intent using:
String msg=intent.getExtras().getString("msg");
Then show the message as :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.mipmap.app_icon)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(context.getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);

Related

php rest API POST request returning null

I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??

PHP, Twilio SMS - capturing twilio's response

I'm trying to do some SMS messages using Twilio, and so far it's pretty straight forward, but I'm using some test data to capture various scenarios and I used "1234567890" as a phone number to capture an error, but I get the following error when I navigate to the page that queries the twilio api:
Fatal error: Uncaught exception 'Twilio\Exceptions\RestException'
with message '[HTTP 404] Unable to fetch record:
The requested resource /PhoneNumbers/1234567890 was not found'
Here's my code:
use Twilio\Rest\Client;
$client = new Client($sid, $token);
if($ph && preg_match('/^[0-9]{10}$/', $ph)) {
//this returns an array containing type, error_code, and a boolean
//value for is_valid.
$response = lookup($client, $ph);
if($response['is_valid']) {
//send the message via twilio.
$message = $client->messages->create(
$ph,
array(
'from' => 'my_twilio_number_goes_here',
'body' => 'text_body_goes_here'
)
);
//handle twilio response
$status = $message->status;
$sid = $message->sid;
}
How can I capture that response?
$twilio = new TwilioClient(env('TWILIO_ACCOUNT_ID'), env('TWILIO_TOKEN'));
$message=new \StdClass;
try
{
//check mobile number is valid or not
$is_valid_number = $twilio->lookups->v1->phoneNumbers($phone_number)->fetch();
if($is_valid_number)
{
$data['From']=env('TWILIO_FROM_ALPHANUMERIC_NAME');
$data['Body']="Sms testing";
$message = $twilio->messages->create($mobile_number, $data);
}
else{
echo "Your Mobile number is not available.";
}
}
catch(\Exception $e)
{
echo $e->getMessage();
}

Cloudant and Php-on-Couch not working well due to continue

I believe Cloudant has recently changed some of their code. Recently, if you do a storedoc operation, in a try/catch statement. Cloudant will return an 'error' to the framework:
Uncaught exception 'couchException' with message 'Continue
Of course you can handle it in the catch statement, but it should really be coming back as 'successful' in the Try statement of the PHP-on-Couch library.
Anyone come across this or know how to handle it? The biggest issues is that you cannot grab the ID and Rev in the catch statement because it's coming up as an error:
try { // does not return here, goes to catch
$response = $client->storeDoc($doc);
$response_json['status'] = 'success';
$response_json['id'] = $response->id;
$response_json['rev'] = $response->rev;
} catch (Exception $e) { // even though the doc is successfully storing
// check for accepted BEG
$error = '';
$error = $e->getMessage();
$err_pos = strpos($error,"Accepted");
$err_pos_2 = strpos($error,"Continue");
if($err_pos !== false OR $err_pos_2 !== false){ // success
$response_json['status'] = 'success';
$response_json['id'] = $response->id; // returns null
$response_json['rev'] = $response->rev; // returns null
} else { // truely an error
$response_json['status'] = 'fail';
$response_json['message'] = $e->getMessage();
$response_json['code'] = $e->getCode();
}
// check for accepted END
}
I tested in both CouchDB and Cloudant and the behavior is the same. This is what I believe is happening. When you create a new couchDocument:
$doc = new couchDocument($client);
By default the document is set to autocommit. You can see this in couchDocument.php:
function __construct(couchClient $client) {
$this->__couch_data = new stdClass();
$this->__couch_data->client = $client;
$this->__couch_data->fields = new stdClass();
$this->__couch_data->autocommit = true;
}
As soon as you set a property on the document:
$doc->set( array('name'=>'Smith','firstname'=>'John') );
storeDoc is immediately called. You are then trying to call storeDoc a second time and couchDB returns an error.
There are 2 ways to fix this:
Turn off autocommit:
$doc = new couchDocument($client);
$doc->setAutocommit(false);
$doc->set( array('name'=>'Smith','firstname'=>'John') );
try {
$response = $client->storeDoc($doc);
$response_json['status'] = 'success';
$response_json['id'] = $response->id;
$response_json['rev'] = $response->rev;
Keep autocommit on and get the id and rev from the $doc after you set a property:
$doc = new couchDocument($client);
try {
$doc->set( array('name'=>'Smith','firstname'=>'John') );
$response_json['status'] = 'success';
$response_json['id'] = $doc->_id;
$response_json['rev'] = $doc->_rev;

stripe webhook test mode response "none"

I am trying to update database.
I have set up the webhook in stripe in test mode and send a "invoice.payment_succeeded" test webhook to file.but it shows response "none" in stripe output.
What have i done wrong, here is the webhook file, please someone help me, i am very stuck at this. any help will be appreciate...
<?php
include '../admin/include/functions.php';
require_once('Stripe/lib/Stripe.php');
require_once 'stripe_secret.php';
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
Stripe::setApiKey($stripe['secretkey']);
$event = Stripe_Event::retrieve($event_id);
var_dump($event);
$invoice = $event->data->object;
if($event->type == 'invoice.payment_succeeded') {
$customer = Stripe_Customer::retrieve($invoice->customer);
$email = $customer->email;
$customerid = $customer->id;
/*$amount = $invoice->amount / 100;*/
$expiry = $invoice->period->end;
$expiredate = date('Y-d-m', $expiry);
$userup = $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' ");
if ($userup) {
echo "User Date extended";
}
// send a invoice notice email here
}
if($event->type == 'invoice.payment_failed') {
$obj->run_query("UPDATE users SET Status = '0' WHERE user_stripe_id = '$customerid' ");
echo "User membership expired";
}
}
catch(Stripe_CardError $e) {
}
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
http_response_code(200);
?>
The test webhooks from the test webhook button sends a webhook with the right format but all the values are null / zero / etc. Thus your line that does $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' "); will return a falsey result. This means you don't echo anything and just send back an empty 200 response.

Amqplib no ack messages bug

I'm using C-compilled library for rabbit AMQP.
Trying to get messages from queue without acknowledge I get only top 3 messages on consume callback.
Server monitoring shows that 3 messages was gotten without acknowledge.
If I use php-amqplib I got all messages from queue without acknowledge while session.
Code like:
$cnn = new AMQPConnection();
$cnn->setLogin('guest');
$cnn->setPassword('guest');
if ($cnn->connect()) {
} else {
die("Error");
}
$channel = new AMQPChannel($cnn);
$exchange = new AMQPExchange($channel);
$exchange->setName('test');
$exchange->setType(AMQP_EX_TYPE_TOPIC);
$exchange->setFlags(AMQP_DURABLE | AMQP_AUTODELETE | AMQP_PASSIVE);
try {
$exchange->declareExchange();
} catch (Exception $e) {
echo 'Error: '.$e->getMessage();
die(0);
}
$q = new AMQPQueue($channel);
$q->setName('queue');
$q->setFlags(AMQP_DURABLE | AMQP_PASSIVE);
$cnt = $q->declareQueue();
$q->bind($exchange->getName(),'token');
$cb = function(AMQPEnvelope $params, AMQPQueue $queue) {
print_r($params->getBody());
echo "\n";
};
while (true) {
$q->consume($cb);
}
$cnn->disconnect();

Categories