Using Square Connect PHP SDK, UpsertCatalogObject fatal error - square-connect

I am using the square connect php sdk, and I am getting the following error, and haven't been able to find any solution. I am trying to push a few new categories that have been added on my app (within mysql database).
Building the catelogObject
foreach ($push_array as $key => $cat_name) {
$category = $this->products_lib->get_category($cat_name);
$idempotency_key = uniqid('',true);
$push_obj = new stdClass();
$push_obj->type = 'CATEGORY';
$push_obj->id = '#' . trim($category->name);
$push_obj->category_data = ['name'=>trim($category->name)];
$push_obj->present_at_all_locations = true;
$catelogObject = ["idempotency_key" => $idempotency_key, 'object' => $push_obj];
print_r($catelogObject);
$response = $square_connect->upsert_category($catelogObject);
}
Produces
(
[idempotency_key] => 5996186208eae4.27853833
[object] => stdClass Object
(
[type] => CATEGORY
[id] => #Drinks
[category_data] => Array
(
[name] => Drinks
)
[present_at_all_locations] => 1
)
)
square_connect class
class SquareConnect {
private $access_token = "***********************";
private $sandbox_access_token = "sandbox-*********************";
public function get_locations() {
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($this->access_token);
$locations_api = new \SquareConnect\Api\LocationsApi();
echo $locations_api->listLocations();
}
public function get_categories() {
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($this->access_token);
$api = new \SquareConnect\Api\CatalogApi();
$retobj = json_decode($api->listCatalog(null, 'CATEGORY'));
// $categories = $retobj->objects;
return $retobj->objects;
}
public function upsert_category($category_object) {
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($this->access_token);
$api = new \SquareConnect\Api\CatalogApi();
// return $apiResponse = json_decode($api->UpsertCatalogObject($category_object));
print_r(json_decode($api->UpsertCatalogObject($category_object))) ;
}
public function get_items() {
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($this->access_token);
$api = new \SquareConnect\Api\CatalogApi();
echo $api->listCatalog(null, 'ITEM');
}
}
When I run the code, I get the following error :
Fatal error: Access to undeclared static property: stdClass::$swaggerTypes in /vendor/square/connect/lib/ObjectSerializer.php on line 43
Hope that is clear enough, and thanks in advance for assistance
Edit
[DEBUG] HTTP Request body ~BEGIN~
~END~
[DEBUG] HTTP Response body ~BEGIN~
{"objects":[{"type":"CATEGORY","id":"52IJHDSD67VAQNJ3GQB5TVRX","updated_at":"2017-08-16T19:50:58.373Z","version":1502913058373,"is_deleted":false,"custom_attributes":[{"name":"straight_fire_type","int_value":0}],"present_at_all_locations":true,"category_data":{"name":"Candy"}},{"type":"CATEGORY","id":"KFB7DDQYPG532F66SYAYAD4W","updated_at":"2017-06-13T19:45:27.653Z","version":1497383127653,"is_deleted":false,"present_at_all_locations":true,"category_data":{"name":"Sandwiches"}},{"type":"CATEGORY","id":"SJVUDRCAMQBSRM7FAEBQATBS","updated_at":"2017-06-13T19:45:35.181Z","version":1497383135181,"is_deleted":false,"present_at_all_locations":true,"category_data":{"name":"Specials"}}]}
~END~
* Hostname was NOT found in DNS cache
* Trying 74.122.190.85...
* Connected to connect.squareup.com (74.122.190.85) port 443 (#0)
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* Server certificate:
* subject: C=US; ST=California; L=San Francisco; O=Square, Inc.; CN=*.squareup.com
* start date: 2016-12-07 00:44:04 GMT
* expire date: 2017-12-16 01:14:02 GMT
* subjectAltName: connect.squareup.com matched
* issuer: C=US; O=Entrust, Inc.; OU=See www.entrust.net/legal-terms; OU=(c) 2012 Entrust, Inc. - for authorized use only; CN=Entrust Certification Authority - L1K
* SSL certificate verify ok.
> GET /v2/catalog/list?types=CATEGORY HTTP/1.1
User-Agent: Square-Connect-PHP/2.2.1
Host: connect.squareup.com
Accept: application/json
Content-Type: application/json
Authorization: Bearer sq0atp-WrF2m45lEzQVzCqAxSA_oA
< HTTP/1.1 200 OK
< Content-Type: application/json
< Vary: Origin, Accept-Encoding
< X-Content-Type-Options: nosniff
< X-Download-Options: noopen
< X-Frame-Options: SAMEORIGIN
< X-Permitted-Cross-Domain-Policies: none
< X-Xss-Protection: 1; mode=block
< Date: Fri, 18 Aug 2017 02:29:24 GMT
< Keep-Alive: timeout=60
< Strict-Transport-Security: max-age=631152000
< content-length: 687
<
* Connection #0 to host connect.squareup.com left intact
EDIT - Solution: Need to change the object property of $catelogObject to an array not an object as the square connect api documentation instructs
foreach ($push_array as $key => $cat_name) {
$category = $this->products_lib->get_category($cat_name);
$idempotency_key = uniqid('',true);
$push_obj = [];
$push_obj['type'] = 'CATEGORY';
$push_obj['id'] = '#' . trim($category->name);
$push_obj['category_data'] = ['name'=>trim($category->name)];
$push_obj['present_at_all_locations'] = true;
$catelogObject = ["idempotency_key" => $idempotency_key, 'object' => $push_obj];
print_r($catelogObject);
$response = $square_connect->upsert_category($catelogObject);
}

Related

Multipart request rejected because no bounday were found while boundary is already sent

I went through the other similar questions but couldn't find any solution. We have a backend service running by Spring Boot and has been working for a while now. But there is a new user of this service recently and they are using MuleSoft to send their request. But all attempts to send a file to our service fails with this error:
Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
The only difference we could find between a request from MuleSoft and say a curl command is that MuleSoft always sends the request with boundary value wrapped with double quotes
Mule request:
<Header name="Content-Type">multipart/form-data; charset=UTF-8; boundary="--------------------------669816398596264398718285"</Header>
Versus Postman/curl request:
* SSL certificate verify ok.
* Using HTTP2, server supports multiplexing
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7fd656810a00)
> POST /api/upload HTTP/2
> Host: myhost
> user-agent: curl/7.79.1
> accept: */*
> content-length: 97255
> content-type: multipart/form-data; boundary=------------------------111fd08cb4fafe1c
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
* We are completely uploaded and fine
< HTTP/2 200
< date: Mon, 19 Dec 2022 04:56:25 GMT
< content-length: 0
Our controller in Spring is very simple:
#RestController
class MyController {
#PostMapping("/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
#ResponseStatus(HttpStatus.OK)
fun uploadDocument(#RequestPart("file") file: MultipartFile) {
logger.info { "ContentType: ${file.contentType}" }
logger.info { "Name: ${file.name}" }
logger.info { "Byte: ${String(file.bytes)}" }
}
}
The following curl command works fine:
curl -v -X POST -F file=#/Users/myhomefolder/Documents/some-file.jpg https://host-name/api/upload
But this script from MuleSoft doesn't (Sorry I'm not familiar with Mule, I got this code from their team):
import dw::module::Multipart
output multipart/form-data boundary = "---WebKitFormBoundary7MA4YWxkTrZu0gW"
---
{
parts : {
file : {
headers : {
"Content-Disposition" : {
"name": "file",
"filename": payload.name
},
"Content-Type" : "multipart/form-data"
},
content : payload.byteArray
}
}
}
Is there any configuration in Spring that accepts double quotes for boundary? Is there anything missing in our backend configuration that should be added to support different HTTP client?

Laravel How to get the MailJet response after an email message has been sent

Based on this answer I want to track the status of an email, in order to determine if the system should try to resend the undelivered mail one more time.
I have created the listener:
class MailJetSentResponse
{
/**
* Handle the event.
*
* #param object $event
* #return void
*/
public function handle(MessageSent $event)
{
//https://stackoverflow.com/a/55576361/1883256
dd($event);
}
}
And what I get from the dd() (by executing Laravel Tinker)
>>> Mail::mailer('smtp')->raw('Tinker mailjet test email message',function($msg) {$msg->to('real#email.com')->subject('What is the API response?');});
is:
-messageId: "af86b7aebb941af_somehash..._5#email.com"
-debug: """
< 220 in.mailjet.com ESMTP Mailjet\r\n
> EHLO [127.0.0.1]\n
< 250-smtpin.mailjet.com\r\n
< 250-PIPELINING\r\n
< 250-SIZE 15728640\r\n
< 250-VRFY\r\n
< 250-ETRN\r\n
< 250-STARTTLS\r\n
< 250-AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5\r\n
< 250-AUTH=PLAIN LOGIN DIGEST-MD5 CRAM-MD5\r\n
< 250-ENHANCEDSTATUSCODES\r\n
< 250-8BITMIME\r\n
< 250 SMTPUTF8\r\n
> STARTTLS\n
< 220 2.0.0 Ready to start TLS\r\n
> EHLO [127.0.0.1]\n
< 250-smtpin.mailjet.com\r\n
< 250-PIPELINING\r\n
< 250-SIZE 15728640\r\n
< 250-VRFY\r\n
< 250-ETRN\r\n
< 250-AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5\r\n
< 250-AUTH=PLAIN LOGIN DIGEST-MD5 CRAM-MD5\r\n
< 250-ENHANCEDSTATUSCODES\r\n
< 250-8BITMIME\r\n
< 250 SMTPUTF8\r\n
> AUTH CRAM-MD5\n
< 334 PDExNTcxM_more_hash..._jg2MjcxMkBAtdnpybj4=\r\n
> ZGJhNDc5YjAwMGRkOTQwZGFmYjdjNTI5YzJhYzllMTggZDBiMzk1YWY1NmE4MWYzNDcxNTU4YWQ3ZWJkYTMyZDY=\n
< 235 2.7.0 Authentication successful\r\n
> MAIL FROM:<real#email.com>\n
< 250 2.1.0 Ok\r\n
> RCPT TO:<destination#email.com>\n
< 250 2.1.5 Ok\r\n
> DATA\n
< 354 End data with <CR><LF>.<CR><LF>\r\n
> .\n
< 250 OK queued as 6ffaf3f2-b351-485c-bb27-a4b8230d873b\r\n
"""
}
}
+data: array:1 [
"message" => Illuminate\Mail\Message^ {#5394
#message: Symfony\Component\Mime\Email^ {#5231}
#embeddedFiles: []
}
]
}
But I feel stuck, I want to know how to get the response where I cant get the status of a given email like in this example or how do I get the data json response from MailJet like this one:
{
"Sent": [
{
"Email": "passenger#mailjet.com",
"MessageID": 1234567890987654400,
"MessageUUID": "1ab23cd4-e567-8901-2345-6789f0gh1i2j"
}
]
}
to track the email status? any ideas?

