How can i recieve pushed message from google pubsub - publish-subscribe

I Have created new topic and new subscription and set delivery type: push and set end point URL :
index.php :
<?php
print_r($_POST);
$data = json_encode($_POST);
print_R($data);
$fp = fopen('data.txt', 'a+');
fwrite($fp, $data);
fclose($fp);
?>
When publish message i want to process the data from this end point as an example save data to file.
the file is created but with empty array [].
any issue in my php code, does the data store in $_POST or i need to use another way.

To fetch Pub/Sub messages, you need to use the Google Pub/Sub library. Given that you've set your subscription endpoint to your URL, the code should look like something similar to this:
use Google\Cloud\PubSub\PubSubClient;
$projectId = "YOUR-PROJECT-ID";
$subscriptionName = "YOUR-SUBSCRIPTION-NAME";
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$subscription = $pubsub->subscription($subscriptionName);
$pullMessages = [];
foreach ($subscription->pull(['returnImmediately' => true]) as $pullMessage) {
$pullMessages[] = $pullMessage;
$msg = $pullMessage->data();
$fp = fopen('data.txt', 'a+');
fwrite($fp, $msg);
fclose($fp);
}
// acknowledge PULL messages
if ($pullMessages) {
$subscription->acknowledgeBatch($pullMessages);
}
You can find an example here. As well as a more in-detail explanation here.

Related

Newbie on Fb messenger Sender_action function

