Sendgrid error 400 Bad Request - php

I'm getting this error message when trying to send a email through SendGrid:
400 { "errors": [ { "message": "Bad Request", "field": null, "help": null } ] } array(14) { [0]=> string(25) "HTTP/1.1 400 Bad Request " [1]=> string(14) "Server: nginx " [2]=> string(36) "Date: Sat, 11 Mar 2017 19:20:44 GMT " [3]=> string(31) "Content-Type: application/json " [4]=> string(19) "Content-Length: 63 " [5]=> string(23) "Connection: keep-alive " [6]=> string(22) "X-Frame-Options: DENY " [7]=> string(58) "Access-Control-Allow-Origin: https://sendgrid.api-docs.io " [8]=> string(35) "Access-Control-Allow-Methods: POST " [9]=> string(87) "Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl " [10]=> string(28) "Access-Control-Max-Age: 600 " [11]=> string(75) "X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html " [12]=> string(1) " " [13]=> string(0) "" }
Here is my code:
<?php
// If you are using Composer
require 'vendor/autoload.php';
use SendGrid\Mail;
$apiKey = 'mykey';
$sg = new \SendGrid($apiKey);
$email = new SendGrid\Email("Me", "mail#gmail.com");
$mail = new SendGrid\Mail();
$mail->setFrom($email);
$mail->setSubject("Attachment Test");
$p = new \SendGrid\Personalization();
$p->addTo($email);
$c = new \SendGrid\Content("text/plain", "Hi");
$mail->addPersonalization($p);
$mail->addContent($c);
$att1 = new \SendGrid\Attachment();
$att1->setContent( file_get_contents("favicon.ico") );
$att1->setType("text/plain");
$att1->setFilename("1.txt");
$att1->setDisposition("attachment");
$mail->addAttachment( $att1 );
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode() . "\n";
echo json_encode( json_decode($response->body()), JSON_PRETTY_PRINT) . "\n";
var_dump($response->headers());
?>
Not sure if it's related to the attachment. I managed to send an email using a different code, but I'm trying to implement attachments to it so this is the new code. I don't know much php so I'm kinda lost on what does this error means.

The error that you're getting is due to the attachment.
The contents of the file must be base64 encoded. Otherwise it will malform the JSON since you're introducing random bytes into the request body.
You can see that in the complete example of the mail helper for sendgrid-php, a base64 string is set as content to the attachment.
https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L83
As you can see in the Attachment class, the content is simply just set and will serialize as a string in the JSON object when the class is serialized:
https://github.com/sendgrid/sendgrid-php/blob/master/lib/helpers/mail/Mail.php#L670
You just need to use this function: http://php.net/manual/en/function.base64-encode.php
To change the line:
$att1->setContent( file_get_contents("favicon.ico") );
To:
$att1->setContent( base64_encode( file_get_contents("favicon.ico") ) );
The v3 Mail Send documentation is here: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
If you scroll down to the "attachments" object and expand the "content" field, it'll show the requirements for it, maily: The Base64 encoded content of the attachment.

Related

Why am I Not receiving a notification when my FedEx package is delivered?

