Pubnub PHP Subscribe Function - php

I need major help!
I am having troubles getting the Pubnub subscribe function to work with PHP! I can get the publish function to work, but not the subscribe function. I have copied some code straight from the Pubnub site, but I am not getting anything. Any help? Also, my PHP version is 5.2.*.
Code:
<?
include("Pubnub.php");
$pubnub = new Pubnub(
"not showing you", // PUBLISH_KEY
"not showing you", // SUBSCRIBE_KEY
"", // SECRET_KEY
false // SSL_ON?
);
$pubnub->subscribe(array(
'channel' => 'Chat',
'callback' => create_function(
'$message',
'var_dump($message); return true;'
)
));
?>

⚠️ ALERT: SDK has been upgraded ⚠️
New SDK URL: https://github.com/pubnub/php
You are asking about a way to use the Subscribe method within a web server like Apache using PHP as the dynamic processing language. Note that this is not a good practice and generally not necessary to do. You would not use the Subscribe({...}) method in a request/response.
The correct way to utilize the $pubnub->subscribe(...) method is in a long-lived PHP process, not involving a web server request-response model. Here are some examples that are confirmed to work:
https://github.com/pubnub/php
Note that each example is assumed to be in a solitary PHP process outside of a web server like Apache when using the Subscribe API in PHP. However! The Publish() API can be used anywhere, including an Apache web server.
Reading History w/ Apache PHP
As an alternative you will be happy to take advantage of our HISTORY API. You can query messages in the Queue with this and receive messages. Here is an example PHP History API usage:
<?php
## Capture Publish and Subscribe Keys from Command Line
$publish_key = "YOUR_PUBLISH_KEY";
$subscribe_key = "YOUR_SUBSCRIBE_KEY";
## Require Pubnub API
require('../Pubnub.php');
## -----------------------------------------
## Create Pubnub Client API (INITIALIZATION)
## -----------------------------------------
$pubnub = new Pubnub( $publish_key, $subscribe_key );
## Get History
echo("Requesting History...\n");
$messages = $pubnub->history(array(
'channel' => 'hello_world', ## REQUIRED Channel to Send
'limit' => 100 ## OPTIONAL Limit Number of Messages
));
var_dump($messages); ## Prints Published Messages.
?>

The php subscribe function is broken and will be fixed in a new upcoming api, I talked with support recently about this and they gave me the this information.

Related

Service Account Domain Delegation unauthorized_client

I am trying to use service account with domain delegation so I can automate some tasks of google classroom via cron. For this I need service account with domain delegation.
I am working and struggling in it for 3 days. I have properly read documentation so many times. You can imagine the 3 days research. Now I am getting exhaust and finally come here in the hope.
I am using php library provided by google for google classroom.
https://github.com/googleapis/google-api-php-client
I am getting this error
Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
Which means in google documentation enter image description here
I tried that several times but still getting this errror.
Here is my php code
require_once plugin_dir_path(__FILE__).'../../xf-google-classroom/vendor/autoload.php';
$this->scopes = [
Google_Service_Classroom::CLASSROOM_COURSES,
//Google_Service_Classroom::CLASSROOM_ROSTERS,
//Google_Service_Classroom::CLASSROOM_COURSES_READONLY,
//Google_Service_Classroom::CLASSROOM_COURSEWORK_ME,
//Google_Service_Classroom::CLASSROOM_COURSEWORK_ME_READONLY,
//Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS,
Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY,
//Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS,
];
$this->credentials = plugin_dir_path(__FILE__) . '/sufi-new-2.json';
//$this->redirect_uri = site_url( 'wp-admin/admin.php?page=bp-groups' );
$this->client = new Google_Client();
//$this->client->useApplicationDefaultCredentials();
$jsonKey = [
"type"=> "service_account",
"project_id"=> "edufix-upgraded",
"client_email"=> "newsufyan#edufix-upgraded.iam.gserviceaccount.com",
"client_id"=> "115746479435703189142",
"auth_uri"=> "https://accounts.google.com/o/oauth2/auth",
"token_uri"=> "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url"=> "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url"=> "https://www.googleapis.com/robot/v1/metadata/x509/newsufyan%40edufix-upgraded.iam.gserviceaccount.com"
];
$this->client->setAuthConfig( $jsonKey );
$this->client->setSubject('clases#krugerschool.edu.ec');
//$this->client->setRedirectUri( $this->redirect_uri );
$this->client->addScope( $this->scopes );
$this->client->setAccessType( 'offline' );
Let me tell you that my OAuth2 authentication with conscent screen application is working good on frontend for users. I am not able to run my cron scripts because of this domain delegation.
Also my OAuth Consent screen is in test mode and I have added test users in it. And working good with users on frontend with consent screen.
Also I always generate new key after any new changes and deploy that new credentials as well everytime. I tried to remove and add again with client id and proper scopes and domain delegation again and again but not working.
Also I have added that my administrator account in service account and grant access to owner. But not not worked.
Kindly help
I am trying to solve my problem and expecting a poper solution

