Mandrill API Error - php

First Time i used Mandrill API to send email,
But I got this error.
A mandrill error occurred: Mandrill_ValidationError - You must specify a key value
Fatal error: Uncaught exception 'Mandrill_ValidationError' with message 'You must specify a key value' in mandrill-api-php/src/Mandrill.php:153 Stack trace: #0 mandrill-api-php/src/Mandrill.php(132): Mandrill->castError(Array) #1 mandrill-api-php/src/Mandrill/Messages.php(80): Mandrill->call('messages/send', Array) #2 mandrill.php(88): Mandrill_Messages->send(Array, false) #3 {main} thrown in Mandrill.php on line 153
This is my code
<?php
require_once 'mandrill-api-php/src/Mandrill.php';
$servername = "localhost";
$username = "root";
$password = "";
$table = '';
$conn = mysql_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$selected = mysql_select_db("DB Name")
or die("Could not select database");
$query=mysql_query(Query);
$table .= "<table width='auto' height='auto' border='1' bordercolor='#003399' style='color:#FF0000;table-layout:fixed' cellpadding=0 cellspacing=0>
<tr>
<th>User ID</th>
<th>Full Name</th>
<th>Username</th>
<th>Email ID</th>
</tr>";
while($row = mysql_fetch_array($query))
{
$table .= "<tr>";
$table .= "<td>" . $row['id'] . "</td>";
$table .= "<td>" . $row['fullname'] . "</td>";
$table .= "<td>" . $row['username'] . "</td>";
$table .= "<td>" . $row['useremail'] . "</td>";
$table .= "</tr>";
}
$table .= "</table><br>";
try {
$mandrill = new Mandrill(API Key);
$message = array(
'html' => $table,
'subject' => 'Notification Email',
'from_email' => 'Example#example.com',
'from_name' => 'Test',
'to' => array(
array(
'email' => 'Example#example.com',
'name' => 'Test',
'type' => 'to'
)
),
'important' => false,
'track_opens' => null,
'track_clicks' => null,
'auto_text' => null,
'auto_html' => null,
'inline_css' => null,
'url_strip_qs' => null,
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
?>
'preserve_recipients' => null,
'view_content_link' => null,
'tracking_domain' => null,
'signing_domain' => null,
'return_path_domain' => null,
);
$async = false;
$result = $mandrill->messages->send($message, $async);
print_r($result);
}
catch(Mandrill_Error $e) {
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
throw $e;
}
?>

<pre>/*
Before coding, you have to make configurations in Mandrill.
Step 1: Enter Mandrill and register your domain.
Step 2: Configure DNS: DKIM and SPF (This is a good tutorial: https://www.youtube.com/watch?v=uEjP_smeLjU) at https://mandrillapp.com/settings/sending-domains
Step 3: Get a KEY API (https://mandrillapp.com/settings)
Step 4: Code with PHP
Step 5: Good luck! :)
*/
/*LIBS*/
include 'lib/mandrill-api-php/src/Mandrill.php';
$mandrill = new Mandrill('YOUR API KEY HERE');
/*ADMIN AND USER EMAIL*/
$admin_email = 'your_email#your_domain.com';
$client_email = 'the_email_of_the_client#mail.com';
/*attach PDF*/
$attachment = file_get_contents('the_route_to_your_pdf');
$attachment_encoded = base64_encode($attachment);
try{
$user_message = array(
'subject' => 'Your Subject here',
'from_email' => $admin_email,
'from_name' => 'your_domain_for_example',
'html' => '<p>AquĆ­ va la plantilla HMTL</p>',
'to' => array(array('email' => $client_email, 'name' => 'Recipient 1')),
'merge_vars' => array(array(
'rcpt' => 'recipient1#domain.com',
'vars' =>
array(
array(
'name' => 'FIRSTNAME',
'content' => 'Recipient 1 first name'),
array(
'name' => 'LASTNAME',
'content' => 'Last name')
))),
'attachments' => array(
array(
'content' => $attachment_encoded,
'type' => "application/pdf",
'name' => 'the_name_of_the_attach.pdf',
))
);
$res_user_mandrill = $mandrill->messages->send($user_message, $async=false, $ip_pool=null, $send_at=null);
} catch(Mandrill_Error $e) {
}
</pre>

