Connecting Zapier with PHPMailer Script - php

I'm using Zapier to collect leads from facebook,and than send them to my CRM.
I Have a script connected to my CRM,that is supposed to handle the leads.
for every new lead the script will trigger,
the script collects the data passed from Zapier and converts it to an XML and sends it my client.
Everything works except for one thing.
The PHPMailer seems to cause trouble with zapier,because whenever the email() function is enabled Zapier will give me an Error.
FYI - this works when I go to the script url and set the GET parameters by hand .
the xml is being sent. But when triggering the script from zapier the problem occurs.
Zapier Error:
"We had trouble sending your test through.
The app returned "Internal Server Error" with no further details. It looks like the server for your connected app is down or currently experiencing problems. Please check the app's status page or contact support if there are no reported issues."
<?php
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
$lastName = isset($_GET['lastName']) ? $_GET['lastName'] : '';
$fullName = isset($_GET['fullName']) ? $_GET['fullName'] : '';
$phone = isset($_GET['phone']) ? $_GET['phone'] : '';
$experience = isset($_GET['experience']) ? $_GET['experience'] : '';
$city = isset($_GET['city']) ? $_GET['city'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
$utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : '';
$campaignId = isset($_GET['campaignId']) ? $_GET['campaignId'] : '';
$utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : '';
require 'vendor/autoload.php';
header('Content-Type: text/plain');
function createXML($data,$dataSource){
$dom = new DOMDocument('1.0', 'utf-8');
$cv = $dom->createElement("cv");
$candidate = $dom->createElement('candidate');
$source_type = $dom->createElement('source_type');
function recursive($dom, $parent, $key, $value) {
if(is_array($value)) {
$new_parent = $dom->createElement($key);
foreach($value as $k => $v){
recursive($dom, $new_parent, $k, $v);
}
$parent->appendChild($new_parent);
} else {
$field = $dom->createElement($key, htmlspecialchars($value));
$parent->appendChild($field);
}
}
foreach($dataSource as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $source_type, $key, $value);
}
foreach($data as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $candidate, $key, $value);
}
// $cv->appendChild($candidate)
$cv->appendChild($candidate);
$cv->appendChild($source_type);
$dom->appendChild($cv);
$node = $cv->appendChild($source_type);
$node->setAttribute('type','other');
$dom->formatOutput = true;
return $dom;
}
$data = array(
"first_name" => filter_var($firstName, FILTER_SANITIZE_STRING),
"last_name" => filter_var($lastName, FILTER_SANITIZE_STRING),
"mobile" => filter_var($phone, FILTER_SANITIZE_STRING),
'email' => '',
'id' => '',
);
$dataSource = array(
"source_title" => filter_var($utm_source, FILTER_SANITIZE_STRING),
"first_name" => '',
"last_name" => '',
"mobile" => '',
"email" => '',
"employee_number" => '',
"department" => '',
"email" => '',
);
//problematic function
function email(){
global $xmlData;
$mail = new PHPMailer(true);
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - " . $today;
}
///////// IF I uncomment bellow,Zapier will give me the following error:
//We had trouble sending your test through.
//The app returned "Internal Server Error" with no further details.
//It looks like the server for your connected app is down or currently experiencing problems.
//Please check the app's status page or contact support if there are no reported issues.
//Uncomment bellow.
// email();
?>
I Expect for every Lead to send an email containing a XML.

Two key problems. Firstly, you're using SMTP, but you have not set Host to your mail server - so it won't work unless it's localhost - is that the case?
You're asking PHPMailer to throw exceptions (by passing true to the constructor), but you don't have a try/catch block wrapped around the calls to PHPMailer, so any errors will result in uncaught exceptions - which will give you exactly the symptom you're seeing. Try this:
function email()
{
global $xmlData;
$mail = new PHPMailer(true);
try {
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - ".$today;
} catch (Exception $e) {
echo 'Sending failed'.$e->getMessage();
}
}
Overall, the main thing is to debug one thing at a time - check that the email() function actually works independently before you start trying to do things that depend on it working, because otherwise you won't know which bit of the code is failing.
If you're using PHP 7.0 or later, you can simplify those initial checks for params by using the null coalesce operator. You can replace this:
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
with:
$firstName = $_GET['firstName'] ?? '';

Related

Telegram bot doesn't answer