DialogFlow - How to Batch Update Intents via API?

I'm looking for a basic example on how to utilize DialogFlow's batchUpdate, and how to utilize batchUpdateResponse to show an actual response once complete.
Have found no examples for DialogFlow V1 or V2 (at this point either would be helpful), the below is all I've managed to setup - looking for the missing arguments to be added:
$intentsClient->batchUpdateIntents($formattedParent, $languageCode, $test_3);
Currently using PHP https://github.com/googleapis/google-cloud-php/tree/83ae284c025f6e93b9ce835b987932c425b5a9de/Dialogflow but any language is fine here.
Ended up figuring this out through the use of https://developers.google.com/apis-explorer/ and the Google Client Library for PHP (https://github.com/googleapis/google-api-php-client).
Below is a basic example for updating the text on two intents at once, via PHP. Hopefully this helps someone in the future, am somewhat surprised at the general lack of helpful documentation and/or examples for using DialogFlow's API V2 (or even V1 for that matter). So many awesome things can be done by using this rather than their Dashboard to train your bot!
// Global variable pointing to the .json file downloaded with private key from DialogFlow
putenv('GOOGLE_APPLICATION_CREDENTIALS=directory-of-file/google-service-acount-key.json');
// Setup Google Client
require __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$httpClient = $client->authorize();
// Setup array to update intent (minified)
$update_intent = array('intentBatchInline'=>array('intents'=>array(
0=>array('name'=>'projects/YOUR-PROJECT-NAME/agent/intents/FIRST-INTENT-ID','displayName'=>'FIRST-INTENT-NAME','messages'=>array(0=>array('text'=>array('text'=>array(0=>'FIRST-INTENT-TEXT-TO-UPDATE',),),),),),
1=>array('name'=>'projects/YOUR-PROJECT-NAME/agent/intents/SECOND-INTENT-ID','displayName'=>'SECOND-INTENT-NAME','messages'=>array(0=>array('text'=>array('text'=>array(0=>'SECOND-INTENT-TEXT-TO-UPDATE',),),),),),),),
);
// Post to DialogFlow API
$response = $httpClient->post('https://dialogflow.googleapis.com/v2/projects/PROJECT-NAME-HERE/agent/intents:batchUpdate', [
GuzzleHttp\RequestOptions::JSON => $test_batch_intent_1
]);
// Print out response for troubleshooting
print_r($response->getBody()->getContents());
echo "<br /><br />Here's to getting past DialogFlow API's hurdles! :)";
exit;
This is similar to my answer. Where I have given a complete example. Do check it out.
Stack Overflow answer.
And this is based out of NodeJs. As you told the language does not matter.
And do check out this documentation for different kinds of examples. This document covers even the batchUpdate functionality.
Please check these out:
GitHub repo
GitHub repo

What is correct Twilio AddOns syntax for php REST client?