I'm using FedEx web services and jeremy-dunn/php-fedex-api-wrapper and attempting to have FedEx send me a plaintext email notification when a package has been delivered. I am using a third party for order fulfillment, and they have and use a different FedEx account that is not mine. (Maybe this is the problem?)
I can track the packages just fine, and when I attempt to subscribe to the delivery notification, the response from FedEx seems to indicate success. I am in testing mode. I'm NOT currently in production mode, in case that matters.
My request uses the following function:
function fedexWebServicesNotificationSubscription( $trackingNumber, $recipient, $sender )
{
global $fedexApiMode;
if( ! is_array( $recipient ) OR ! isset( $recipient['email_addr'] ) )
return FALSE;
if( ! is_array( $sender ) OR ! isset( $sender['email_addr'], $sender['name'] ) )
return FALSE;
$userCredential = new ComplexType\WebAuthenticationCredential();
$userCredential->setKey(FEDEX_KEY)
->setPassword(FEDEX_PASSWORD);
$webAuthenticationDetail = new ComplexType\WebAuthenticationDetail();
$webAuthenticationDetail->setUserCredential($userCredential);
$clientDetail = new ComplexType\ClientDetail();
$clientDetail->setAccountNumber(FEDEX_ACCOUNT_NUMBER)
->setMeterNumber(FEDEX_METER_NUMBER);
$version = new ComplexType\VersionId();
$version->setMajor(5)
->setIntermediate(0)
->setMinor(0)
->setServiceId('trck');
$localization = new ComplexType\Localization();
$localization->setLocaleCode("US")
->setLanguageCode("EN");
$emailRecip = new ComplexType\EMailNotificationRecipient();
$emailRecip->setEMailNotificationRecipientType(SimpleType\EMailNotificationRecipientType::_SHIPPER)
->setEMailAddress( $recipient['email_addr'] )
->setLocalization($localization)
->setFormat(SimpleType\EMailNotificationFormatType::_TEXT)
->setNotificationEventsRequested([
SimpleType\EMailNotificationEventType::_ON_DELIVERY,
SimpleType\EMailNotificationEventType::_ON_EXCEPTION,
SimpleType\EMailNotificationEventType::_ON_SHIPMENT,
SimpleType\EMailNotificationEventType::_ON_TENDER
]);
$emailNotificationDetail = new ComplexType\EMailNotificationDetail();
$emailNotificationDetail->setPersonalMessage('Shipment Status Notification')
->setRecipients([$emailRecip]);
$request = new ComplexType\TrackNotificationRequest();
$request->setWebAuthenticationDetail($webAuthenticationDetail)
->setClientDetail($clientDetail)
->setVersion($version)
->setTrackingNumber( $trackingNumber )
->setSenderEMailAddress( $sender['email_addr'] )
->setSenderContactName( $sender['name'] )
->setNotificationDetail($emailNotificationDetail);
$trackServiceRequest = new TrackService\Request();
if( $fedexApiMode == 'production' )
$trackServiceRequest->getSoapClient()->__setLocation(TrackService\Request::PRODUCTION_URL);
$response = $trackServiceRequest->getGetTrackNotificationReply($request, TRUE);
return $response;
}
I use that function like this:
$trackingNumber = '781893213291';
$recipient = [
'email_addr' => 'email#example.com'
];
$sender = [
'email_addr' => 'email#example.com',
'name' => 'My Name'
];
$response = fedexWebServicesNotificationSubscription( $trackingNumber, $recipient, $sender );
echo '<pre>';
var_dump($response);
echo '</pre>';
And my response looks like this:
object(stdClass)#28 (6) {
["HighestSeverity"]=>
string(7) "SUCCESS"
["Notifications"]=>
object(stdClass)#29 (5) {
["Severity"]=>
string(7) "SUCCESS"
["Source"]=>
string(4) "trck"
["Code"]=>
string(1) "0"
["Message"]=>
string(35) "Request was successfully processed."
["LocalizedMessage"]=>
string(35) "Request was successfully processed."
}
["Version"]=>
object(stdClass)#30 (4) {
["ServiceId"]=>
string(4) "trck"
["Major"]=>
int(5)
["Intermediate"]=>
int(0)
["Minor"]=>
int(0)
}
["DuplicateWaybill"]=>
bool(false)
["MoreDataAvailable"]=>
bool(false)
["Packages"]=>
object(stdClass)#31 (6) {
["TrackingNumber"]=>
string(12) "781893213291"
["TrackingNumberUniqueIdentifiers"]=>
string(23) "12018~781893213291~FDEG"
["CarrierCode"]=>
string(4) "FDXG"
["ShipDate"]=>
string(10) "2018-07-17"
["Destination"]=>
object(stdClass)#32 (4) {
["City"]=>
string(13) "SAN FRANCISCO"
["StateOrProvinceCode"]=>
string(2) "CA"
["CountryCode"]=>
string(2) "US"
["Residential"]=>
bool(false)
}
["RecipientDetails"]=>
object(stdClass)#33 (1) {
["NotificationEventsAvailable"]=>
array(6) {
[0]=>
string(11) "ON_DELIVERY"
[1]=>
string(12) "ON_EXCEPTION"
[2]=>
string(12) "ON_EXCEPTION"
[3]=>
string(12) "ON_EXCEPTION"
[4]=>
string(12) "ON_EXCEPTION"
[5]=>
string(12) "ON_EXCEPTION"
}
}
}
}
So it appears that I have subscribed, and that I should receive an email notification when the package is delivered, but the email never arrives. So I need help to know what's wrong with my code, or what's wrong with what I'm doing. I believe I understand what I'm doing, but no success.
https://www.fedex.com/us/developer/WebHelp/ws/2014/dvg/WS_DVG_WebHelp/26_Shipment_Notification_in_the_Ship_Request.htm
Here it says you cannot receive an email in test enviro
1) In test mode, notifications are not sent. With the production key (production mode), notifications are sent. This is what I was expecting.
2) My code and the response I am getting back are fine.
3) Adding a track notification for a package that was not sent through my account works just fine. There is no restriction to adding track notifications, other than there may only be a total of 4.

