I try to send json format to my android app , but i find that my json format is uncorrect.
{data={"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, flag=0, title=Google Cloud Messaging, is_background=false}
I set the data like this:
$app->post('/users/send_to_all',
function() use ($app) {
$response = array();
verifyRequiredParams(array('user_id', 'message'));
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$db = new DbHandler();
$user_id = $app->request->post('user_id');
$message = $app->request->post('message');
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$gcm = new GCM();
$push = new Push();
//get the user using userid
$user = $db->getUser($user_id);
//creating tmp message , skipping database insertion
$msg = array();
$msg['message'] = $message;
$msg['message_id'] = '';
$msg['chat_room_id'] = '';
$msg['created_at'] = date('Y-m-d G:i:s');
$data = array();
$data['user'] = $user;
$data['message'] = $msg;
$data['image'] = 'http://www.androidhive.info/wp-content/uploads/2016/01/Air-1.png';
$push->setTitle("Google Cloud Messaging");
$push->setIsBackground(FALSE);
$push->setFlag(PUSH_FLAG_USER);
$push->setData($data);
//sending message to topic `global`
//on the device every user should subscribe to `global` topic
$gcm->sendToTopic('global', $push->getPush());
$response['user'] = $user;
$response['error'] = false;
echoRespnse(200, $response);
});
Here is my Push.php about getPush():
public function getPush() {
$res = array();
$res['title'] = $this->title;
$res['is_background'] = $this->is_background;
$res['flag'] = $this->flag;
$res['data'] = $this->data;
return $res;
}
Here is my Gcm.php about sendToTopic:
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
I'm really not familiar with php , how do i fix the JSON format ?
Any help would be appreciated , thanks in advance !
I update my question , i find json_encode in my Gcm.php:
It's on curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
class GCM {
//constructor
function __construct() {
}
//sending push message to single user by gcm registration id (array 最後面有, 待看)
public function send($to, $message) {
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending push message to multiple users by gcm registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//function makes curl request to gcm servers (__DIR__ 待看)
private function sendPushNotification($fields) {
//include config
include_once __DIR__ . '/../../include/config.php';
//Set POST variable
//$url = 'https://gcm-http.googleapis.com/gcm/send';
$url='https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//open connection
$ch = curl_init();
//set the url , number of POST vars , POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//Execute post (=有三個?)
$result = curl_exec($ch);
if ($result === FALSE){
die('Curl failed: '. curl_error($ch));
}
//close connection
curl_close($ch);
return $result;
}
}
?>
It's still let my json format incorrect , how do i fix ?
PHP has some built-in json functions, you need json_encode() and json_decode().
For example this code:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Will print:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Here's the link to documentation for json_encode() and for the entire json in php documentation.
Hope this helps.
Your JSON is invalid. try:
{"data":{"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, "flag":0, "title":"Google Cloud Messaging", "is_background":false}
Notice ive replaced usage of = with : and wrapped keys and strings in quotes (")
To get it into a nice json string with php you need to build your array correctly first. Possible way is to setup a response array and then you can json_encode() it.
$response =[
'data' => $data,
'flag' => 0,
'title' => 'Google Cloud Messaging',
'is_background' => false.
];
now you can
json_encode($response);
Related
I'm new to laravel and I seek to learn more about Retrieving user information from Database.
I have a website where you can send a message from_id, to_id.
When people register, there data get inserted in a table users.
Users table contains:
uid(from_id), email, tokenn
Posts table contains:
message, from_id, to_id
I created an php file that will push notification for a user tokenn and added this code to:
\sup\app\Http\Controllers
postsController.php
Here's my post function that posts a message from user to another with push notification function.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\post;
use Auth;
use Lang;
class postsController extends Controller
{
public function send_feedback(Request $request){
$this->validate($request,[
'feedback_image' => 'nullable|image|mimes:jpeg,png,jpg|max:3072',
'feedback_content' => 'required|max:500'
]);
$pid = rand(9,999999999)+time();
if (Auth::user()) {
$from_id = Auth::user()->uid;
}elseif (Auth::guest()) {
$from_id = 0;
}
$to_id = $request['hidden2'];
$feedback = $request['feedback_content'];
$image = $request->file('feedback_image');
$time = $request['hidden'];
if ($request->hasFile('feedback_image')) {
$img_ext = $image->getClientOriginalExtension();
$img_name = rand(9,9999999)+time()+rand(0,55555).".".$img_ext;
$img_new = $image->storeAs("fbImgs",$img_name);
}else{
$img_name = "";
}
$post = new post();
$post->pid = $pid;
$post->from_id = $from_id;
$post->to_id = $to_id;
$post->feedback = $feedback;
$post->image = $img_name;
$post->time = $time;
$post->save();
//
**define('xxxxx');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='{{ Auth::user()->tokenn }}';
$notification = [
'title' =>'XXX',
'body' => 'XXXX',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;**
//
return redirect()->back()->with('feedback_sent',Lang::get('trans.fb_sent'));
}
public function postPrivacy(Request $request){
$pid_var = $request['pid'];
$pid_ex = explode("_", $pid_var);
$pid = #$pid_ex[1];
if ($request['status'] == "true") {
$updatePrivacy = post::where('pid',$pid)->update(['privacy' => 1]);
}else{
$updatePrivacy = post::where('pid',$pid)->update(['privacy' => 0]);
}
return $pid;
}
public function deletePost(Request $request){
$checkID = post::where('pid',$request['pid'])->get()->count();
if ($checkID > 0) {
$allowed = post::where('pid',$request['pid'])->get();
foreach ($allowed as $getAllowed) {
$to_id = $getAllowed->to_id;
$from_id = $getAllowed->from_id;
}
if ($to_id == Auth::user()->uid || $from_id == Auth::user()->uid) {
$deleteFB = post::where('pid',$request['pid'])->delete();
return "done";
}else{
return Lang::get('trans.delPost_notAllowed');
}
}else{
return Lang::get('trans.err_somethingWrong');
}
}
}
?>
As you can see, $token='{{ Auth::user()->tokenn }}';, Token should get current user's tokenn, the recipient token from users table but I don't know how?
I tried to declare new variable as follows: $tokenn = Auth::user()->tokenn but it is not working. I'm messing something. I searched whole project where to declare and retrieve column name of token but I don't know where.
Edit:
changed $token='{{ Auth::user()->tokenn }}'; to $token=Auth::user()->tokenn; as I have been informed.
It is working but in this case $token is recieving logged in user token and sends the sender a notification. I want to push notification for the recipient of the message something like $token=Auth::user()->to_id->tokenn;
In case if you want to get the other user's tokenn (to_id user), try this code:
$token = User::find($to_id)->tokenn;
in case if to_id is the column uid inside your table, then you should use this:
$token = User::where('uid', $to_id)->first()->tokenn;
also you need to make sure that the other user exists, from request validation or using findOrFail instead of find or firstOrFail instead of first.
Update:
Instead of curl, you can use Laravel native Illuminate\Support\Facades\Http wrapper which makes debugging easier. I translated your code:
<?php
class postsController extends Controller
{
public function send_feedback(Request $request)
{
// codes before ....
$apiAccessKey = "some key";
$token = "something";
$url = "https://fcm.googleapis.com/fcm/send";
$notification = [
'title' => 'XXX',
'body' => 'XXXX',
'icon' => 'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = [
"message" => $notification,
"moredata" => 'dd'
];
$fcmNotification = [
'to' => $token,
'notification' => $notification,
'data' => $extraNotificationData
];
$response = Http::acceptJson()
->withHeaders([
'Authorization' => 'key=' . $apiAccessKey
])->post(
$url,
$fcmNotification
);
dd($response->json());
}
}
I have a problem on setting signature in this part of the guide (http://amazonpaycheckoutintegrationguide.s3.amazonaws.com/amazon-pay-checkout/set-payment-info.html). Here' my code:
<?
header('Content-Type: application/json');
define("STORE_ID", "amzn1.application-oa2-client.fb120c0b541e4007aaf987a73b365a3e");
define("VENDOR_ID", "A6SFQPANHYSL0");
define("PUBLIC_KEY_ID", "AGBUUNBAKQW5OMTKHP5WZH55");
define("PRIVATE_KEY_ID", "AmazonPay_AGBUUNBAKQW5OMTKHP5WZH55.pem");
$method = 'POST';
// API Merchant Scan
$url = 'https://pay-api.amazon.eu/sandbox/v2/checkoutSessions/'.$_GET['amazonCheckoutSessionId'];
$payload = array(
'webCheckoutDetails' => array(
'checkoutResultReturnUrl'=> 'https://a.com/merchant-confirm-page'
),
'paymentDetails' => array(
'paymentIntent'=> 'AuthorizeWithCapture',
'canHandlePendingAuthorization'=>false,
'softDescriptor'=> 'Descriptor',
'chargeAmount'=> array(
'amount'=> '1',
'currencyCode'=> 'EUR'
),
),
'merchantMetadata'=> array(
'merchantReferenceId'=> 'Merchant reference ID',
'merchantStoreName'=> 'Merchant store name',
'noteToBuyer'=> 'Note to buyer',
'customInformation'=> 'Custom information'
)
);
// Convert to json string
$payload = json_encode($payload);
$requestParameters = array();
include 'amazon-pay-api-sdk-php-master/vendor/autoload.php';
$amazonpay_config = array(
'public_key_id' => PUBLIC_KEY_ID,
'private_key' => PRIVATE_KEY_ID,
'region' => 'EU',
'sandbox' => true
);
$client = new Amazon\Pay\API\Client($amazonpay_config);
// Create an array that will contain the parameters for the charge API call
$pre_signed_headers = array();
$pre_signed_headers['Accept'] = 'application/json';
$pre_signed_headers['Content-Type'] = 'application/json';
$pre_signed_headers['X-Amz-Pay-Region'] = 'eu';
$timestamp_data = date("Ymd");
$timestamp_orario = date("His");
$timestamp = $timestamp_data."T".$timestamp_orario."Z";
$signedInput = $client->createSignature($method, $url, $requestParameters, $pre_signed_headers, $payload, $timestamp);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://pay-api.amazon.eu/sandbox/v2/checkoutSessions/'.$_GET['amazonCheckoutSessionId']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$headers = array();
$headers[] = 'Authorization: AMZN-PAY-RSASSA-PSS PublicKeyId=AGBUUNBAKQW5OMTKHP5WZH55, SignedHeaders=accept;content-type;x-amz-pay-date;x-amz-pay-host;x-amz-pay-region, Signature= '.$signedInput;
$headers[] = 'X-Amz-Pay-Date: '.$timestamp;
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$json = json_decode($result);
print_r($json);
?>
The class for $client->createSignature is:
public function createSignature($http_request_method, $request_uri, $request_parameters, $pre_signed_headers, $request_payload, $timeStamp)
{
$rsa = $this->setupRSA();
$pre_signed_headers['X-Amz-Pay-Date'] = $timeStamp;
$pre_signed_headers['X-Amz-Pay-Host'] = $this->getHost($request_uri);
$hashedPayload = $this->hexAndHash($request_payload);
$canonicalURI = $this->getCanonicalURI($request_uri);
$canonicalQueryString = $this->createCanonicalQuery($request_parameters);
$canonicalHeader = $this->getHeaderString($pre_signed_headers);
$signedHeaders = $this->getCanonicalHeadersNames($pre_signed_headers);
$canonicalRequest = (
$http_request_method . "\n" .
$canonicalURI . "\n" .
$canonicalQueryString . "\n" .
$canonicalHeader . "\n" .
$signedHeaders . "\n" .
$hashedPayload
);
$hashedCanonicalRequest = self::AMAZON_SIGNATURE_ALGORITHM . "\n" . $this->hexAndHash($canonicalRequest);
$signature = $rsa->sign($hashedCanonicalRequest);
if ($signature === false) {
throw new \Exception('Unable to sign request, is your RSA private key valid?');
}
return base64_encode($signature);
}
The problem i received from the page i want to laod is:
[reasonCode] => InvalidRequestSignature
[message] => Unable to verify signature, signing String ...
Do you know how i can get a valid signature? I can use the one i got 2 steps before (the one that create the button for amazon pay) but i don't think it is the same.
Thank you for your time.
i am trying to send push notification from my android device through my server, so i have wrote kotlin code for getting token from firebase and stored it into my server. next step i wrote php script to fetch stored tokens from my server and send message command to firebase. i have tested the same API using postman and u got the success message
{"multicast_id":7524239394194034238,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1587205979775713%03eb2b8403eb2b84"}]}[]
but the message is not received in my android application , when i directly send notification from the firebase console the notification is received in my application i think the problem is in my PHP script. i am new to this firebase configuration and PHP help me to complete this one.
below i'll add my kotlin code and PHP scripts
my kotlin file
class myfirebasemessaging: FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
if (remoteMessage!!.notification != null) {
val title = remoteMessage.notification!!.title
val body = remoteMessage.notification!!.body
NotificationHelper.displayNotification(applicationContext, title!!, body!!)
}
}
}
fetch token from my db
public function getAllTokens($usertype){
$stmt = $this->con->prepare("SELECT token from fcm_token WHERE user_type=?");
$stmt->bind_param("s", $usertype);
$stmt->execute();
//$stmt->bind_result($token);
$result = $stmt->get_result();
$tokens = array();
while($token = $result->fetch_assoc()){
array_push($tokens, $token['token']);
}
return $tokens;
}
Firebase send PHP
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'notification' => $message,
);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once '../Constants.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
sett message PHP
<?php
class Push {
//notification title
private $title;
//notification message
private $message;
//notification image url
private $image;
//initializing values in this constructor
function __construct($title, $message, $image) {
$this->title = $title;
$this->message = $message;
$this->image = $image;
}
//getting the push notification
public function getPush() {
$res = array();
$res['data']['title'] = $this->title;
$res['data']['message'] = $this->message;
$res['data']['image'] = $this->image;
return $res;
}
}
*sorry for my bad english
You are receiving notification payload on your android app so change your php getPush function to use notification payload:
public function getPush() {
$res = array();
$res['title'] = $this->title;
$res['body'] = $this->message;
$res['image'] = $this->image;
return $res;
}
I'm using Quickblox to send push notifications to iPhone users. I created PHP functions for session and creating a user and API is working fine, but testing sending a push notification, I got an error on Dashboard/Queue: "incorrect event" on the message column. The event is created but never arrived.
The response of the API is OK, like the documentation.
I don't know why I got that error.
This is my code:
if (isset($_POST['mensaje'])) {
// Quickblox user Sign Up
$session = createSession( . . . , '...', '...', '...', '...');
$token = $session->token;
$group = '...'; // Hardcoded only for testing
$resp = sendQBPush($_POST['mensaje'], $group, $token);
}
and the function:
function sendQBPush($msg, $group, $token)
{
if (!$msg) {
return false;
}
$message = base64_encode($msg);
// Build post body
$post_body = array(
'event' => array(
'notification_type' => 'push',
'environment' => 'production',
'user' => array(
'tags' => array(
'any' => $group
)
) ,
'push_type' => 'apns',
'message' => 'payload=' . $message
)
);
$request = json_encode($post_body);
$ch = curl_init('http://api.quickblox.com/events.json');
curl_setopt($ch, CURLOPT_POST, true); // Use POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); // Setup post body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.0',
'QB-Token: ' . $token
));
$resultJSON = curl_exec($ch);
$responseJSON = json_decode($resultJSON);
echo $resultJSON;
// Check errors
if ($responseJSON) {
return $responseJSON;
}
else {
$error = curl_error($curl) . '(' . curl_errno($curl) . ')';
return $error;
}
// Close connection
curl_close($curl);
}
Thanks for your help
i am able to send sms via php but in that i have to mention mobile number everytime i want that with the same script i can send sms to the entries stored in my database .
here is my code:
<?php
//Your authentication key`enter code here`
$authKey = "API key";
//Multiple mobiles numbers separated by comma
$mobileNumber = "+919425386214";
//Sender ID,While using route4 sender id should be 6 characters long.
$senderId = "Social";
//Your message to send, Add URL encoding here.
$message = urlencode("Test message");
//Define route
$route = "04";
//Prepare you post parameters
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
if (isset($_POST['submit']))
{
//API URL
$url="https://control.msg91.com/api/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo $output;
}
?>
please help so that i can send sms to my clients whom contact no. are stored in my database
You need to do some query code to do it , for your help a sample code:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$mobileNumber = '';
$conn = mysqli_connect('localhost','root','','database name') or die (mysqli_error()); // give connection credentials here
if($conn){
$query = "Select mobile_number From User"; // change table name and column name accordingly.
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$mobileNumber .= $row['mobile_number'].',';
}
}
}
$mobileNumber = substr($mobileNumber,0,strlen($mobileNumber)-1); // now you have all mobile numbers in , seperated form in this variable
Note:- You can add this code in your current php code and do changes accordingly and you will get the output what you want.