Email delivery (spam?) - Email not received with some ISP emails

I'm having a problem with some emails not being delivered with some ISP email address
Common email example reported by users : "xx#free.fr", "#bellsouth.net"
I don't really have a way to "test" why they don't get the emails. I told them to verify spam folder and they aren't there.. I have test account for popular email service "gmail, hotmail" and they work fine.
The emails I'm sending are common emails from my domain website (registration, confirm account, forgot password). I don't send any bulk email. I'm using goDaddy as hosting service.
I have set up SPF on my domain, and the email are sent with PHP(codeIgniter) - See bottom for how the mail is sent with code
Here is an example of mail that I sent that is blocked by theses ISP:
Delivered-To: tdfdestgmfdsailmaxmt123okdddf3#gmail.com
Received: by 10.112.159.166 with SMTP id xd6csp1482168lbb;
Wed, 17 Dec 2014 10:27:57 -0800 (PST)
X-Received: by 10.50.61.238 with SMTP id t14mr9680303igr.34.1418840877015;
Wed, 17 Dec 2014 10:27:57 -0800 (PST)
Return-Path: <admin#maximumtrainer.com>
Received: from p3nlsmtpcp01-03.prod.phx3.secureserver.net (p3nlsmtpcp01-03.prod.phx3.secureserver.net. [184.168.200.142])
by mx.google.com with ESMTP id hh16si4059486icb.62.2014.12.17.10.27.56
for <tdfdestgmfdsailmaxmt123okdddf3#gmail.com>;
Wed, 17 Dec 2014 10:27:56 -0800 (PST)
Received-SPF: pass (google.com: domain of admin#maximumtrainer.com designates 184.168.200.142 as permitted sender) client-ip=184.168.200.142;
Authentication-Results: mx.google.com;
spf=pass (google.com: domain of admin#maximumtrainer.com designates 184.168.200.142 as permitted sender) smtp.mail=admin#maximumtrainer.com
Received: from p3plcpnl0063.prod.phx3.secureserver.net ([184.168.200.112])
by p3nlsmtpcp01-03.prod.phx3.secureserver.net with : CPANEL :
id UiR51p01s2S0Aj401iR5yP; Wed, 17 Dec 2014 11:25:05 -0700
Received: from p3plcpnl0063.prod.phx3.secureserver.net ([184.168.200.112]:34603 helo=maximumtrainer.com)
by p3plcpnl0063.prod.phx3.secureserver.net with esmtpa (Exim 4.84)
(envelope-from <admin#maximumtrainer.com>)
id 1Y1JKF-0001bp-W0
for tdfdestgmfdsailmaxmt123okdddf3#gmail.com; Wed, 17 Dec 2014 11:27:56 -0700
User-Agent: CodeIgniter
Date: Wed, 17 Dec 2014 18:27:55 +0000
From: "Maximum Trainer" <admin#maximumtrainer.com>
To: tdfdestgmfdsailmaxmt123okdddf3#gmail.com
Subject: =?utf-8?Q?Bienvenue?=
Reply-To: "admin#maximumtrainer.com" <admin#maximumtrainer.com>
X-Sender: admin#maximumtrainer.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <5491cb2be1fa8#maximumtrainer.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
X-AntiAbuse: This header was added to track abuse, please include it with any abuse report
X-AntiAbuse: Primary Hostname - p3plcpnl0063.prod.phx3.secureserver.net
X-AntiAbuse: Original Domain - gmail.com
X-AntiAbuse: Originator/Caller UID/GID - [47 12] / [47 12]
X-AntiAbuse: Sender Address Domain - maximumtrainer.com
X-Get-Message-Sender-Via: p3plcpnl0063.prod.phx3.secureserver.net: authenticated_id: admin#maximumtrainer.com
X-Source:
X-Source-Args:
X-Source-Dir:
CodeIgniter sender function:
function send_confirmation_mail($email, $first_name, $confirm_code) {
$CI =& get_instance();
$CI->load->library('email'); // load library
$CI->email->from ( 'admin#maximumtrainer.com', 'Maximum Trainer' );
$CI->email->to ( $email );
$CI->email->subject ( lang('email_activate_title') );
$link = base_url(). index_page(). lang('url_confirm_user'). "/". $confirm_code;
$message = lang('email_hello'). $first_name. ", \r\n".
lang('email_activate_thank_you'). "\r\n\r\n".
lang('email_activate_click_link'). "\r\n".
$link. "\r\n\r\n".
lang('email_activate_farewwell'). "\r\n".
lang('email_linkMT');
$CI->email->message( $message );
if ( ! $CI->email->send()) {
$CI->messages->add("error send_confirmation_mail", "error");
return false;
}
return true;
}
Server config :
$config['useragent'] = 'CodeIgniter';
$config['protocol'] = 'smtp';
#$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'p3plcpnl0063.prod.phx3.secureserver.net';
$config['smtp_user'] = 'yyyyyy#maximumtrainer.com';
$config['smtp_pass'] = 'xxxxxxx';
$config['smtp_port'] = 25; #465 to test doesnt seem to work
$config['smtp_timeout'] = 5;
$config['wordwrap'] = FALSE;
$config['wrapchars'] = 76;
$config['mailtype'] = 'text';
$config['charset'] = 'utf-8';
$config['validate'] = FALSE;
$config['priority'] = 3;
$config['crlf'] = "\r\n";
$config['newline'] = "\r\n";
$config['bcc_batch_mode'] = FALSE;
$config['bcc_batch_size'] = 200;
Are there any services to diagnose what could be the cause of the problem? I can't register for free with these email providers in order to test.

Google Drive API download file, http respond code 200 but the responseBody is empty

Sorry if this is a stupid question but I´m new here and I don´t know how to follow.
I´ve implemented the support of Google drive in our server in php that provides support to our apps in Android and IOs, we can upload files to Google Drive or delete them with no issues, and when we are downloading the file, it looks like the httpResponseCode is correct 200 and the responseHeader too but the responseBody is empty.
I put here the response from Google Drive Server in case someone has any idea. thanks
apiHttpRequest Object
(
[batchHeaders:apiHttpRequest:private] => Array
(
[Content-Type] => application/http
[Content-Transfer-Encoding] => binary
[MIME-Version] => 1.0
[Content-Length] =>
)
[url:protected] => https://doc-0s-6s-docs.googleusercontent.com/docs/securesc/3h10lch354ufu4pkrusuk27smk7k4ifq/qp3b555lfchhfmpfodjv4mcpbug1vol6/1346112000000/12488086635796486161/12488086635796486161/0B_cf3F02DuErM3V3b0o4WnYyNTA?h=16653014193614665626&e=download&gd=true
[requestMethod:protected] => GET
[requestHeaders:protected] => Array
(
[authorization] => Bearer ya29.AHES6ZQwIuu8ZhP8Uk389Sgo5NELnvArjzAC362ByzEsh2qa_gjDvJw
)
[postBody:protected] =>
[userAgent:protected] => google-api-php-client/0.5.0
[responseHttpCode:protected] => 200
[responseHeaders:protected] => Array
(
[server] => HTTP Upload Server Built on Aug 15 2012 18:03:01 (1345078981)
[access-control-allow-origin] => *
[access-control-allow-credentials] => false
[access-control-allow-headers] => authorization
[access-control-allow-methods] => GET,OPTIONS
[content-type] => video/quicktime
[content-disposition] => attachment;filename="VID_20120827_105737.mp4";filename*=UTF-8''VID_20120827_105737.mp4
[content-length] => 2768422
[date] => Tue, 28 Aug 2012 00:15:26 GMT
[expires] => Tue, 28 Aug 2012 00:15:26 GMT
[cache-control] => private, max-age=0
)
[responseBody:protected] =>
Now the code that I´m using:
public function GetFile($fileId) {
$fileVars = null;
try {
/*
* Retrieve metadata for the file specified by $fileId.
*/
$file = $this->service->files->get($fileId);
$fileVars = get_object_vars($file);
/*
* Retrieve the file's content using download URL specified in metadata.
*/
$downloadUrl = $file->getDownloadUrl();
error_log('Download URL file from Drive: ' . $downloadUrl);
if ($downloadUrl) {
$request = new apiHttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = apiClient::$io->authenticatedRequest($request);
error_log(print_r($httpRequest, 1));
if ($httpRequest->getResponseHttpCode() == 200) {
$content = $httpRequest->getResponseBody();
$fileVars['content'] = $content?($content):'';
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error retrieving file from Drive: ' . $e->getMessage());
throw $e;
}
return json_encode($fileVars);
}

Inserting a new calendarEntry in google calendar API v3 returns a 404

I use the google-api-services-calendar v3 for java.
I list without problems my calendarEntries. But the insertion of a new calendarEntry fails.
I use the same code as the samples :
CalendarListEntry newCal = new CalendarListEntry();
newCal.setId(calTitle);
newCal.setSummary(calTitle);
newCal.setTimeZone("Europe/Paris");
CalendarListEntry execute = null;
try {
execute = service.calendarList().insert(newCal).execute();
} catch (IOException e) {
e.printStackTrace();
}
The calendar is not created. In the logs I have :
CONFIG: {"id":"A_TEST","summary":"A_TEST","timeZone":"Europe/Paris"}
15 juin 2012 16:20:45 com.google.api.client.http.HttpRequest execute
CONFIG: -------------- REQUEST --------------
POST https://www.googleapis.com/calendar/v3/users/me/calendarList
Accept-Encoding: gzip
Authorization: <Not Logged>
User-Agent: Google-HTTP-Java-Client/1.10.2-beta (gzip)
Content-Type: application/json; charset=UTF-8
Content-Encoding: gzip
Content-Length: 69
CONFIG: Total: 60 bytes
CONFIG: {"id":"A_TEST","summary":"A_TEST","timeZone":"Europe/Paris"}
15 juin 2012 16:20:46 com.google.api.client.http.HttpResponse <init>
CONFIG: -------------- RESPONSE --------------
HTTP/1.1 404 Not Found
X-Frame-Options: SAMEORIGIN
Date: Fri, 15 Jun 2012 14:07:52 GMT
Content-Length: 120
Expires: Fri, 15 Jun 2012 14:07:52 GMT
X-XSS-Protection: 1; mode=block
Content-Encoding: gzip
Content-Type: application/json; charset=UTF-8
Server: GSE
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
CONFIG: Total: 165 bytes
CONFIG: {
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
Any ideas?
RTFM!
I was not on the good uri. The correct insertion must be on https://www.googleapis.com/calendar/v3/calendars
and not https://www.googleapis.com/calendar/v3/users/me/calendarList.
The code is :
Calendar newCal = new Calendar();
newCal.setSummary(calTitle);
newCal.setTimeZone("Europe/Paris");
Calendar createdCalendar = null;
try {
createdCalendar = service.calendars().insert(newCal).execute();
} catch (Exception e){
e.printStackTrace();
}

Resources