I am trying to implement Paytm payment gateway in my app but it is giving
Bundle[{STATUS=TXN_FAILURE, ORDERID=order1, TXNAMOUNT=7.00, MID=cdBOMy65033449597261, RESPCODE=330, BANKTXNID=, CURRENCY=INR, RESPMSG=Paytm checksum mismatch.}] this error, for both TEST and Production environment.
Here is my PHP code to generate the checksum.
$paytmParams = array();
$paytmParams["MID"] = "cdBOMy65033449597261";
$paytmParams["ORDER_ID"] = "order1";
$paytmParams["CUST_ID"] = "cust1";
$paytmParams["MOBILE_NO"] = "9799990168";
$paytmParams["EMAIL"] = "droidwithme#gmail.com";
$paytmParams["CHANNEL_ID"] = "WAP";
$paytmParams["TXN_AMOUNT"] = "7.00";
$paytmParams["WEBSITE"] = "DEFAULT"; //tried WEBSTAGING and APPSTAGING
$paytmParams["INDUSTRY_TYPE_ID"] = "Retail";
$paytmParams["CALLBACK_URL"] = "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=order1";
//Here checksum string will return by getChecksumFromArray() function.
$paytmChecksum = EndecPaytm::getChecksumFromArray($paytmParams, $merchantKey);
$responseBody = [
'message' => 'Checksum Generated.',
'data' => [
"CHECKSUMHASH" => $paytmChecksum,
"ORDER_ID" => "order1",
"payt_STATUS" => "1"
]
];
return ApiMethods::apiResponse('success', $responseBody);
And this is my android side code,
private void getPaytmWindow(String chkSm) {
PaytmPGService Service = PaytmPGService.getProductionService();
//Kindly create complete Map and checksum on your server-side and then put it here in paramMap.
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put( "MID" , "cdBOMy65033449597261"); //cdBOMy65033449597261
// Key in your staging and production MID available in your dashboard
paramMap.put( "ORDER_ID" , "order1");
paramMap.put( "CUST_ID" , "cust1");
paramMap.put( "MOBILE_NO" , "9799990168");
paramMap.put( "EMAIL" , "droidwithme#gmail.com");
paramMap.put( "CHANNEL_ID" , "WAP");
paramMap.put( "TXN_AMOUNT" , "7.00");
paramMap.put( "WEBSITE" , "DEFAULT");
// This is the staging value. Production value is available in your dashboard
paramMap.put( "INDUSTRY_TYPE_ID" , "Retail");
// This is the staging value. Production value is available in your dashboard
paramMap.put( "CALLBACK_URL", "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=order1");
paramMap.put( "CHECKSUMHASH" , chkSm);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
// Some UI Error Occurred in Payment Gateway Activity.
// // This may be due to initialization of views in
// Payment Gateway Activity or may be due to //
// initialization of webview. // Error Message details
// the error occurred.
Utils.logD(TAG, "someUIErrorOccurred : " + inErrorMessage);
}
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG123444", "Payment Transaction : " + inResponse);
if (Objects.requireNonNull(inResponse.getString("STATUS")).contains("TXN_SUCCESS")) {
Toast.makeText(getApplicationContext(), "Transaction completed", Toast.LENGTH_LONG).show();
}
Utils.logD(TAG, inResponse.getString("STATUS"));
// Toast.makeText( getApplicationContext(), "Payment Transaction response " + inResponse.toString(), Toast.LENGTH_LONG ).show();
}
#Override
public void networkNotAvailable() {
// If network is not
// available, then this
// method gets called.
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
// This method gets called if client authentication
// failed. // Failure may be due to following reasons //
// 1. Server error or downtime. // 2. Server unable to
// generate checksum or checksum response is not in
// proper format. // 3. Server failed to authenticate
// that client. That is value of payt_STATUS is 2. //
// Error Message describes the reason for failure.
Utils.logD(TAG, "clientAuthenticationFailed " + inErrorMessage);
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
Utils.logD(TAG, "inErrorMessage " + inErrorMessage);
Utils.logD(TAG, "inFailingUrl " + inFailingUrl);
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
Utils.logD(TAG, "Payment Transaction Failed " + inErrorMessage);
Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
}
});
}
This is the Gradle dependency
implementation('com.paytm:pgplussdk:1.2.3') {
transitive = true
}
I have tried the Test environment and Production as well, but getting the checksum mismatch error every time.
For testing purposes, I have set the values hardcoded. I have gone various threads over the Paytm QA forum but they did not provide any sufficient answer to the threads(threads same as mine).
In PHP
Change this
$paytmParams["ORDER_ID"] = "order1";
to this
$paytmParams["ORDERID"] = "order1";
In APP
Change this
paramMap.put( "ORDER_ID" , "order1");
to this
paramMap.put( "ORDERID" , "order1");
Related
i use the latest v2 paypal php sdk sandbox and samples with laravel framework, the create order always success but when capture the order it always fails
and return this error:
"{"name":"UNPROCESSABLE_ENTITY",
"details":[
{"issue":"COMPLIANCE_VIOLATION",
"description":"Transaction cannot be processed due to a possible compliance violation. To get more information about the transaction, call Customer Support."}],
"message":"The requested action could not be performed, semantically incorrect, or failed business validation.",
"debug_id":"d701744348160",
"links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-COMPLIANCE_VIOLATION","rel":"information_link","method":"GET"}]}
my web.php file :
Route::get('capture_order', 'PayController#capture_order')->name('capture_order');
Route::get('create_order', 'PayController#create_order')->name('create_order');
Route::get('cancel', 'PayController#cancel')->name('payment.cancel');
Route::get('return', 'PayController#return')->name('payment.return');
Route::get('success', 'PayController#success')->name('payment.success');
& the PayController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
class PayController extends Controller
{
public $clientId;
public $clientSecret;
public $client;
public $cancel_url = 'http://localhost:8000/cancel';
public $return_url = 'http://localhost:8000/return';
public function __construct()
{
$mode = config('paypal.mode', 'sandbox');
if ($mode == "live") {
$this->clientId = config('paypal.live.client_id');
$this->clientSecret = config('paypal.live.client_secret');
} else {
$this->clientId = config('paypal.sandbox.client_id');
$this->clientSecret = config('paypal.sandbox.client_secret');
}
$environment = new SandboxEnvironment($this->clientId, $this->clientSecret);
$this->client = new PayPalHttpClient($environment);
}
private function buildRequestBody()
{
return [
'intent' => 'CAPTURE',
'application_context' =>[ "cancel_url" => $this->cancel_url,
"return_url" => $this->return_url],
'purchase_units' =>
[
0 => [
'amount' =>
[
'currency_code' => 'USD',
'value' => '20'
]
]
]
];
}
public function create_order()
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = $this->buildRequestBody();
try {
$response = $this->client->execute($request);
foreach ($response->result->links as $key => $value) {
if ($value->rel == "approve")
{
return redirect($value->href);
}
}
}catch (\Exception $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
}
public function capture_order(Request $request)
{
// if ($request->token) {
$request = new OrdersCaptureRequest($request->token);
$request->prefer('return=representation');
try {
$response = $this->client->execute($request);
}catch (\Exception $ex) {
echo $ex->statusCode;
dd($ex->getMessage());
}
// }
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function cancel(Request $request)
{
dump($request->all());
dd('Your payment is canceled. You can create cancel page here.');
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function return(Request $request)
{
if ($request->token) {
return redirect()->route('capture_order', [
'token' => $request->token,
'PayerID' => $request->PayerID
]);
}
dd($request->all());
}
}
i use paypal php sdk with a sandbox account.
can i use the old paypal version or it's completely deprecated ?
waiting your help :)
COMPLIANCE_VIOLATION
This problem is most likely related to the country of the receiving sandbox Business account. Create a new account for a different country such as US, then create a new REST app that uses that sandbox account, and test its sandbox clientid/secret in sandbox mode instead.
For later use in live mode, ensure that if the live business account is from one of the countries that require it, that the live account has a valid auto sweep withdrawal method active and enabled on the account, such as a US bank or local visa card. If you need help configuring auto sweep for live mode, contact PayPal's business support
i call the support and the response was:
Funds received into Egyptian accounts need to be automatically withdrawn to an attached funding source, such as a bank. You can set this up by going into the account settings section of the account, then the "money, banks and cards" section and at the bottom of that page you'll find "automatic withdrawal" where you can specify a financial instrument to use for automatic withdrawals -- https://www.sandbox.paypal.com/businessmanage/account/money
thanks for u all :)
I wan't to implement a Twitter login through the Firebase API.
My client is a android app who loggs into the Twitter account and sends the IdToken to my php backend. This works fine.
OAuthProvider.Builder provider = OAuthProvider.newBuilder("twitter.com");
provider.addCustomParameter("lang", "de");
FirebaseAuth.getInstance()
.startActivityForSignInWithProvider(/* activity= */ this, provider.build())
.addOnSuccessListener(
new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
// User is signed in.
// IdP data available in
// authResult.getAdditionalUserInfo().getProfile().
// The OAuth access token can also be retrieved:
// authResult.getCredential().getAccessToken().
// The OAuth secret can be retrieved by calling:
// authResult.getCredential().getSecret().
Log.d("werte", "User is signed in");
Log.d("werte", "Username: " + authResult.getAdditionalUserInfo().getUsername());
Log.d("werte", "Info: " + authResult.getAdditionalUserInfo().getProfile().toString());
authResult.getUser().getIdToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
#Override
public void onSuccess(GetTokenResult getTokenResult) {
Log.d("werte", "Accesstoken: " + getTokenResult.getToken());
}
});
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Handle failure.
Log.d("werte", "Sign in failed");
e.printStackTrace();
}
});
But for php I only found a method to verify the token. I additionally need the user information. How do I get this?
$verifier = IdTokenVerifier::createWithProjectId('myProjectId');
try {
$token = $verifier->verifyIdToken($idToken);
echo($token);
} catch (IdTokenVerificationFailed $e) {
echo $e->getMessage();
// Example Output:
// The value 'eyJhb...' is not a verified ID token:
// - The token is expired.
}
Edit:
I solved it with the help of Frank. But I used a little different way.
$googleKeysURL = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com';
$key = json_decode(file_get_contents($googleKeysURL), true);
$decoded = JWT::decode($idToken, $key, array("RS256"));
In the $decoded Object you can find every profile information you need.
Thank you Frank
Verifying the ID token does nothing more then what its name says: it verifies that the token is signed with a valid key.
If you want to use the claims from the decoded token, use a JWT decoding library like the one from Firebase: php-jwt. From the example in the documentation, you should be able to get the decoded token with:
$decoded = JWT::decode($jwt, $key, array('HS256'));
I'm using Firebase for push notifications. My PHP code is working fine. I'm getting success message, but not receiving the push notification in my Android app for single device and multi device. But using Firebase console for sending notification it's working fine. I got the notification on the Android device. Is there any server configuration that I need to add?
PHP Code:
$yourApiSecret = "AIzaSyDY";
$androidAppId = "traasasadad";
$data = array(
"tokens" => "AAAA_kFbSQ4:APA91bQuMV-nRuTnVNFg0HD2C9PBnWWad",
"notification" => "Hello World!"
);
$data_string = json_encode($data);
$ch = curl_init('https://push.ionic.io/api/v1/push');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'X-Ionic-Application-Id: '.$androidAppId,
'Content-Length: ' . strlen($data_string),
'Authorization: Basic '.base64_encode($yourApiSecret)
)
);
$result = curl_exec($ch);
var_dump($result);
Android Code:
package com.seven77Trades.notification;
/** * Created by ist on 21/3/17. */ import
android.app.NotificationManager; import android.app.PendingIntent;
import android.content.Context; import android.content.Intent; import
android.media.RingtoneManager; import android.net.Uri; import
android.support.v4.app.NotificationCompat; import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService; import
com.google.firebase.messaging.RemoteMessage; import
com.seven77Trades.HomeActivity; import com.seven77Trades.R;
public class FirebaseMsgService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see:
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be:
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
/*Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getColor());
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getSound());
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getTag());
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getClickAction());*/
sendNotification(remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_logo)
.setContentTitle("Firebase")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} }
Output:
"{"multicast_id":8295856130292351869,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1492611205996022%0296efeff9fd7ecd"}]}"
I got the solution .finally I'm receiving notification in android device.When we are sending notification using API (php,java,python) that time android application getting this request in different method (WakefulBroadcastReceiver) and when we sending using fire base console then request comes different method (FirebaseMessagingService).
Here the BrackPullBroadCastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GcmIntentService extends IntentService {
private Context context;
public GcmIntentService() {
super("GcmIntentService");
}
String imageUrl = "";
#Override
protected void onHandleIntent(Intent intent) {
context = this;
Bundle extras = intent.getExtras();
for (String key: extras.keySet())
{
Log.d (TAG, key + " is a key in the bundle");
Log.d(TAG, extras.get(key) + "");
}
}
}
I think there is some mistake with the target url you can try sending the notification like this:
$url = 'http://fcm.googleapis.com/fcm/send';
$fields =array(
"notification"=> array(
"title" => 'sometitle',
"body" => $message, //Can be any message you want to send
"icon" => $image,
"click_action" => "http://google.com"
),
"registration_ids"=> 'Your android app fcm token',
"data"=> array(
"data" => "something",
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "your firebase app key",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
Also you can pass custom data in the payload
I'm getting a notification only in one device that is set as the first token stored the table in mySQL DB and the notification is not sent to the rest of the token numbers. I tried a WHILE loop and stored the token numbers in an array, but it did not work.
Please suggest a solution. Thank you.
Here is my code:
<?php
require "init.php";
$message=$_POST['message'];
$title=$_POST['title'];
$path_to_fcm='https://fcm.googleapis.com/fcm/send';
$server_key="A*************************Q";
$sql="select token from fcm_info";
$result =mysqli_query($con,$sql);
$row=mysqli_fetch_row($result);
$key=$row[0];
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
$fields =array('to'=>$key,
'notification'=>array('title'=>$title,'body'=>$message));
$payload =json_encode($fields);
$curl_session =curl_init();
curl_setopt($curl_session,CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST, true);
curl_setopt($curl_session,CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session,CURLOPT_IPRESOLVE, CURLOPT_IPRESOLVE);
curl_setopt($curl_session,CURLOPT_POSTFIELDS, $payload);
$result=curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($con);
?>
Use 'registration_ids' instead of 'to' and pass comma separated multiple registrations ids to use multicast in FCM. Final payload should be like:
{
"registration_ids":["id1","id2",...],
"priority" : "normal",
"data" : {
"title" : "Title",
"message" : "Message to be send",
"icon": "icon_path"
}
}
see https://developers.google.com/cloud-messaging/http-server-ref for more help
////////////////////// FCM START /////////////////////////
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key = "your_server_key";
$headers = array(
'Authorization:key=' . $server_key,
'Content-Type:application/json');
$keys = ["key_1", "key_2"];
$fields = array(
"registration_ids" => $keys,
"priority" => "normal",
'notification' => array(
'title' => "title of notification",
'body' => "your notification goes here"
)
);
$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$curl_result = curl_exec($curl_session);
////////////////////// FCM END /////////////////////////
This works for me.
You need to cover the notification sending logic in method and then start the loop & call that method in each iterations pass token and message to the method.
"Please suggest a solution"
I would like to suggest using Services. You're most recommended to read the documention by Android Studio here.
There is a lot to perceive about Services, but at the moment I believe a snippet will be most helpful to you, here is a little code,
Create a class called HelloService
and paste the following code inside with the proper imports*
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "servicestarting",Toast.LENGTH_SHORT).show();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
"This is overhwleming" you might think to yourself. However it's but the contrary.
Example for Services + Firebase
Instead of pushing a message from Firebase, let's say you want to notify a user whenever a modification takes place in one of your databases
first, create databasereference earlier on the Oncreate
mDatabaseLike=FirebaseDatabase.getInstance().getReference().child("Likes");
Go to 'handleMessage Method' and add the following
#Override
public void handleMessage(Message msg) {
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
notifyUserOfDBupdate()
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//stopSelf(msg.arg1);
}
}
Here is the notifyUserOfDBupdate method and how to notify a user
private void notifyUserOfDBupdate() {
//Intents
Intent Pdf_view = new Intent(this, //class to throw the user when they hit on notification\\.class);
PendingIntent pdf_view = PendingIntent.getActivity(this, 0, Pdf_view, 0);
//Notification Manager
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
//The note
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification noti = new NotificationCompat.Builder(getApplicationContext())
.setTicker("TickerTitle")
.setContentTitle("content title")
.setSound(soundUri)
.setContentText("content text")
.setContentIntent(pdf_view).getNotification();
//Execution
noti.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(0, noti);
}
Now run your application once on your real device and a second time on an emulator. Once either one of two modifies your firebase database, the other will be notified instantly.
Modify whichever method you like inside the HandleMessage method. It will be eternal, not unless you make it killable.
kindest regards
I have the server configuration to speak to the Android clients as:
<?php
require_once("mysql.class.php");
require_once("lib/autoloader.php");
// Setting up the PubNub Server:
use Pubnub\Pubnub;
$pubnub = new Pubnub(
"pub-c...", ## PUBLISH_KEY
"sub-c..." ## SUBSCRIBE_KEY
);
// Publishing :
$post_data = json_encode(array("type"=> "groupMessage", "data" => array("chatUser" => "SERVER", "chatMsg" => "Now lets talk", "chatTime"=>1446514201516)));
$info = $pubnub->publish('MainChat', $post_data);
print_r($info);
print_r($post_data);
?>
and html:
<!doctype html>
<html>
<head>
<title>PubNub PHP Test Page</title>
</head>
<body>
<form method="POST" action="index.php">
<input type="submit" name="submit" value="TestSendMessage" />
</form>
</body>
</html>
The publish function works in the server as I can see the messages arrive in the log console of the client Android app, but the message is never parsed correctly and therefore does not appear in the listview given the SubscribeCallback:
public void subscribeWithPresence(String channel) {
this.channel = channel;
Callback subscribeCallback = new Callback() {
#Override
public void successCallback(String channel, Object message) {
if (message instanceof JSONObject) {
try {
JSONObject jsonObj = (JSONObject) message;
JSONObject json = jsonObj.getJSONObject("data");
final String name = json.getString(Constants.JSON_USER);
final String msg = json.getString(Constants.JSON_MSG);
final long time = json.getLong(Constants.JSON_TIME);
if (name.equals(mPubNub.getUUID())) return; // Ignore own messages
final ChatMessage chatMsg = new ChatMessage(name, msg, time);
presentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// Adding messages published to the channel
mChatAdapter.addMessage(chatMsg);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.d("PUBNUB", "Channel: " + channel + " Msg: " + message.toString());
}
#Override
public void connectCallback(String channel, Object message) {
Log.d("Subscribe", "Connected! " + message.toString());
//hereNow(false);
// setStateLogin();
}
};
try {
mPubNub.subscribe(this.channel, subscribeCallback);
//presenceSubscribe();
} catch (PubnubException e) {
e.printStackTrace();
// Checking if success
Log.d("Fail subscribe ", "on channel: " + channel);
}
}
Testing the server output in the browser by clicking TestSendMessage yields:
Array ( [0] => 1 [1] => Sent [2] => 14465159776373950 ) {"type":"groupMessage","data":{"chatUser":"SERVER","chatMsg":"Now lets talk","chatTime":1446514201516}}
and in app the log output from line: Log.d("PUBNUB", "Channel: " + channel + " Msg: " + message.toString());
Returns: D/PUBNUB: Channel: MainChat Msg: {"type":"groupMessage","data":{"chatUser":"SERVER","chatMsg":"Now lets talk","chatTime":1446514201516}}
as it should, but the message never appears within the ListView of messages and thusly fails the JSON parsing.
The JSON tags are straightforward from the Constants class as:
public static final String JSON_GROUP = "groupMessage";
public static final String JSON_USER = "chatUser";
public static final String JSON_MSG = "chatMsg";
public static final String JSON_TIME = "chatTime";
How can the server sending be reconfigured to allow the success of in app parsing?
Sending JSON over PubNub
Send the JSON object without stringifying it first. In the case for PHP, do not json_encode the message. PubNub SDK will encode and decode it for you.
This:
$post_data = array("type"=> "groupMessage", "data" => array(
"chatUser" => "SERVER", "chatMsg" => "Now lets talk",
"chatTime"=>1446514201516));
Not this:
$post_data = json_encode(array("type"=> "groupMessage", "data" => array(
"chatUser" => "SERVER", "chatMsg" => "Now lets talk",
"chatTime"=>1446514201516)));
Please comment if this resolves or not.