Implementing chat between webpage and android - php

This is my situation. I have a chat-room website. People are publicly chatting together and everyone see who is writing what. All the chats are stored in database (mysql)
Now I want to implement this chatting on Android. So when user sends a text from his phone it should be sent to the chat-room website and vice versa, meaning the Android user should see all texts which are being sent from the chat webpage.
As a result:
1: Android user should see all the texts which people send via the webpage,
2: Android user should be able to send a text to this chat-room webpage (so other users which are using the webpage to chat should see his text).
The big question is, what is the best way to achieve this?
Could this process happen in real time like XMPP?
Is GCM the only way (although it is not real time)?
If i use web services to send the messages to the web, how can i set a listener for the incoming messages?
I don't know if i am clear. Any help is appreciated. Just give the head of the string i will go to the end...
Edit: a server side question: Is there anyway to make the server do something when a specific table in MYSQL is changed (for example when a new row is added)?

The first thing that leapt into my mind was that this fits fairly well into the Pub/Sub paradigm. Clients publish chat messages to specific channels (rooms,) and also subscribe to the channels; the server subscribes to a channel and stores the data in a MySQL database.
You might try using an external real-time network like PubNub. PubNub is free for up to 1m messages (see the pricing page.) They have an Android SDK and PHP SDK (I assume you're using PHP on your server due to your use of the PHP tag.)
In your case, in your Android client, you'd subscribe to a channel:
Pubnub pubnub = new Pubnub("demo", "demo");
try {
pubnub.subscribe("my_channel", new Callback() {
//See full example for all Callback methods
#Override
public void successCallback(String channel, Object message) {
System.out.println("SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
}
} catch (PubnubException e) {
System.out.println(e.toString());
}
(Full example here.) Then, when you want to publish a message:
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
Log.d("PUBNUB",response.toString());
}
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB",error.toString());
}
};
pubnub.publish("my_channel", "This is an important chat message!" , callback);
Neat! But what about your server, how does it receive these messages?
$pubnub = new Pubnub(
"demo", ## PUBLISH_KEY
"demo", ## SUBSCRIBE_KEY
"", ## SECRET_KEY
false ## SSL_ON?
);
$pubnub->subscribe(array(
'channel' => 'my_channel', ## REQUIRED Channel to Listen
'callback' => function($message) { ## REQUIRED Callback With Response
## Time to log this to MySQL!
return true; ## Keep listening (return false to stop)
}
));
I hope this helps your project. Let me know how it goes.

SHORT ANSWER
Here's link to CODETUTS
and to a SAMPLE
LONG ANSWER
For make a chat in realtime compatible with android using db like mysql you have various way. the first who come up to me is to do some api but is not the most good way cause you will have to do many request to your server. So i advice you to use technology like nodeJs and socketIO (just google them...you will find tons of example), take a look to the link i've found for you. Have a nice day. Antonio

You need websockets on the web to do this in real time, in android you need to send push notifications.
Maybe you want to check "Google Cloud Messaging for Android".

Related

How can I send a Firebase Cloud Messaging notification to all devices in laravel [duplicate]

I'm attempting to send out a notification to all app users (on Android), essentially duplicating what happens when a notification is sent via the Firebase admin console. Here is the CURL command I begin with:
curl --insecure --header "Authorization: key=AIzaSyBidmyauthkeyisfineL-6NcJxj-1JUvEM" --header "Content-Type:application/json" -d "{\"notification\":{\"title\":\"note-Title\",\"body\":\"note-Body\"}}" https://fcm.googleapis.com/fcm/send
Here's that JSON parsed out to be easier on your eyes:
{
"notification":{
"title":"note-Title",
"body":"note-Body"
}
}
The response that comes back is just two characters:
to
That's it, the word "to". (Headers report a 400) I suspect this has to do with not having a "to" in my JSON. What would one even put for a "to"? I have no topics defined, and the devices have not registered themselves for anything. Yet, they are still able to receive notifications from the Firebase admin panel.
I'm want to attempt a "data only" JSON package due to the amazing limitation of Firebase notification processing whereby if your app is in the foreground, the notification gets processed by YOUR handler, but if your app is in the background, it gets processed INTERNALLY by the Firebase service and never passed to your notification handler. APPARENTLY this can be worked around if you submit your notification request via the API, but ONLY if you do it with data-only. (Which then breaks the ability to handle iOS and Android with the same message.) Replacing "notification" with "data" in any of my JSON has no effect.
Ok, then I attempted the solution here: Firebase Java Server to send push notification to all devices
which seems to me to say "Ok, even though notifications to everyone is possible via the Admin console... it's not really possible via the API." The workaround is to have each client subscribe to a topic, and then push out the notification to that topic. So first the code in onCreate:
FirebaseMessaging.getInstance().subscribeToTopic("allDevices");
then the new JSON I send:
{
"notification":{
"title":"note-Title",
"body":"note-Body"
},
"to":"allDevices"
}
So now I'm getting a real response from the server at least. JSON response:
{
"multicast_id":463numbersnumbers42000,
"success":0,
"failure":1,
"canonical_ids":0,
"results":
[
{
"error":"InvalidRegistration"
}
]
}
And that comes with a HTTP code 200. Ok... according to https://firebase.google.com/docs/cloud-messaging/http-server-ref a 200 code with "InvalidRegistration" means a problem with the registration token. Maybe? Because that part of the documentation is for the messaging server. Is the notification server the same? Unclear. I see elsewhere that the topic might take hours before it's active. It seems like that would make it useless for creating new chat rooms, so that seems off as well.
I was pretty excited when I could code up an app from scratch that got notifications in just a few hours when I had never used Firebase before. It seems like it has a long way to go before it reaches the level of, say, the Stripe.com documentation.
Bottom line: does anyone know what JSON to supply to send a message out to all devices running the app to mirror the Admin console functionality?
Firebase Notifications doesn't have an API to send messages. Luckily it is built on top of Firebase Cloud Messaging, which has precisely such an API.
With Firebase Notifications and Cloud Messaging, you can send so-called downstream messages to devices in three ways:
to specific devices, if you know their device IDs
to groups of devices, if you know the registration IDs of the groups
to topics, which are just keys that devices can subscribe to
You'll note that there is no way to send to all devices explicitly. You can build such functionality with each of these though, for example: by subscribing the app to a topic when it starts (e.g. /topics/all) or by keeping a list of all device IDs, and then sending the message to all of those.
For sending to a topic you have a syntax error in your command. Topics are identified by starting with /topics/. Since you don't have that in your code, the server interprets allDevices as a device id. Since it is an invalid format for a device registration token, it raises an error.
From the documentation on sending messages to topics:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic.
Copy this in your main activity
FirebaseMessaging.getInstance().subscribeToTopic("all");
Now send the request as
{
"to": "/topics/all",
"data":
{
"title":"Your title",
"message":"Your message"
"image-url":"your_image_url"
}
}
This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.
Just checked the FCM documentation, this is the only way to send notifications to all the devices (as of 8th July 2022).
As mentioned in the comments, the notification is not automatically displayed, you have to define a class that is derived from FirebaseMessagingService and then override the function onMessageReceived.
First register your service in app manifest.
<!-- AndroidManifest.xml -->
<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Add these lines inside the application tag to set the custom default icon and custom color:
<!-- AndroidManifest.xml -->
<!-- Set custom default icon. This is used when no icon is set
for incoming notification messages. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used
when no color is set for the incoming notification message. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
Now create your service to receive the push notifications.
// MyFirebaseMessagingService.java
package com.google.firebase.example.messaging;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
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());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
// [END receive_message]
// [START on_new_token]
/**
* There are two scenarios when onNewToken is called:
* 1) When a new token is generated on initial app startup
* 2) Whenever an existing token is changed
* Under #2, there are three scenarios when the existing token is changed:
* A) App is restored to a new device
* B) User uninstalls/reinstalls the app
* C) User clears app data
*/
#Override
public void onNewToken(#NonNull String token) {
Log.d(TAG, "Refreshed token: " + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// FCM registration token to your app server.
sendRegistrationToServer(token);
}
// [END on_new_token]
private void scheduleJob() {
// [START dispatch_job]
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
.build();
WorkManager.getInstance(this).beginWith(work).enqueue();
// [END dispatch_job]
}
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
public static class MyWorker extends Worker {
public MyWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
// TODO(developer): add long running task here.
return Result.success();
}
}
}
You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM and Send messages to multiple devices - Firebase Documentation
To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:
{
"data":
{
"title": "Your title",
"message": "Your message"
"image-url": "your_image_url"
},
"condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}
Read more about conditions and topics here on FCM documentation
EDIT: It appears that this method is not supported anymore (thx to #FernandoZamperin). Please take a look at the other answers!
Instead of subscribing to a topic you could instead make use of the condition key and send messages to instances, that are not in a group. Your data might look something like this:
{
"data": {
"foo": "bar"
},
"condition": "!('anytopicyoudontwanttouse' in topics)"
}
See https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2
One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.
I was looking solution for my Ionic Cordova app push notification.
Thanks to Syed Rafay's answer.
in app.component.ts
const options: PushOptions = {
android: {
topics: ['all']
},
in Server file
"to" => "/topics/all",
Check your topic list on firebase console.
Go to firebase console
Click Grow from side menu
Click Cloud Messaging
Click Send your first message
In the notification section, type something for Notification title and Notification text
Click Next
In target section click Topic
Click on Message topic textbox, then you can see your topics (I didn't created topic called android or ios, but I can see those two topics.
When you send push notification add this as your condition.
"condition"=> "'all' in topics || 'android' in topics || 'ios' in topics",
Full body
array(
"notification"=>array(
"title"=>"Test",
"body"=>"Test Body",
),
"condition"=> "'all' in topics || 'android' in topics || 'ios' in topics",
);
If you have more topics you can add those with || (or) condition, Then all users will get your notification. Tested and worked for me.
Just make all users who log in subscribe to a specific topic, and then send a notification to that topic.
For anyone wondering how to do it in cordova hybrid app:
go to index.js -> inside the function onDeviceReady() write :
subscribe();
(It's important to write it at the top of the function!)
then, in the same file (index.js) find :
function subscribe(){
FirebasePlugin.subscribe("write_here_your_topic", function(){
},function(error){
logError("Failed to subscribe to topic", error);
});
}
and write your own topic here -> "write_here_your_topic"
It is a PHP Admin-SDK example to subscribe an user to a Topic and to send messages to a device by device token or to a Topic. Note that the Topic is created automatically when you subscribe an user.
$testTokens = ['device token 1', 'device token 2', ....]
// CREDENTIALS, YOU HAVE TO DOWNLOAD IT FROM FIREBASE CONSOLE.
$factory = (new Factory())->withServiceAccount('credentials.json');
$messaging = $factory->createMessaging();
// Subscribe a token or a group of tokens to a topic (this topic is created automatically if not exists)
// YOU CAN DO THIS IN THE MOBILE APP BUT IS BETTER DO IT IN THE API.
$result = $messaging->subscribeToTopic('all', $testTokens); // 'all' is the topic name
// Send a message to a specific Topic (Channel)
$message = CloudMessage::withTarget('topic', 'all')
->withNotification(Notification::create('Global message Title', 'Global message Body'))
->withData(['key' => 'value']); // optional
$messaging->send($message);
// Send a message to a token or a grup of tokens (ONLY!!!)
foreach($testTokens as $i=>$token){
$message = CloudMessage::withTarget('token', $token)
->withNotification(Notification::create('This is the message Title', 'This is the message Body'))
->withData(['custom_index' => $i]); // optional
$messaging->send($message);
You can check this repo for more details: firebase-php-admin-sdk
Your can send notification to all devices using "/topics/all"
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/all",
"notification":{ "title":"Notification title", "body":"Notification body", "sound":"default", "click_action":"FCM_PLUGIN_ACTIVITY", "icon":"fcm_push_icon" },
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}

Google pub/sub subscription data doesn't match with the app

I'm trying to listen for subscription changes (new and existing) of my Google Play app on the server. Here's the code I'm using. This uses the google/cloud-pubsub composer package:
$projectId = 'app-name';
$keyFile = file_get_contents(storage_path('app/app-name.json'));
$pubsub = new PubSubClient([
'projectId' => $projectId,
'keyFile' => json_decode($keyFile, true)
]);
$httpPostRequestBody = file_get_contents('php://input');
$requestData = json_decode($httpPostRequestBody, true);
info(json_encode($requestData));
$message = $pubsub->consume($requestData);
info(json_encode($message));
The code above works but the problem is that the data I get doesn't match the one I'm getting in the app side. This is a sample data:
{
"message":{
"data":"eyJ2ZXJ...",
"messageId":"16797998xxxxxxxxx",
"message_id":"1679799xxxxxxxxx",
"publishTime":"2020-12-15T02:09:23.27Z",
"publish_time":"2020-12-15T02:09:23.27Z"
},
"subscription":"projects\/app-name\/subscriptions\/test-subs"
}
If you base64_decode() the data, you'll get something like this:
{
version: "1.0",
packageName: "com.dev.app",
eventTimeMillis: "1607997631636",
subscriptionNotification: {
version: "1.0",
notificationType: 4,
purchaseToken: "kmloa....",
subscriptionId: "app_subs1"
}
}
This is where I'm expecting the purchaseToken to be the same as the one I'm getting from the client side.
Here's the code in the client-side. I'm using Expo in-app purchases to implement subscriptions:
setPurchaseListener(async ({ responseCode, results, errorCode }) => {
if (responseCode === IAPResponseCode.OK) {
const { orderId, purchaseToken, acknowledged } = results[0];
if (!acknowledged) {
await instance.post("/subscribe", {
order_id: orderId,
order_token: purchaseToken,
data: JSON.stringify(results[0]),
});
finishTransactionAsync(results[0], true);
alert(
"You're now subscribed! You can now use the full functionality of the app."
);
}
}
});
I'm expecting the purchaseToken I'm extracting from results[0] to be the same as the one the Google server is returning when it pushes the notification to the endpoint. But it doesn't.
Update
I think my main problem is that I'm assumming all the data I need will be coming from Google Pay, so I'm just relying on the data published by Google when a user subscribes in the app.
This isn't actually the one that publishes the message:
await instance.post("/subscribe")
It just updates the database with the purchase token. I can just use this to subscribe the user but there's no guarantee that the request is legitimate. Someone can just construct the necessary credentials based on an existing user and they can pretty much subscribe without paying anything. Plus this method can't be used to keep the user subscribed. So the data really has to come from Google.
Based on the answer below, I now realized that you're supposed to trigger the publish from your own server? and then you listen for that? So when I call this from the client:
await instance.post("/subscribe", {
purchaseToken
});
I actually need to publish the message containing the purchase token like so:
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$topic = $pubsub->topic($topicName);
$message = [
'purchaseToken' => request('purchaseToken')
];
$topic->publish(['data' => $message]);
Is that what you're saying? But the only problem with this approach is how to validate if the purchase token is legitimate, and how to renew the subscription in the server? I have a field that needs to be updated each month so the user stays "subscribed" in the eyes of the server.
Maybe, I'm just overcomplicating things by using pub/sub. If there's actually an API which I could pull out data from regularly (using cron) which allows me to keep the user subscription data updated then that will also be acceptable as an answer.
First of all - I have a really bad experience with php and pubsub because of the php PubSubClient. If your script is only waiting for push and checking the messages then remove the pubsub package and handle it with few lines of code.
Example:
$message = file_get_contents('php://input');
$message = json_decode($message, true);
if (is_array($message)) {
$message = (isset($message['message']) && isset($message['message']['data'])) ? base64_decode($message['message']['data']) : false;
if (is_string($message)) {
$message = json_decode($message, true);
if (is_array($message)) {
$type = (isset($message['type'])) ? $message['type'] : null;
$data = (isset($message['data'])) ? $message['data'] : [];
}
}
}
I'm not sure how everything works on your side but if this part publishes the message:
await instance.post("/subscribe", {
order_id: orderId,
order_token: purchaseToken,
data: JSON.stringify(results[0]),
});
It looks like it's a proxy method to publish your messages. Because payload sent with it is not like a PubSub described schema and in the final message it doesn't look like IAPQueryResponse
If I was in your situation I will check few things to debug the problem:
How I publish/read a message to/from PubSub (topic, subscription and message payload)
I will write the publish mechanism as it is described in Google PubSub publish documentation
I will check my project, topic and subscription
If everything is set-up correctly then I will compare all other message data
If the problem persist then I will try to publish to PubSub minimal amount of data - just purchaseToken at the start to check what breaks the messages
For easier debug:
Create pull subscription
When you publish a message check pull subscription messages with "View messages"
For me the problem is not directly in PubSub but in your implementation of publish/receiving of messages.
UPDATE 21-12-2020:
Flow:
Customer create/renew subscription
Publish to pubsub with authentication
PubSub transfers the message to analysis application via "push" to make your analysis.
If you need information like:
New subscribers count
Renews count
Active subscriptions count
You can create your own analysis application but if you need something more complicated then you have to pick a tool to met your needs.
You can get the messages from pubsub also with "pull" but there are few cases I've met:
Last time I've used pull pubsub returns random amount of messages - if my limit is 50 and I have more than 50 messages in the queue I'm expecting to get 50 messages but sometimes pubsub gives me less messages.
PubSub returned messages in random order - now there is an option to use ordering key but it's something new.
To implement "pull" you have to run crons or something with "push" you receive the message as soon as possible.
With "pull" you have to depend on library/package (or whatever in any language it's called) but on "push" you can handle the message with just few lines of code as my php exapmle.

Push notification overrides previous notifications

I'm using codeigniter-gcm library on top of codeigniter to send messages to Google Cloud Messaging service. It sends the message and the message is received at the mobile device, but if I send multiple messages, only the latest message appears on the device (as if it is overriding the previous messages).
I'm seeing that I might need to create a unique notification ID, but I'm not seeing how it's done anywhere on the codeigniter-gcm documentation or Google's documentation for downstream messages.
Any idea how this should be done?
Here's my code in the codeigniter controller. It is worth mentioning that Google's response contains a different message_id for each time I send a push...
public function index() {
$this->load->library("gcm");
$this->gcm->setMessage("Test message sent on " . date("d.m.Y H:i:s"));
$this->gcm->addRecepient("*****************");
$this->gcm->setData(array(
'title' => 'my title',
'some_key' => 'some_val'
));
$this->gcm->setTtl(false);
$this->gcm->setGroup(false);
if ($this->gcm->send())
echo 'Success for all messages';
else
echo 'Some messages have errors';
print_r($this->gcm->status);
print_r($this->gcm->messagesStatuses);
}
After three exhausting days I found the solution. I'm posting it here in hope of saving someone else's time...
I had to add a parameter to the data object inside the greater JSON object, named "notId" with a unique integer value (which I chose to use a random integer from a wide range). Now why Google didn't include this in their docs? Beats me...
Here's how my JSON looks now, when it creates separate notifications instead of overriding:
{
"data": {
"some_key":"some_val",
"title":"test title",
"message":"Test message from 30.09.2015 12:57:44",
"notId":14243
},
"registration_ids":["*******"]
}
Edit:
I'm now thinking that the notId parameter is not really determined by Google, but by a plugin I use on the mobile app side.
To extend further on my environment, my mobile app is developed using Phonegap, so to get push notification I use phonegap-plugin-push which I now see in its docs that parameter name.
I'm kinda' lost now as far as explaining the situation - but happy it is no longer a problem for me :-)
You need to pass a unique ID to each notification. Once you have clicked on the notification you use that ID to remove it.
...
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID_A);
...
But I'm sure you shouldn't have so much of notifications for user at once. You should show a single notification that consolidates info about group of events like for example Gmail client does. Use Notification.Builder for that purpose.
NotificationCompat.Builder b = new NotificationCompat.Builder(c);
b.setNumber(g_push.Counter)
.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.list_avatar))
.setSmallIcon(R.drawable.ic_stat_example)
.setAutoCancel(true)
.setContentTitle(pushCount > 1 ? c.getString(R.string.stat_messages_title) + pushCount : title)
.setContentText(pushCount > 1 ? push.ProfileID : mess)
.setWhen(g_push.Timestamp)
.setContentIntent(PendingIntent.getActivity(c, 0, it, PendingIntent.FLAG_UPDATE_CURRENT))
.setDeleteIntent(PendingIntent.getBroadcast(c, 0, new Intent(ACTION_CLEAR_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSound(Uri.parse(prefs.getString(
SharedPreferencesID.PREFERENCE_ID_PUSH_SOUND_URI,
"android.resource://ru.mail.mailapp/raw/new_message_bells")));

Quickbooks integration (intranet)

I need to integrate vTiger CRM with Quickbooks 2010. So it is PHP. QB server and Linux box running vTiger are sitting in the same office. I try to figure out if there is a way to make PHP talk directly to QB server without using web connector. We need real time data access. Not like real 'real time', but report needs to be generated in like 5-30 seconds. Only reading of data, no writing. Any way to send/receive qbXML directly to QB server?
Thanks in advance.
Michael
This can be done... but be aware that QuickBooks isn't always the most reliable piece of software to integrate with for real-time data access - connections to QuickBooks tend to be both slow and fragile, which is why you usually see a queued model with the Web Connector.
What you could do is write a custom C# component (look at the examples included with the SDK, specifically this one: C:\Program Files (x86)\Intuit\IDN\QBSDK12.0\samples\qbdt\c-sharp\qbXML\CustomerAdd) which opens a connection to QuickBooks, and then does whatever.
"Whatever" might be something like:
Run a query against QuickBooks, and then HTTP POST the data back to vTiger
or
Open a socket and listen for incoming requests, in which case PHP could connect to the socket and feed the component requests which it could relay to QuickBooks, and then return the response
Be aware that generating a report in QuickBooks every 5 seconds is probably going to slow QuickBooks down considerably. Depending on how much data you're talking and what filters, it might not even be possible to get QuickBooks to generate a report that quickly.
Likewise, be aware that certain things cause connections to QuickBooks to fail, so you'll have to handle those gracefully. Specifically:
QuickBooks automatic updates will lock out integrated apps
If you have too many users logged in at once you'll get locked out
If someone else goes into single-user mode you'll get locked out
etc.
Maybe if you can provide more detail about why you need such frequent access to reports, we can provide some additional information.
Your code would look something like this:
while (true)
{
string input = "your fancy qbXML request goes here";
RequestProcessor2 rp = null;
string ticket = null;
string response = null;
try
{
rp = new RequestProcessor2 ();
rp.OpenConnection("", "Your App Name");
ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare );
response = rp.ProcessRequest(ticket, input);
}
catch( System.Runtime.InteropServices.COMException ex )
{
MessageBox.Show( "COM Error Description = " + ex.Message, "COM error" );
return;
}
finally
{
if( ticket != null )
{
rp.EndSession(ticket);
}
if( rp != null )
{
rp.CloseConnection();
}
};
// Do something with the response here
...
}

XMPPHP as live support chat

My idea is to integrate a live support chat on a website. The users text is send with xmpphp to my jabber client with the jabberbot sender id and if I answer, the jabber bot, takes my answer and transfers the text to the user.
There is only one problem. How do I separate different users or different chats? I don't want all users to see the answer, but the user who asks. Is there a kind of unique chat id or another possibility, that I might just missed?
User => Website => Chatbot => me
I want to answer and send it back to the user, but how can I find out the correct user from my answer?
Last time I have to solve this problem I used this architecture:
Entlarge image
The Webserver provides an JavaScript / jQuery or flash chat.
After chat is started, the client ask the server all 1 Second for new Messages.
Alternative for 1 Sec Polling
If that is to slow for you, have a look at websockets.
http://martinsikora.com/nodejs-and-websocket-simple-chat-tutorial
http://demo.cheyenne-server.org:8080/chat.html
But Websockets could no provided by php. There for you need to change php + apchache agaist node.js or java.
Plain HTTP PHP Methode
In PHP you will connect to the PsyBnc with is polling the messages from the supporter for you.
The PsyBnc is an IRC bot.
The reason why don't directly connect to XMPP or BitlBee is that those protocols don't like the flapping connect, disconnect from PHP. Because you can not keep the session alive, you need something that is made for often and short connects. This is the PsyBnc.
I would use something like this:
http://pear.php.net/package/Net_SmartIRC/download
<?php
session_start();
$message = $_GET['message'];
$client_name = $_GET['client_name'];
if (empty($_SESSION['chat_id'])) {
$_SESSION['chat_id'] = md5(time(). mt_rand(0, 999999));
}
if (empty($_SESSION['supporter'])) {
// how do you select the supporter?
// only choose a free?
// We send first message to all supporter and the first who grapped got the chat (where only 3 gues)
}
$irc_host = "127.0.0.1";
$irc_port = 6667; // Port of PsyBnc
$irc_password = "password_from_psy_bnc";
$irc_user = "username_from_psy_bnc";
include_once('Net/SmartIRC.php');
class message_reader
{
private $messages = array();
public function receive_messages(&$irc, &$data)
{
// result is send to #smartirc-test (we don't want to spam #test)
$this->messages[] = array(
'from' => $data->nick,
'message' => $data->message,
);
}
public function get_messages() {
return $this->messages;
}
}
$bot = &new message_reader();
$irc = &new Net_SmartIRC();
$irc->setDebug(SMARTIRC_DEBUG_ALL);
$irc->setUseSockets(TRUE);
$irc->registerActionhandler(SMARTIRC_TYPE_QUERY|SMARTIRC_TYPE_NOTICE, '^' . $_SESSION['chat_id'], $bot, 'receive_messages');
$irc->connect($irc_host, $irc_port);
$irc->login($_SESSION['chat_id'], $client_name, 0, $irc_user, $irc_password);
$irc->join(array('#bitlbee'));
$irc->listen();
$irc->disconnect();
// Send new Message to supporter
if (!empty($message)) {
$irc->message(SMARTIRC_TYPE_QUERY, $_SESSION['supporter'], $message);
}
echo json_encode(array('messages' => $bot->get_messages()));
Connect the support instant messanger to PHP
We have allready an IRC connection to the PsyBnc, now we need to send messages from IRC to ICQ, XMPP, GOOGLE TALK, MSN, YAHOO, AOI...
Here for is a nice solution named BitlBee.
BitlBee offers an IRC Server with can transfer message from and to nearly all instant messager protocols. By aliasing those accounts. For example you need for your system only 1 Server account at google talk, icq ... and at all your supporter to the buddylist of those accounts. Now BitleBee will provide your boddylist as an irc chat.
Your requirements are rather confusing. As Joshua said, you don't need a Jabber bot for this. All you need is a Jabber server - which you should already have. What you do is, you create a volatile user account sessionid#*yourdomain.com* whenever the chat feature is used and then you can just reply to any incoming message like normal while your website client can fetch the messages meant for it whenever.
Alternatively you could create one user account - qa#yourdomain.com - and use XMPP resource identifiers for the routing part. XMPP allows for something like qa#yourdomain.com/*sessionid* and you should be able to tell your XMPP library to only query a specific resource. Most XMPP client software will also reply to a specific resource by default and open a new conversation when applicable. This method is less "clean" than the first, but it would work somewhat better if you can't arbitrarily create user accounts for some reason.
I don't know what XMPP server you are using, but you could also try the Fastpath plugin and webchat for Openfire. Which is meant to provide a support team service over XMPP.
That being said, your question itself seems to imply nothing more than the standard chat feature of XMPP, which is between two users. It just means that the support person has a unique chat with each user asking a question. No other user will see that conversation.

Categories