I am under a learning process in chatbot, and kinda new to coding overall ( learning by doing right? )
Trying to execute a messenger function so our chatbot gets the little "writing" bubble for x amount of time before it sends a template. = sender_action_typing_on.
I have tried sleep, await, wait, and so on but the code doesn´t seem to be executed, but the template still shows after the time I chose.
The json is also correct by the documentation from Facebook, and if it get´s executed alone it runs for 20 sek before a timeout.
Code:
if ( $response == "")
{
$jsonData = '{"recipient":{"id":"' . $sender . '"},"message":{"text":"' . $message_to_reply.'"}}';
$jsonDataEncoded = $jsonData;
}
else
if ( $response == "123456")
{
$sender_action_typing_on = '{
"recipient":{
"id":"<PSID>"
},
"sender_action":"Typing_on"
}';
$sender_action_typing_on = str_replace("<PSID>", $sender, $sender_action_typing_on);
$jsonDataEncoded = $sender_action_typing_on;
$velkommenTemplateJSON = str_replace("<PSID>", $sender, $velkommenTemplateJSON);
$jsonDataEncoded = $velkommenTemplateJSON;
}
I have now fixed this issue, this may be very self-explaining for many but for the "lost soul" looking for answers u can see the way i dealed with the problem here:
First i created a new function:
function sendToMessenger($access_token, $sender, $sender_actiontemplateJSON)
{
$content = str_replace("<PSID>", $sender, $sender_actiontemplateJSON);
$opts = array(
'http'=>array(
'method'=>"POST",
'header' => "Content-Type: application/json",
'content' => $content
)
);
$context = stream_context_create($opts);
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=' . $access_token;
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
return $file;
Then i rearranged the way i´m sending template since the template got sent at det end of my code "Sender_action" would always be overwritten, Now with the "SendToMessenger" Function it gets sent right away.
else
if ( $response == "123456")
{
sendToMessenger($access_token, $sender, $sender_actiontemplateJSON);
sleep(1);
sendToMessenger($access_token, $sender, $velkommenTemplateJSON);
}
Now it works like a charm!

PHP mail function not working

I do not think the problem lies with the mail function code, but with my aproach of the $_SESSION variables. I have a form consisting of 5 pages, the fifth being a preview page. Upon the final submission, on the preview page, i want the entire $_SESSION data to be sent to two different email adresses.
I am displaying the data on the preview page as follows:
<?php
//retrieve session data
echo "<b> Varname: </b>". $_SESSION['varname'];
?>
in a form with method="post" and action="mail.php".
In the mail.php, i start the session, and then:
$_SESSION['email'] = $mail;
$_SESSION['varname'] = $varname;
$email_from = 'mail#company.de';
$email_subject = "Mail";
$email_body = "You have submitted the following data: $inhalt.\n";
$to = "mymail#company.de, $mail";
$headers = "From: Company";
mail($to,$email_subject,$email_body,$headers);
Upon submitting the form the page goes to blank. What exactly am i doing wrong?
I managed to solve the problem in the end, as follows:
$email_from = 'mail#company.de';
$email_subject = "Mail";
$to = ("myadress#work.de," . $_SESSION['email'] . "");
mail($to,"Form submission","Form data:
Inhalt: " . $_SESSION['inhalt1'] . "
");
As I said in the question, the problem was my aproach of the $_SESSION variables. Instead of $_SESSION['varname'] = $varname, i just went directly with . $_SESSION['varname'] .´.

CodeIgniter: Cannot redirect after $this->email->send()

i have the following code which sends an email from a posted form:
$this->load->library('email');
$config['charset'] = 'iso-8859-1';
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('info#mysite.com', 'Scarabee');
$this->email->to('info#mysite.com');
$this->email->subject('Message via website');
$data['msg'] = nl2br($this->input->post('msg'));
$data['msg'] .= '<br><br><b>Verstuurd door:</b><br>';
if($this->input->post('bedrijf')){
$data['msg'] .= $this->input->post('bedrijf').'<br>';
}
$data['msg'] .= $this->input->post('naam').'<br>';
$data['msg'] .= $this->input->post('adres').' - '.$this->input->post('postcode').', '.$this->input->post('gemeente').'<br>';
$data['msg'] .= $this->input->post('tel').'<br>';
$data['msg'] .= $this->input->post('email');
$message = $this->load->view('email', $data, TRUE);
$this->email->message($message);
if($this->email->send()){
$success = 'Message has been sent';
$this->session->set_flashdata('msg', $success);
redirect('contact/'.$this->input->post('lang'));
}
else{
show_error('Email could not be sent.');
}
Problem: the email gets sent with proper formatting (from the email view template), but the page then goes blank. For instance, if I try to echo out $message just below the $this->email->send() call, nothing shows up. Redirecting, as I’m attempting above, obviously doesn’t work either. Am I missing something? Thanks for any help…
Update
Traced the problem down to a function inside /system/libraries/Email.php (CI's default email library). Commenting out the code inside this function allows the mail to get sent, as well as a proper redirect:
protected function _set_error_message($msg, $val = '')
{
$CI =& get_instance();
$CI->lang->load('email');
if (substr($msg, 0, 5) != 'lang:' || FALSE === ($line = $CI->lang->line(substr($msg, 5))))
{
$this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
}
else
{
$this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
}
}
The line that caused the error is: $CI->lang->load('email');
Go figure...
UPDATE 2: SOLVED
I had this in my controller's construct:
function __construct() {
parent::__construct();
$this->lang = $this->uri->segment(2, 'nl');
}
I guess there was a conflict between $this->lang and the _set_error_message function which also returns a "lang" variable (see var_dump further down).
Solution: changed $this->lang to $this->language, and everything's hunky dory!
Thought I'd post the answer here in case anyone else is ever losing hair with a similar problem :-)
It's likely that an error is occurring when you attempt to send an e-mail which is then killing your script during execution. Check your apache and PHP error logs ( /var/log/apache/ ) and enable full error reporting.
You could, for debugging purposes, try doing this:
...
$this->email->message($message);
$this->email->send();
redirect('contact/'.$this->input->post('lang'));
This should redirect you, regardless of your mail being sent or not (if you still recieve it, you can assume that the redirect would be the next thing that happens).
My own solution looks like this:
...
if ( $this->email->send() )
{
log_message('debug', 'mail library sent mail');
redirect('contact/thankyou');
exit;
}
log_message('error', 'mail library failed to send');
show_error('E-mail could not be send');
$ref2 = $this->input->server('HTTP_REFERER', TRUE);
redirect($ref);
By using the above code you can redirect to the current page itself
and you can set your flash message above the redirect function.

PEAR Mail, Mail_Mime and headers() overwrite

I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.
Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.
To be exact: The problem is
$mime->headers($headers, true);
As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.
I'm really going crazy about this thing... any suggestions?
(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)
Code:
// sql query and if num_rows > 0 ....
require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');
ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();
ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();
$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;
$mail =& Mail::factory('smtp', $XY['mail']['params']);
$headers = array();
$headers['From'] = 'XY <service#XY.at>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <service#XY.at>';
ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();
$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
$html = $head . $template . $foot;
$mime->setHTMLBody($html);
#$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to webmaster#XY.at
$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <webmaster#XY.at>';
$headers['To'] = $to; // Sets to in headers to a new
$body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
$hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user
$sent = $mail->send($to, $hdrs, $body);
if (PEAR::isError($sent)) {
errlog('error while sending to user_id: '.$row['id']); // personal error function
} else {
// Write log file
}
}
There is no reason to keep the old object and not creating a new one.
Use OOP properly and create new objects - you do not know how they work internally.

Sending a SOAP message with PHP

what I'm trying to do is send a load of values captured from a form to a CRM system with SOAP and PHP. I've been reading up on SOAP for a while and I don't understand how to go about doing so, does anybody else know?
In order to do this it might be easiest to download a simple soap toolkit like 'NuSOAP' from sourceforge.
And then you would code something like the following (example submission of ISBN number):
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
This code snippet was taken directly from, which is also a good resource to view
http://developer.apple.com/internet/webservices/soapphp.html
Hope this helps.
You probably found a solution since then - but maybe the following helps someone else browsing for this:
soap-server.php:
<?php
class MySoapServer {
public function getMessage ()
{
return "Hello world!";
}
public function add ($n1,$n2)
{
return $n1+n2;
}
}
$option = array ('uri' => 'http://example.org/stacky/soap-server');
$server = new SoapServer(null,$option);
$server->setClass('MySoapServer');
$server->handle();
?>
and soap-client.php
<?php
$options = array ('uri' => 'http://example.org/stacky/soap-server',
'location' => 'http://localhost/soap-server.php');
$client = new SoapClient(null,$options);
echo $client ->getMessage();
echo "<br>";
echo $client ->add(41,1);
?>