Related

WordPress: Form posting but php script not executing

My goal is to have the user fill out a form with country and postal code, post the data to a php script that makes a call to fedex's server and returns shipment rates.
I have successfully accomplished this on my local web server, but upon implementation to my WordPress site, the php script does not execute when the form data is posted. My code is as follows:
rate.php (form and php script both in this file):
<!-- FORM -->
<h1 style="font-family: "Ek Mukta", sans-serif;">Quick Quote</h1>
<br>
<form id="quick-quote" class="" action="" method="post">
<label>Country</label>
<br>
<input id="country" type="text" name="country" value="">
<br>
<label>Postal Code</label>
<br>
<input id="postal" type="text" name="postal" value="">
<br>
<br>
<input id="submit" type="submit" name="" value="submit">
</form>
<br>
<!-- FEDEX CALL -->
<?php
print_r($_POST); //this works!
error_reporting(E_ALL);
session_start();
require_once('../../library/fedex-common.php'); //code seems to break here
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "RateService/RateService_v20.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v20 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '20',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_ECONOMY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array('Ammount'=>0,'Currency'=>'USD');
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['VariableHandlingChargeDetail'] = addHandlingCharge();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
//$request['RequestedShipment']['RateRequestTypes'] = addRateType();
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
// $request['RequestedShipment']['RateRequestTypes'] = 'PREFERRED ';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try
{
if(setEndpoint('changeEndpoint'))
{
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
$rateReply = $response -> RateReplyDetails;
echo '<table>';
$country = $_POST['country'];
$postal = $_POST['postal'];
$productPrice = 100;
$serviceFee = 50;
echo $country;
// echo '<tr><td>Country Code </td><td>Postal Code</td><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
$amount = number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalVariableHandlingCharges->TotalCustomerCharge->Amount,2,".",",");
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
$total = $productPrice + $serviceFee + $amount;
// echo "<td>$country</td>. <td>$postal</td>. $serviceType. <td>$amount</td>. $deliveryDate";
// echo '</tr>';
// echo '</table>';
echo
"
<h3>Country Code: $country</h3>
<h3>Postal Code: $postal</h3>
<br>
<table>
<tr>
<td>Product Cost</td>
<td>Shipping Cost</td>
<td>Service Fee</td>
<td>Total</td>
</tr>
<br>
<tr>
<td>$$productPrice<span>+</span></td>
<td>$$amount<span>+</span></td>
<td>$$serviceFee<span>=</span></td>
<td>$$total </td>
</tr>
</table>";
printSuccess($client, $response);
}
else
{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
//FUNCTIONS
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'XXX',
'CompanyName' => 'XXX',
'PhoneNumber' => 'XXX'),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'New York',
'StateOrProvinceCode' => 'XXX',
'PostalCode' => 'XXXX',
'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient(){
$country = $_POST['country'];
$postal = $_POST['postal'];
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => 'XXX'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => '',
'StateOrProvinceCode' => '',
'PostalCode' => ''.$postal.'',
'CountryCode' => ''.$country.'',
'Residential' => false)
);
return $recipient;
}
//HANDLING CHARGE
function addHandlingCharge(){
$VariableHandlingChargeDetail = array(
'RateTypeBasis' => 'LIST',
'RateElementBasis' => 'BASE_CHARGE', // valid values NET_CHARGE, NET_CHARGE_EXCLUDING_TAXES, NET_FREIGHT
'FixedValue' => array('Currency' => 'USD', 'Amount' => 0),
'PercentValue' => '0',
);
return $VariableHandlingChargeDetail;
};
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
// 'PostalCode' => '10036',
'CountryCode' => 'US')
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75');
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array('Currency' => 'USD', 'Amount' => 150),
'CollectionType' => 'ANY')// ANY, GUARANTEED_FUNDS
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 2,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 2,
'Width' => 2,
'Height' => 2,
'Units' => 'IN'
)
);
return $packageLineItem;
}
?>
quick-quote.php (template file to include feature on specific pages):
<?php /* Template Name: quick-quote */ ?>
<?php
get_header();
include('RateService_v20_php/RateAvailableServicesService_v20_php/php/RateWebServiceClient/RateAvailableServices/RateAvailableServicesWebServiceClient.php');
get_footer();
?>
functions.php (relevant code only):
add_action( 'admin_post_quick_quote', 'prefix_admin_quick_quote' );
function prefix_admin_quick_quote() {
// What do I do here!?
}
The issue that I have having is this:
-I fill out the form
-hit submit
-print_r($_POST) the data to see if form posted correctly (it does)
-any code after require_once('../../library/fedex-common.php'); does not execute
Things I have already checked/tried:
-PHP and SOAP are installed correctly on the server
-all files are excessible 664 not 666
-ran the file on the server, it works fine
-setting the form's action to "rate.php" or "quick-quote.php" (form posts data to same page so I think this can be left blank)
-made sure ('../../library/fedex-common.php') is the correct path
So my questions are:
-How do I make the php script execute after the form is submitted?
-Is this accomplished using functions.php to hook into admin-post.php?
Thanks so much!
It sounds like PHP does not have access to fedex-common.php.
Change the relative path for the 'require_once` to an absolute path.
Check that the application has permissions to the directory.
Check that the application has permissions to execute the file.
Additionally, you can check that the include is success by replacing the 'require_once' with the following to further determine if the issue actually a side effect of the file location or an issue with the referenced file.
if(!#include_once("/PATH/TO/library/fedex-common.php")) {
throw new Exception ('fedex-common.php does not exist');
}