I'm using the package of eleirbag89 http://eleirbag89.github.io/TelegramBotPHP to create my bot on telegram.
I'm having some issues on it, it doesn't answer me on telegram but the code is correct (it answered in the past and nothing has changed).
How can I debug the code to see if everything is good?
Could be a problem of SSL certificate?
This is the simple code I used to test the bot after the issue:
require '../vendor/autoload.php';
$BOT_TOKEN = "[bot:token]";
$telegram = new Telegram($BOT_TOKEN);
$result = $telegram->getData();
$text = $result['message']['text'];
$chat_id = $result['message']['chat']['id'];
if ($text == "/test") {
$msg = 'Test is good';
$content = array('chat_id' => $chat_id, 'text' => $msg);
$telegram->sendMessage($content);
}
But it doesn't answer me :(
$token = "Token";
$link01 = "https://api.telegram.org/bot".$token;
$updates = file_get_contents('php://input');
$updates = json_decode($updates, TRUE);
$msgID = $updates['message']['from']['id'];
$name = $updates['message']['from']['first_name'];
try this one.
Could be a problem of SSL certificate?
YES
You need to set webhook,
Only you can set webhook, If it is HTPS
Here is how to set web hook

Call to undefined method Google_Service_Gmail_Message::toSimpleObject()

I'm trying to develop a web application that send email throught Gmail API.
But I'm getting this error :
Call to undefined method Google_Service_Gmail_Message::toSimpleObject()
Here is my code :
// LOAD GOOGLE LIBRARY
$this->CI->load->library('master_google');
$this->CI->load->library('master_phpmailer');
$client = $this->CI->master_google->getClient($data);
$mail = $this->CI->master_phpmailer;
$mail->setFrom($data->sender_email, $data->sender_name);
$mail->addReplyTo($data->response_email, $data->response_name);
$mail->addAddress($data->email);
$mail->Subject = $data->subject;
$mail->msgHTML(htmlspecialchars_decode($data->body));
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$encoded_message = base64url_encode($mime);
// Gmail Message Body
**$message = new Google_Service_Gmail_Message();**
$message->setRaw($encoded_message);
// Send the Email
$service = new Google_Service_Gmail($client);
$email = $service->users_messages->send('me',$message);
if($email->getId()){
return array('stat' => true, 'msg' => '');
} else {
return array('stat' => false, 'msg' => '');
}
The error is generated on this line :
$message = new Google_Service_Gmail_Message();
Any help is appreciated.
I found what was the problem lol, I had a model with the same name : Google_model, I rename that to Mygoogle_model and it works :D
I think the method toSimpleObject() does not exist in your gmail-api class.

Send data from Google App Script to a php site

Trying to send data from Google App Script to a php site which sends an email from my database. For most of the date it is no problem I send it via the url(example.com/example.php?id=test&id2=test2&id3=test3).
For most of the data it is no problem except for the third parameter, the given value is way longer than the other two and may contain newlines as well. My idea was to send the third(or all values) as JSON object.
My Google AppScript code so far:
function sendData(){
var options = {'text' : 'A longer example text'} ;
try {
var url = "https://example.com/example.php?id1=test1&id2=test2&id3="+options;
var httpRequest = UrlFetchApp.fetch(url, options).getContentText();
}
catch(e){
Logger.log(e);
}
return;
}
My PHP code:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'ChromePhp.php';
$email = $_GET["id1"];
$name = $_GET["id2"];
$text = $_GET["id3"];
$json = json_decode($text, true);
ChromePhp::log($json->text);
if(strpos($text, "\n") !== FALSE) {
$text = str_replace("\n", "<br>", $text);
}
$replace_to_standard=[$name, $text];
$replace_standard =['nametochange', 'textochange'];
$delivery_added = str_replace($replace_standard, $replace_to_standard, file_get_contents('standardMail.html'));
echo "" . $delivery_added . "";
$m = new MailSender;
$m-> sendMail($email, $email, $delivery_added, "Mail All");
The chrome logger will log "null"
Any ideas?
Using an AJAX post as an example, you can use the POST capability of Google apps script to send a post request to your PHP file and process it using the $_POST function of PHP.
Try in you GAS:
var payload = {
'text' : 'A longer example text',
'email' : 'test#email.com'
};
var options = {
'method' : 'post',
'payload' : payload
};
//var text = String(jsonData.comment);
try {
var url = "https://etadres.nl/login/mailAll.php";
var httpRequest = UrlFetchApp.fetch(url, options).getContentText();
}
catch(e){
Logger.log(e);
}
Catch your POST request in PHP and edit it as follows:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'ChromePhp.php';
//Receive the RAW post data via the php://input IO stream.
$content = file_get_contents("php://input");
$email = $_POST["email"];
$text= $_POST["text"];
if(strpos($text, "\n") !== FALSE) {
$text = str_replace("\n", "<br>", $text);
}
$replace_to_standard=[$name, $text];
$replace_standard =['nametochange', 'textochange'];
$delivery_added = str_replace($replace_standard, $replace_to_standard, file_get_contents('standardMail.html'));
echo "" . $delivery_added . "";
$m = new MailSender;
$m-> sendMail($email, $email, $delivery_added, "Mail All");