imap_body() returning empty string

Hello fellow developers,
Im currently trying to read all emails with imap. Im trying to get the header infos with imap_headerinfo and the body with imap_fetchbody.
However, I get all the headerinfo but I only get an empty string as a return from the fetchbody function. I hope someone can help me
$this->inbox = imap_open($server, $user, $password);
// Header und Body der Email auslesen
$emails = imap_search($this->inbox,'ALL');
foreach($emails as $k) {
$this->email_contents[$k] = array(
'header' => imap_headerinfo($this->inbox, $k),
'body' => imap_fetchbody($this->inbox, $k, '1')
);
}
imap_close($this->inbox);
fetch_structure
object(stdClass)#65 (11) {
["type"]=>
int(1)
["encoding"]=>
int(0)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(5) "MIXED"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["ifdisposition"]=>
int(0)
["ifdparameters"]=>
int(0)
["ifparameters"]=>
int(1)
["parameters"]=>
array(1) {
[0]=>
object(stdClass)#66 (2) {
["attribute"]=>
string(8) "boundary"
["value"]=>
string(36) "------------CC4C1146391EA6C129642420"
}
}
["parts"]=>
array(2) {
[0]=>
object(stdClass)#67 (12) {
["type"]=>
int(0)
["encoding"]=>
int(1)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(5) "PLAIN"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["lines"]=>
int(30)
["bytes"]=>
int(590)
["ifdisposition"]=>
int(0)
["ifdparameters"]=>
int(0)
["ifparameters"]=>
int(1)
["parameters"]=>
array(2) {
[0]=>
object(stdClass)#68 (2) {
["attribute"]=>
string(7) "charset"
["value"]=>
string(5) "utf-8"
}
[1]=>
object(stdClass)#69 (2) {
["attribute"]=>
string(6) "format"
["value"]=>
string(6) "flowed"
}
}
}
[1]=>
object(stdClass)#70 (13) {
["type"]=>
int(5)
["encoding"]=>
int(3)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(4) "JPEG"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["bytes"]=>
int(1036)
["ifdisposition"]=>
int(1)
["disposition"]=>
string(10) "attachment"
["ifdparameters"]=>
int(1)
["dparameters"]=>
array(1) {
[0]=>
object(stdClass)#71 (2) {
["attribute"]=>
string(8) "filename"
["value"]=>
string(11) "logo_sm.jpg"
}
}
["ifparameters"]=>
int(1)
["parameters"]=>
array(1) {
[0]=>
object(stdClass)#72 (2) {
["attribute"]=>
string(4) "name"
["value"]=>
string(11) "logo_sm.jpg"
}
}
}
}
}
imap-fetchbody() works unusually when handling attached email messages and it's behaviour is inconsistent.
I was going to re-write this but to be honest the author atamido does a fantastic job of showing why this happens so i'll humbly cite his lead comment from this:: http://php.net/manual/en/function.imap-fetchbody.php he also includes an example of how to extract the body
imap-fetchbody() will decode attached email messages inline with the
rest of the email parts, however the way it works when handling
attached email messages is inconsistent with the main email message.
With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following
for each requested part number:
(empty) - Entire message
0 - Message header
1 - Body text
With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has
a file.ext attachment, imap-fetchbody() will return something like the
following for each requested part number:
(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext
Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of
part number system:
(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext
Note that the file.ext is on the same level now as the plain text and
HTML, and that there is no way to access the MULTIPART/ALTERNATIVE in
the attached message.
Here is a modified version of some of the code from previous posts
that will build an easily accessible array that includes accessible
attached message parts and the message body if there aren't multipart
mimes. The $structure variable is the output of the
imap_fetchstructure() function. The returned $part_array has the
field 'part_number' which contains the part number to be fed directly
into the imap_fetchbody() function.
<?php
function create_part_array($structure, $prefix="") {
//print_r($structure);
if (sizeof($structure->parts) > 0) { // There some sub parts
foreach ($structure->parts as $count => $part) {
add_part_to_array($part, $prefix.($count+1), $part_array);
}
}else{ // Email does not have a seperate mime attachment for text
$part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
}
return $part_array;
}
// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
$part_array[] = array('part_number' => $partno, 'part_object' => $obj);
if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
//print_r($obj);
if (sizeof($obj->parts) > 0) { // Check to see if the email has parts
foreach ($obj->parts as $count => $part) {
// Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
if (sizeof($part->parts) > 0) {
foreach ($part->parts as $count2 => $part2) {
add_part_to_array($part2, $partno.".".($count2+1), $part_array);
}
}else{ // Attached email does not have a seperate mime attachment for text
$part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
}
}
}else{ // Not sure if this is possible
$part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
}
}else{ // If there are more sub-parts, expand them out.
if (sizeof($obj->parts) > 0) {
foreach ($obj->parts as $count => $p) {
add_part_to_array($p, $partno.".".($count+1), $part_array);
}
}
}
}
?>