Beginner to both Twilio & php here:
I have: Twilio php helper, Twilio account, Whitepages Pro AddOn enabled for Lookups and have successfully retrieved "basic" lookup data, ie, "Carrier->Type" (the "basic" lookup does not use the AddOn)
I need: to use Twilio Rest Client with Whitepages Pro AddOn to retrieve other data, ie, "standard_address_line1", for an individual phone number. I do not want the $0.07 per call AddOn enabled for all incoming calls, although I was able to receive this data from the AddOn that way.
Twilio API Documentation is scant. Shows output format, but not REST Client request syntax: WhitePagesPro AddOn Documentation
Here is what I tried:
<?php
require 'vendor/autoload.php';
use Twilio\Rest\Client;
$client = new Client(ACxxxxxxxxxx,Tokenxxxxxxxx);
$number = $client->lookups
->phoneNumbers("+1xxxxxxxxxx")
->fetch(
array("AddOns" => "whitepages_pro_caller_id")
);
echo $number->
results->
whitepages_pro_caller_id->
result->
results[0]->
associated_locations[0]->
standard_address_line1;
//This syntax works for 'basic' lookup
//Returns: "landline"
//
//$number = $client->lookups
// ->phoneNumbers("+1xxxxxxxxxx")
// ->fetch(
// array("type" => "carrier")
// );
//
//echo $number->carrier['type'];
?>
Throws error: Uncaught exception 'Twilio\Exceptions\TwilioException' with message 'Unknown property: results'
I'm way over my head, I don't know how to go about debugging this. Any Twilio experts?
Ideally I'd also like to know if it's possible to specify this particular data in the request vs traversing many levels of the response in order to get the data I need...
Twilio developer evangelist here.
You're very close with what you have there. The addOns results are actually returned in the addOns property of the number there. So, using your code, you can print the request SID of the call like this:
<?php
require 'vendor/autoload.php';
use Twilio\Rest\Client;
$client = new Client(ACxxxxxxxxxx,Tokenxxxxxxxx);
$number = $client->lookups
->phoneNumbers("+1xxxxxxxxxx")
->fetch(
array("AddOns" => "whitepages_pro_caller_id")
);
echo $number->addOns['results']['whitepages_pro_caller_id']['request_sid']
If you want to inspect the entire result, you can use var_dump to see the entire structure
var_dump($number->addOns['results']['whitepages_pro_caller_id'])
The structure will appear as it does in the documentation but it might be easier to see in the PHP output.
Let me know if that helps at all.

Send event to Google Analytics using API server sided

I have a website where I send events to Google Analytics using javascript function:
ga('send', 'event', 'showphone', 'feedback', 'result');
However I also need to send some similar events from server-side using PHP. I tried this quick start tutorial: Hello Analytics API: PHP quickstart for service accounts and reporting works like a charm, but I have no idea how to send event.
Could you please show me step-by-step what I should code to send exactly same event like mentioned above.
Hello Analytics API: PHP quickstart for service accounts is not going to help you at all. That code uses the core reporting API the core reporting API is for requesting data from Google Analytics not sending data to Google Analytics.
To send data to Google Analytics we use the Measurement Protocol. The measurement protocol is used to send information to Google analytics the JS snippet you posted also uses the measurement protocol.
You can use the measurement protocol from any language that supports HTTP post or Http Get. That being said there is no PHP specific library for sending information to Google analytics you are going to have to format your post yourself. A tip would be to use Validating hits to check it before you send it to Google while you are developing this.
It will probably look something like this
http://www.google-analytics.com/collect?v=1&tid=UA-XXX-Y&cid=35009a79-1a05-49d7-b876-2b884d0f825b&an=My%20Awesom%20APP&aid=com.daimto.awesom.app&av=1.0.0&aiid=come.daimto.awesom.installer &t=event&ec=list&ea=accounts&userclicked&ev=10
There is a PHP library php-ga-measurement-protocol by theiconic on github which can be used to send data using Measurement Protocal.
use TheIconic\Tracking\GoogleAnalytics\Analytics;
// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);
// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
->setProtocolVersion('1')
->setTrackingId('UA-26293728-11')
->setClientId('12345678')
->setDocumentPath('/mypage')
->setIpOverride("202.126.106.175");
// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();
Here is an example of how to do it with PHP.
First build your request with Google Analytics Hit Builder, test it with https://google-analytics.com/debug/collect?_query_here, and then send it with file_get_contents (see here).
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => 'v=1&t=transaction&tid=UA-xxxxxxx-x&cid=xxxxxx&ti=abcdef&tr=100&in=productname'
)
);
$context = stream_context_create($options);
$result = file_get_contents('https://www.google-analytics.com/collect', false, $context);

Implementing chat between webpage and android

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".

Categories