Tabs not showing up in envelope created from template

I'm trying to create a embedded envelope based on a template. The problem I am having is that in the created envelope the tabs I have created are missing.
I searched around and found the role assignment and used that and still no luck. When I look at the XML the role is the same as the template as well as the routing order and ID.
I tried setting the template so that I can't delete any recipients and I get the error:
Uncaught SoapFault exception: [soap:Client] Required recipient in the template has not been provided. Recipient not satisfied for role, Signer, in template Test Form
Here is my PHP to create and send the envelope, a lot of this is code used from the documentation:
// Get the recipient from a post
$rcp1 = new Recipient(); // First recipient to put in recipient array
$rcp1->UserName = $_POST['Name'];
$rcp1->Email = $_POST['Email'];
$rcp1->Type = RecipientTypeCode::Signer;
$rcp1->ID = "1";
$rcp1->RoutingOrder = 1;
$rcp1->CaptiveInfo = new RecipientCaptiveInfo();
$rcp1->CaptiveInfo->ClientUserId = 1;
$rcp1->RoleName = "Signer";
$rcp1->RequireIDLookup = FALSE;
// Create Role Assignments
$assign = new TemplateReferenceRoleAssignment();
$assign->RecipientID = $rcp1->ID;
$assign->RoleName = $rcp1->RoleName;
// Use a server-side template
$templateRef = new TemplateReference();
$templateRef->TemplateLocation = TemplateLocationCode::Server;
$templateRef->RoleAssignments = $assign;
$templateRef->Template = "****";
// Construct the envelope info
$envInfo = new EnvelopeInformation();
$envInfo->AccountId = $AccountID;
$envInfo->Subject = "This is the Subject";
$envInfo->EmailBlurb = "I have no Idea What a blurb is";
// Send creates draft with all the template info
$createEnvelopeFromTemplatesparams = new CreateEnvelopeFromTemplates();
$createEnvelopeFromTemplatesparams->TemplateReferences = array($templateRef);
$createEnvelopeFromTemplatesparams->Recipients = array($rcp1);
$createEnvelopeFromTemplatesparams->EnvelopeInformation = $envInfo;
$createEnvelopeFromTemplatesparams->ActivateEnvelope = true;
$env = $api->CreateEnvelopeFromTemplates($createEnvelopeFromTemplatesparams);
$envStatus = $env->CreateEnvelopeFromTemplatesResult;
// Construct the recipient token authentication assertion and specify
// ID, start time, method, and domain
$assertion = new RequestRecipientTokenAuthenticationAssertion();
$assertion->AssertionID = guid();
$assertion->AuthenticationInstant = nowXsdDate();
$assertion->AuthenticationMethod = RequestRecipientTokenAuthenticationAssertionAuthenticationMethod::Password;
$assertion->SecurityDomain = "Request Recipient Token Test";
// Construct the URLs based on UserName
$recip = $envStatus->RecipientStatuses->RecipientStatus[0];
$urls = new RequestRecipientTokenClientURLs();
$urlbase = getCallbackURL('pop.php');
$urls->OnSigningComplete = $urlbase . "?event=SignComplete&uname=" . $recip->UserName;
$urls->OnViewingComplete = $urlbase . "?event=ViewComplete&uname=" . $recip->UserName;
$urls->OnCancel = $urlbase . "?event=Cancel&uname=" . $recip->UserName;
$urls->OnDecline = $urlbase . "?event=Decline&uname=" . $recip->UserName;
$urls->OnSessionTimeout = $urlbase . "?event=Timeout&uname=" . $recip->UserName;
$urls->OnTTLExpired = $urlbase . "?event=TTLExpired&uname=" . $recip->UserName;
$urls->OnIdCheckFailed = $urlbase . "?event=IDCheck&uname=" . $recip->UserName;
$urls->OnAccessCodeFailed = $urlbase . "?event=AccesssCode&uname=" . $recip->UserName;
$urls->OnException = $urlbase . "?event=Exception&uname=" . $recip->UserName;
// Send
$requestRecipientTokenparams = new RequestRecipientToken();
$requestRecipientTokenparams->EnvelopeID = $envStatus->EnvelopeID;
$requestRecipientTokenparams->ClientUserID = $recip->ClientUserId;
$requestRecipientTokenparams->Username = $recip->UserName;
$requestRecipientTokenparams->Email = $recip->Email;
$requestRecipientTokenparams->AuthenticationAssertion = $assertion;
$requestRecipientTokenparams->ClientURLs = $urls;
$response = $api->RequestRecipientToken($requestRecipientTokenparams);
$tokenUrl = $response->RequestRecipientTokenResult;
echo '<iframe src="' . $tokenUrl . '" width="100%" height="720px"></iframe>';
This is the recipient info that is returned when I RequestTemplate():
[0] => Recipient Object
(
[ID] => 1
[UserName] =>
[SignerName] =>
[Email] =>
[Type] => Signer
[AccessCode] =>
[AddAccessCodeToEmail] =>
[RequireIDLookup] =>
[IDCheckConfigurationName] =>
[PhoneAuthentication] =>
[SignatureInfo] =>
[CaptiveInfo] =>
[CustomFields] =>
[RoutingOrder] => 1
[IDCheckInformationInput] =>
[AutoNavigation] =>
[RecipientAttachment] =>
[Note] =>
[RoleName] => Signer
[TemplateLocked] =>
[TemplateRequired] => 1
[TemplateAccessCodeRequired] =>
[DefaultRecipient] =>
[SignInEachLocation] =>
)
This might be due to you instatiating the templateRoleAssignments as an object and not an array. Since you're using the SOAP api and not REST have you seen the DocuSign SOAP SDK up on Github? That has sample code and projects for 5 different environments including PHP (PHP, Java, C#, Ruby, and Salesforce):
https://github.com/docusign/DocuSign-eSignature-SDK
Looking at a function defined in the PHP project I see the following:
function createFinalRoleAssignments($recipients) {
$roleAssignments[] = new TemplateReferenceRoleAssignment();
foreach ($recipients as $r) {
$assign = new TemplateReferenceRoleAssignment();
$assign->RecipientID = $r->ID;
$assign->RoleName = $r->RoleName;
array_push($roleAssignments, $assign);
}
// eliminate 0th element
array_shift($roleAssignments);
return $roleAssignments;
}
Notice how $roleAssignments is declared as an array using square brackets [], I have a strong feeling that is causing your error. Try defining your roleAssignments the same way and that will probably work.