Issues in facebook ad creations

Below is the my code for creating ad and I am getting a Fatal Error on step-7:
public function add_ads($account_id,$campaign_id){
/**
* Step 3 Search Targeting
*/
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
print_r($target);
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('GB'));
$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);
print_r($targeting->getData());
/**
* Step 4 Create the AdSet
*/
$adset = new AdSet(null, "act_".$account_id);
var_dump($account_id);
//var_dump(expression)
$adset->setData(array(
AdSetFields::ACCOUNT_ID => "act_".$account_id,
AdSetFields::NAME => 'My First AdSet',
AdFields::BID_TYPE => 'CPC',
AdSetFields::BID_INFO => array('CLICKS' => 500),
AdSetFields::CAMPAIGN_ID => $campaign_id,
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => AdSetOptimizationGoalValues::REACH,
AdSetFields::BILLING_EVENT => AdSetBillingEventValues::IMPRESSIONS,
AdSetFields::BID_AMOUNT => 2,
AdSetFields::DAILY_BUDGET => 4000,
AdSetFields::START_TIME =>(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
print_r($adset->getData());
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_PAUSED,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
$image = new AdImage(null, "act_".$account_id);
$image->{AdImageFields::FILENAME}
= __DIR__.'/avatar3.jpg';
print_r($image);
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
$creative = new AdCreative(null, "act_".$account_id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::TITLE => 'Welcome to the Jungle',
AdCreativeFields::BODY => 'We\'ve got fun \'n\' games',
AdCreativeFields::IMAGE_HASH => $image->hash,
AdCreativeFields::OBJECT_URL => 'http://www.example.com/',
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
$ad = new Ad(null, "act_".$account_id);
$ad->setData(array(
AdFields::CREATIVE =>
array('creative_id' => $creative->id),
AdFields::NAME => 'My First Ad',
AdFields::ADSET_ID => $adset->id,
));
print_r($ad);
$ad->create(array(Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED));
echo 'Ad ID:' . $ad->id . "\n";
return $ad;
}
Here is the error I'm getting:
Fatal error: Uncaught FacebookAds\Http\Exception\AuthorizationException: Invalid parameter in /var/www/html/codeigniter_metronic-master/application/libraries/facebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php:140
Stack trace:
#0 /var/www/html/codeigniter_metronic-master/application/libraries/facebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Client.php(215): FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
#1 /var/www/html/codeigniter_metronic-master/application/libraries/facebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Request.php(282): FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
#2 /var/www/html/codeigniter_metronic-master/application/libraries/facebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Api.php(151): FacebookAds\Http\Request->execute()
#3 /var/www/html/codeigniter_metronic-master/application/libraries/facebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Api.php(193): FacebookAds\Api->executeRe in /var/www/html/codeigniter_metronic-master/application/libraries/facebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php on line 140
Try Synchronous Ad Creation method
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$fields = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset_id,
AdFields::STATUS => Ad::STATUS_PAUSED,
AdFields::CREATIVE => array(
'creative_id' => $creative_id,
),
);
$ad = new Ad();
$ad->create($fields);
Ad creating

cannot open file generated by PHPReport and PHPExcel

I have used the PHPReport library content with the PHPExcel Library content. I am creating the website locally on my macbook using Xampp. The following code I wrote to fetch the data and generate the excel sheet:
public function fetchReportData($newStartDate, $newEndDate){
if ($this->getDBConnection()) {
$q = "select * from PMA where request_date between '".$newStartDate."' and '".$newEndDate ."'";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row_count = $r->num_rows;
if ($row_count == 0) {
echo '<div align="left">'
. '<b><font color="red">* </font>No requests were found in this period</b></div>';
} else {
$data = array();
while ($row = mysqli_fetch_array($r)) {
$desc = $this->returnDesc($row[0]);
$requestId = $this->getNormalReqID($row[0]);
$this->get($requestId);
$username = $this->getUserName($this->requestor_id);
$srv_id = $this->getSRVId($row[0]);
$this->getSRV($srv_id);
$srv_date = date("d-m-Y", strtotime($this->srv_date));
$srv = 'SRV dtd '.$srv_date;
if($this->srv_remarks == null)
{
$remark = $srv;
}
else
{
$remark = $this->srv_remarks;
}
$data[] =
array("Date" => $row[2], "Originator" => $username, "Material No" => $this->material_number,
"Description" => $desc, "Quantity" => $row[5], "Order Number" => $this->pm_order_number,
"Request Number" => $row[7], "Gate Pass No"=> $row[10], "Gate Pass Date"=> $row[14],
"SRV/Date" => $srv, "Received Qty" => $row[11], "Remarks" => $remark)
;
}
include_once 'PHPReport.php';
$R=new PHPReport();
$R->load(array(
'id'=>'product',
'header'=>array(
'Date'=>'Date', 'Originator' => 'Originator', 'Material No' => 'Material No',
'Description' => 'Description' , 'Quantity' => 'Quantity', 'Order Number' => 'Order Number',
'Request Number' => 'Request Number', 'Gate Pass No' => 'Gate Pass No', 'Gate Pass Date'=> 'Gate Pass Date',
'SRV/Date' => 'SRV/Date' , 'Received Qty' => 'Received Qty', 'Remarks' => 'Remarks'
),
'footer'=>array(
'Date'=>'', 'Originator' => '', 'Material No' => '',
'Description' => '' , 'Quantity' => '', 'Order Number' => '',
'Request Number' => '', 'Gate Pass No' => '', 'Gate Pass Date'=> '',
'SRV/Date' => '' , 'Received Qty' => '', 'Remarks' => ''
),
'data'=> $data
)
);
echo $R->render('excel');
}
}
}
}
It does not show any error while calling the code and it generates the xlsx sheet fine but I cannot open the file. I get the following error when I try to open the sheet:
The format or file extension is not valid. verify that the file has not been corrupted and the file extension matches the format of the file.
I get the same error while trying to open a PDF created by the library PHP to PDF, is it something wrong with my macbook?

Forward an email which decode from mandrill webhook, by php SwiftMailer

I'm using mandrill to manage my website emails.But I also want to use a mailbox like yahoo or google so I set a route in mandrill which forward inbound emails that will send to info#mydomain.com, to my default mail box(myEmail#ymail.com).I wrote a PHP code which receive an email, decode it, and forward it to a my email. I use SwiftMailer to send SMTP email.
It works nice for emails without any attachment.But there is a strange problem with attachments.They deliver corruptly.I can not open them.
I search throughly and test a lot, but unfortunately couldn't find the problem.
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
// ----------------- Send ----------------------------------------
include_once "swiftmailer-master/lib/swift_required.php";
$subject = $mail->msg->subject . " From " . $mail->msg->from_email;
$from = array('info#myDomain.ir' =>'myDomain');
$to = array(
'myEmail#yahoo.com' => 'Hamed Gh'
);
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 25,tls);
$transport->setUsername('username');
$transport->setPassword('***********');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
//I think there is a problem here!!
foreach ($mail->msg->attachments as $attachment) {
$myType = $attachment->type;
$myName = $attachment->name;
$myContent = $attachment->content;
$attachment = Swift_Attachment::newInstance()
->setFilename($myName)
->setContentType($myType)
->setBody($myContent)
;
$message->attach($attachment);
}
$body = $mail->msg->html;
$message->setBody($body, 'text/html');
$message->setTo($to);
$text = "Mandrill speaks plaintext";
$message->addPart($text, 'text/plain');
if($recipients = $swift->send($message, $failures) )
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
?>
At the end I couldn't find the problem with SwiftMailer but I could answer my need with mandrill API,
this code works for me:
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
require 'mandrill/src/Mandrill.php';
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
$attachments = array();
foreach ($mail->msg->attachments as $attachment) {
$attachments[] = array(
'type' => $attachment->type,
'name' => $attachment->name,
'content' => $attachment->content,
);
}
$headers = array();
// Support only Reply-to header
if(isset($mail->msg->headers->{'Reply-to'})) {
$headers[] = array('Reply-to' => $mail->msg->headers->{'Reply-to'});
}
// ----------------- Send ----------------------------------------
try {
$mandrill = new Mandrill('-------------');
$message = array(
'html' => $mail->msg->html,
'text' => 'Example text content',
'subject' => $mail->msg->subject . " From " . $mail->msg->from_email,
'from_email' => 'info#mydomain.com',
'from_name' => 'info',
'to' => array(
array(
'email' => 'me#yahoo.com',
'name' => 'me',
'type' => 'to'
)
),
'headers' => array('Reply-To' => 'info#mydomain.com'),
'important' => false,
'track_opens' => null,
'track_clicks' => null,
'auto_text' => null,
'auto_html' => null,
'inline_css' => null,
'url_strip_qs' => null,
'preserve_recipients' => null,
'view_content_link' => null,
'bcc_address' => null,
'tracking_domain' => null,
'signing_domain' => null,
'return_path_domain' => null,
'merge' => true,
'attachments' => $attachments
);
$async = false;
$ip_pool = 'Main Pool';
$send_at = null;
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
?>

facebook publish stream

i have problem... I did follow this site... Im not good at facebook API.. sorry im really noobs with API..
my code:
<?php
define('FB_APIKEY', '***************************');
define('FB_SECRET', '***************************');
define('FB_SESSION', '***************************');
require_once 'facebook-platform/php/facebook.php';
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = 'testasdfsadf';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'TITLE', 'href' => 'http://www.mysite.com'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "2410160********";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
I got error:
post on wall
exception 'FacebookRestClientException' with message 'The user hasn't authorized the application to perform this action' in /Users/*****/Sites/FacebookTEST/facebook-platform/php/facebookapi_php5_restlib.php:3025 Stack trace: #0 /Users/******/Sites/FacebookTEST/facebook-platform/php/facebookapi_php5_restlib.php(916): FacebookRestClient->call_method('facebook.stream...', Array) #1 /Users/******/Sites/FacebookTEST/index.php(46): FacebookRestClient->stream_publish('testasdfsadf', '{"name":null,"h...', '[{"text":"TITLE...', NULL, '2410160********') #2 {main}
I found answer:
here solution:
http://www.facebook.com/connect/prompt_permissions.php?api_key=YOUR_API_KEY&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=page&ext_perm=publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=ID_OF_YOUR_PAGE
Insert your API Key and Page ID in BOLD text..

Categories