get JSON data from RPC object php5.5

I have a RPC server class that accepts JSON data from an unspecified given 3rd party using cURL.
I can see the data hit my class, I can store a var_dump into a for what appears to be the server request, but the output looks like receiving webserver info with references to the inbound object.
But I do not see my JSON data 'foo:bar'
<?php
class jsonRPCServer {
public static function handle($object) {
if (
$_SERVER['REQUEST_METHOD'] != 'POST' ||
empty($_SERVER['CONTENT_TYPE']) ||
$_SERVER['CONTENT_TYPE'] != 'application/json'
) {
return false;
}
$request = json_decode(file_get_contents('php://input'),true);
$args=func_get_args();
ob_start();
var_dump($_SERVER);
$result2 = ob_get_clean();
$file = 'stripedump.txt';
$current = file_get_contents($file);
$current .= $result2;
file_put_contents($file, $current);
try {
if ($result = #call_user_func_array(array($object,$request['method']),$request['params'])) {
$response = array (
'id' => $request['id'],
'result' => $result,
'error' => NULL
);
} else {
$response = array (
'id' => $request['id'],
'result' => NULL,
'error' => 'unknown method or incorrect parameters'
);
}
} catch (Exception $e) {
$response = array (
'id' => $request['id'],
'result' => NULL,
'error' => $e->getMessage()
);
}
if (!empty($request['id'])) { // notifications don't want response
header('content-type: text/javascript');
echo json_encode($response);
}
return true;
}
}
?>
<?php
require_once 'example.php';
require_once 'jsonRPCServer.php';
$myExample = new example();
jsonRPCServer::handle($myExample)
or print 'no request';
echo '<b>Attempt to perform basic operations</b><br />'."\n";
try {
echo 'Your name is <i>'.$myExample->giveMeSomeData('name').'</i><br />'."\n";
$myExample->changeYourState('I am using this funnction from the local environement');
echo 'Your status request has been accepted<br />'."\n";
} catch (Exception $e) {
echo nl2br($e->getMessage()).'<br />'."\n";
}
var_dump($myExample);
echo '<br /><b>Attempt to store strategic data</b><br />'."\n";
try {
$myExample->writeSomething('bite me');
echo 'Strategic data succefully stored';
} catch (Exception $e) {
echo nl2br($e->getMessage());
}
?>
output from remote cURL client:
gentoo-mini htdocs # curl -X POST -H "Content-Type: application/json" -d "{foo:bar}" http://nyctelecomm.com/hooker/
<b>Attempt to perform basic operations</b><br />
Your name is <i>Bubba</i><br />
Your status request has been accepted<br />
object(example)#1 (1) {
["someData":"example":private]=>
array(2) {
["name"]=>
string(5) "Bubba"
["attr"]=>
string(17) "Some me Attribute"
}
}
<br /><b>Attempt to store strategic data</b><br />
Strategic data succefully stored
stored var_dump($_SERVER) data:
array(29) {
["HTTP_HOST"]=>
string(15) "nyccomm.com"
["HTTP_USER_AGENT"]=>
string(11) "curl/7.42.1"
["HTTP_ACCEPT"]=>
string(3) "*/*"
["CONTENT_TYPE"]=>
string(16) "application/json"
["CONTENT_LENGTH"]=>
string(1) "9"
["PATH"]=>
string(29) "/sbin:/bin:/usr/sbin:/usr/bin"
["LD_LIBRARY_PATH"]=>
string(29) "/usr/local/lib:/usr/local/lib"
["SERVER_SIGNATURE"]=>
string(0) ""
["SERVER_SOFTWARE"]=>
string(34) "Apache/2.4.12 (FreeBSD) PHP/5.6.10"
["SERVER_NAME"]=>
string(15) "nyccomm.com"
["SERVER_ADDR"]=>
string(13) "108.61.175.20"
["SERVER_PORT"]=>
string(2) "80"
["REMOTE_ADDR"]=>
string(12) "67.82.49.236"
["DOCUMENT_ROOT"]=>
string(21) "/home/www"
["REQUEST_SCHEME"]=>
string(4) "http"
["CONTEXT_PREFIX"]=>
string(0) ""
["CONTEXT_DOCUMENT_ROOT"]=>
string(21) "/home/www"
["SERVER_ADMIN"]=>
string(19) "admin#ex-mailer.com"
["SCRIPT_FILENAME"]=>
string(38) "/home/www/hooker/index.php"
["REMOTE_PORT"]=>
string(5) "52841"
["GATEWAY_INTERFACE"]=>
string(7) "CGI/1.1"
["SERVER_PROTOCOL"]=>
string(8) "HTTP/1.1"
["REQUEST_METHOD"]=>
string(4) "POST"
["QUERY_STRING"]=>
string(0) ""
["REQUEST_URI"]=>
string(8) "/hooker/"
["SCRIPT_NAME"]=>
string(17) "/hooker/index.php"
["PHP_SELF"]=>
string(17) "/hooker/index.php"
["REQUEST_TIME_FLOAT"]=>
float(1436429001.683)
["REQUEST_TIME"]=>
int(1436429001)
}
string(4) "name"
tcpdump:
00:29:06.659025 IP 192.168.0.55.52841 > 108.61.175.20.vultr.com.http: Flags [P.], seq 1:148, ack 1, win 115, options [nop,nop,TS val 2017270703 ecr 2483478707], length 147
E....A#.#.f....7l=...i.P...g.I.]...s.......
x=......POST /hooker/ HTTP/1.1
Host: nyccomm.com
User-Agent: curl/7.42.1
Accept: */*
Content-Type: application/json
Content-Length: 9
{foo:bar}
00:29:06.746198 IP 108.61.175.20.vultr.com.http > 192.168.0.55.52841: Flags [P.], seq 1:561, ack 148, win 1033, options [nop,nop,TS val 2483478793 ecr 2017270703], length 560
E..dm.#.5...l=.....7.P.i.I.]....... :......
... x=..HTTP/1.1 200 OK
Date: Thu, 09 Jul 2015 08:03:21 GMT
Server: Apache/2.4.12 (FreeBSD) PHP/5.6.10
X-Powered-By: PHP/5.6.10
Content-Length: 373
Content-Type: text/html; charset=UTF-8
<b>Attempt to perform basic operations</b><br />
Your name is <i>Bubba</i><br />
Your status request has been accepted<br />
object(example)#1 (1) {
["someData":"example":private]=>
array(2) {
["name"]=>
string(5) "Bubba"
["attr"]=>
string(17) "Some me Attribute"
}
}
<br /><b>Attempt to store strategic data</b><br />
Strategic data succefully stored
00:29:06.746271 IP 192.168.0.55.52841 > 108.61.175.20.vultr.com.http: Flags [.], ack 561, win 123, options [nop,nop,TS val 2017270790 ecr 2483478793], length 0
E..4.B#.#.gP...7l=...i.P.....I.....{.W.....
How do I access the JSON data from my inbound RPC object? (specifically 'foo:bar')
This works when used all by its self
<?php
$request = file_get_contents('php://input');
$args=func_get_args();
ob_start();
var_dump($request);
$result2 = ob_get_clean();
$file = 'stripedump.txt';
$current = file_get_contents($file);
$current .= $result2;
file_put_contents($file, $current);
?>

Editing Contact Results In "Not Found"

I have working PHP code to create a Google contact via their v3 API. However, when it comes time to edit (update) the contact I cannot seem to get it to do the update. I keep getting a "Not Found" back in the update response. Any ideas why???
Here is my code.
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPE);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setAccessToken($token);
$xml = <<<END_XML
<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gContact='http://schemas.google.com/contact/2008'>
<atom:content type='text'>{$content}</atom:content>
</atom:entry>
END_XML;
$request = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/{$account}/full/{$contact['id']}");
$request = $client->getAuth()->sign($request);
$request->setRequestMethod("POST");
$request->setPostBody($xml);
$request->setRequestHeaders(array('content-length' => strlen($xml), 'GData-Version'=> '3.0','content-type'=>'application/atom+xml; charset=UTF-8; type=feed'));
$response = $client->getIo()->executeRequest($request);
Here is a var_dump of my request (data masked with xxx):
object(Google_Http_Request)#5 (14) {
["batchHeaders":"Google_Http_Request":private]=>
array(3) {
["Content-Type"]=>
string(16) "application/http"
["Content-Transfer-Encoding"]=>
string(6) "binary"
["MIME-Version"]=>
string(3) "1.0"
}
["queryParams":protected]=>
array(0) {
}
["requestMethod":protected]=>
string(4) "POST"
["requestHeaders":protected]=>
array(4) {
["authorization"]=>
string(90) "Bearer ya29.vQDJSs7ZxzBG8eN05Er6KiwutMf0K_uNKyuNUu4s5jd9XL4oA3o_SsikhUeIGzRoVtacYwlVVFcEYg"
["content-length"]=>
int(392)
["gdata-version"]=>
string(3) "3.0"
["content-type"]=>
string(46) "application/atom+xml; charset=UTF-8; type=feed"
}
["baseComponent":protected]=>
string(22) "https://www.google.com"
["path":protected]=>
string(65) "/m8/feeds/contacts/events#xxx/full/1603b8310ac9f5ca"
["postBody":protected]=>
string(392) "<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gContact='http://schemas.google.com/contact/2008'>
<id>http://www.google.com/m8/feeds/contacts/events%40xxx/base/1603b8310ac9f5ca</id>
<atom:content type='text'>Notes Test Data</atom:content>
</atom:entry>"
["userAgent":protected]=>
NULL
["canGzip":protected]=>
NULL
["responseHttpCode":protected]=>
NULL
["responseHeaders":protected]=>
NULL
["responseBody":protected]=>
NULL
["expectedClass":protected]=>
NULL
["accessKey"]=>
NULL
}
Here is a var_dump of my response:
array(3) {
[0]=>
string(9) "Not Found"
[1]=>
array(12) {
["cache-control"]=>
string(46) "no-cache, no-store, max-age=0, must-revalidate"
["pragma"]=>
string(8) "no-cache"
["expires"]=>
string(29) "Fri, 01 Jan 1990 00:00:00 GMT"
["date"]=>
string(29) "Fri, 14 Nov 2014 00:13:58 GMT"
["vary"]=>
string(15) "Origin
X-Origin"
["content-type"]=>
string(24) "text/html; charset=UTF-8"
["x-content-type-options"]=>
string(7) "nosniff"
["x-frame-options"]=>
string(10) "SAMEORIGIN"
["x-xss-protection"]=>
string(13) "1; mode=block"
["server"]=>
string(3) "GSE"
["alternate-protocol"]=>
string(15) "443:quic,p=0.01"
["transfer-encoding"]=>
string(7) "chunked"
}
[2]=>
int(404)
}
Since https://developers.google.com/google-apps/contacts/v3/http-update,
that means request to the Contacts API must be sent with https:// instead of http:// now, have you noticed you are using
http://www.google.com/m8/feeds/contacts/events%40xxx/base/1603b8310ac9f5ca
rather than
https://www.google.com/m8/feeds/contacts/events%40xxx/base/1603b8310ac9f5ca
in the var_dump of my request code.
I think you need to change
$request->setRequestMethod("POST");
to
$request->setRequestMethod("PUT");

Invalid Request on YouTube video upload with Zend Gdata

I have the following code that returns HTTP error 400 everytime I try to execute it.
$file = "/home/.../videos/bigbuckbunny.mp4";
$title = "This is a test";
$category = "Film";
$description = "test";
$keywords = "test, film, big buck";
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_App_HttpException');
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($this->settings['username'], $this->settings['password'], 'youtube', NULL, 'Test Client');
$this->youTube = new Zend_Gdata_YouTube($httpClient, 'Test Client', 'Videos Plugin', $this->settings['key']);
$this->youTube->setMajorProtocolVersion(2);
$entry = new Zend_Gdata_YouTube_VideoEntry();
$fileSource = $this->youTube->newMediaFileSource($file);
$fileSource->setContentType(mime_content_type($file));
$fileSource->setSlug(basename($file));
$entry->setMediaSource($fileSource);
$entry->setVideoCategory($category);
$entry->setVideoTitle($title);
$entry->setVideoDescription($description);
$entry->setVideoTags($keywords);
try
{
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/users/default/uploads';
$newEntry = $this->youTube->insertEntry($entry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
}
catch(Zend_Gdata_App_HttpException $e)
{
var_dump($e->getResponse());
return NULL;
}
My settings are correct. The exception is the following:
object(Zend_Http_Response)#362 (5) {
["version:protected"]=>
string(3) "1.1"
["code:protected"]=>
int(400)
["message:protected"]=>
string(11) "Bad Request"
["headers:protected"]=>
array(9) {
["Server"]=>
string(61) "HTTP Upload Server Built on Mar 22 2012 14:54:02 (1332453242)"
["Content-type"]=>
string(24) "text/html; charset=UTF-8"
["X-guploader-uploadid"]=>
string(98) "AEnB2UoljS9KYUftPEhuRV8hVssGvOHcR1mcK0rfhMOGTBkUYSxX29iKpO9vHisG10EYxQE0-rul3rVEbd2YJlFiXCbaGBpUpQ"
["Date"]=>
string(29) "Fri, 23 Mar 2012 18:36:46 GMT"
["Pragma"]=>
string(8) "no-cache"
["Expires"]=>
string(29) "Fri, 01 Jan 1990 00:00:00 GMT"
["Cache-control"]=>
string(35) "no-cache, no-store, must-revalidate"
["Content-length"]=>
string(2) "15"
["Connection"]=>
string(5) "close"
}
["body:protected"]=>
string(15) "Invalid Request"
}
Does anyone have any idea? I got it working before, now it doesn't seem to work.
Turns out I had the wrong upload URL, it should have been:
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/users/' . $this->settings['feed'] . '/uploads';

Categories