PHP Mail function not working on Web Services

I am using two different servers for dev site and live site. My webservice function to send email confirmation is working on Dev Site but it is not working in Live Site. My
email confirmation function is:
function getEmailConfirmation($UserName, $ChecklistID,$UserID,$AnswerBulkID, $TotalSubmitted){
if ( ($UserID == '') || (!isset($UserID)) ) {
return error("partial");
}
$entry = new Entry();
$entry_date_check = date('Y-m-d'); //for check if already
$count_tbl_answers = $entry->listEntry("SELECT count(*) as total_from_answers FROM tbl_answers where user_id='".$UserID."' and answer_bulk_id ='".$AnswerBulkID."' and date(ent_date) = '".$entry_date_check."' ");
$to = "****#gmail.com";
$subject = "TDL Checklist email";
$message = "Hello there! \n User ID: ".$UserID." \n User Name: ".$UserName."\n Check List ID: ".$ChecklistID."\n Answer Bulk ID: ".$AnswerBulkID;
$from = "TLD-Email-Confirmation";
$headers = "From:" . $from;
if(($count_tbl_answers[0]['total_from_answers']) == $TotalSubmitted){
mail($to,$subject,$message,$headers);
$result = array(
"user_id" => $UserID,
"user_name" => $UserName,
"check_list_id" => $ChecklistID,
"answer_bulk_id" => $AnswerBulkID,
);
} else{
$delete_bulk = $entry->query("delete FROM tbl_answerbulk WHERE user_id ='".$UserID."' and check_list_id ='".$ChecklistID."' and id ='".$AnswerBulkID."' ");
$delete_answer = $entry->query("delete FROM tbl_answers WHERE user_id='".$UserID."' and answer_bulk_id ='".$AnswerBulkID."' ");
return error("custom","","Could not submit your answer this time. Please try again later.");
}
$message = json_encode(
$result
);
$fin_data['response'] = json_encode(array('Message'=>'ok','Data'=>$message));
return $fin_data;
}
This function works perfectly on dev server, but it does not work on live server. What might be the reason?
Note:
Although mail function not working on Live site, it returns the result array which is just after the mail function.
That is:
#mail($to,$subject,$message,$headers);
$result = array(
"user_id" => $UserID,
"user_name" => $UserName,
"check_list_id" => $ChecklistID,
"answer_bulk_id" => $AnswerBulkID,
);
I also tried ini_set('smtp_port', 587); and #mail($to,$subject,$message,$headers); but does not worked.

Categories