#php #json #curl
Вопрос:
Я пытаюсь создать нового клиента в своем API, используя php cURL. Клиенты, продукты и все, что создается, создается методом POST. Это мой код:
$json='{ "data": { "type": "customers", "attributes": { "tax_registration_number": "5555555550", "business_name": "Test customer", "contact_name": "Mr. Test", "website": "https://www.testurl.pt", "phone_number": "2299999999", "mobile_number": "9299999999", "email": "test@testcustomer.pt", "observations": "This is only a test", "internal_observations": "This is good customer", "not_final_customer": null, "cashed_vat": null, "tax_country_region": "PT-MA" }, "relationships": { "main_address": { "data": { "type": "addresses", "id": 1 } }, "addresses": { "data": [ { "type": "addresses", "id": 1 }, { "type": "addresses", "id": 2 } ] } } } }'; print($json);
Здесь я инициирую завиток, у меня уже есть токен и авторизация:
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,($url)); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS,($json)); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/vnd.api json', 'Accept: application/json', 'Authorization: Bearer ' . $token, )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); var_dump ($response); $response=json_decode($response,true); curl_close ($ch);
Это тот ответ, который у меня есть:
string(329) "{"errors":[{"status":"500 Internal Server Error","code":"JA006","detail":"Erro de sistema JA006: erro interno na base de dados. Por favor contacte o suporte técnico.","meta":{"internal-error":"in JsonapiJson::Value::operator[](ArrayIndex)const: requires arrayValue"}}],"jsonapi":{"version": "1.0","meta":{"libversion":"2.4.1"}}}"
Кто-нибудь, пожалуйста, может мне помочь? Спасибо!
Комментарии:
1.
application/vnd.api json
выглядит немного подозрительно.application/json
это обычный тип содержимого JSON (как и в вашем заголовке «Принять»). Кроме того, ошибка 500 на самом деле является ошибкой на стороне сервера, поэтому вам придется связаться с сопровождающими API, чтобы выяснить, почему произошел сбой. Лично я не вижу ничего явно неправильного в вашем коде, но, возможно, кто-то еще что-то заметит2. Вы получаете
JA006 system error: internal database error. Please contact technical support.
данные из API, поэтому обратитесь в их техническую поддержку
Ответ №1:
Ошибка API гласит следующее: in JsonapiJson::Value::operator[](ArrayIndex)const: requires arrayValue
.
Вы уверены, что JSON-правильный формат? Похоже, что вы, вероятно, предоставляете объект в JSON, где сервер ожидает массив объектов. Например, проверьте , должны ли data
, или relationships
, или addresses
быть массивами.
Мое главное предположение было бы вместо:
"addresses": { "data": [ { "type": "addresses", "id": 1 }, { "type": "addresses", "id": 2 } ] }
Может быть, так и должно быть
"addresses":[ { "type": "addresses", "id": 1 }, { "type": "addresses", "id": 2 } ]
Я, конечно, не могу сказать вам наверняка, так как я не знаю API, который вы пытаетесь использовать, но я сильно подозреваю, что это такой случай, когда он ожидает массив, но вы предоставляете объект.
Stay organized with collections
Save and categorize content based on your preferences.
The following document provides reference information about the status codes
and error messages that are used in the Cloud Storage JSON API. For
the page specific to the Cloud Storage XML API, see
HTTP status and error codes for XML.
Error Response Format
Cloud Storage uses the standard HTTP error reporting format for the
JSON API. Successful requests return HTTP status codes in the 2xx range. Failed
requests return status codes in the 4xx and 5xx ranges. Requests that require a
redirect returns status codes in the 3xx range. Error responses usually include
a JSON document in the response body, which contains information about the
error.
The following examples show some common errors. Note that the header
information in the responses is omitted.
The following is an example of an error response you receive if you try to
list the buckets for a project but do not provide an authorization header.
401 Unauthorized { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
403 Forbidden
This is an example of an error response you receive if you try to list the
buckets of a non-existent project or one in which you don’t have permission
to list buckets.
403 Forbidden { "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Forbidden" } ], "code": 403, "message": "Forbidden" } }
404 Not Found
The following is an example of an error response you receive if you try to
retrieve an object that does not exist.
404 Not Found { "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "Not Found" } ], "code": 404, "message": "Not Found" } }
409 Conflict
The following is an example of an error response you receive if you try to
create a bucket using the name of a bucket you already own.
409 Conflict { "error": { "errors": [ { "domain": "global", "reason": "conflict", "message": "You already own this bucket. Please select another name." } ], "code": 409, "message": "You already own this bucket. Please select another name." } }
The following table describes the elements that can appear in the response body
of an error. Fields should be used together to help determine the problem.
Also, the example values given below are meant for illustration and are not an
exhaustive list of all possible values.
Element | Description |
---|---|
code |
An HTTP status code value, without the textual description.
Example values include: |
error |
A container for the error information. |
errors |
A container for the error details. |
errors.domain |
The scope of the error. Example values include: global and push . |
errors.location |
The specific item within the locationType that caused the error. For example, if you specify an invalid value for a parameter, the location will be the name of the parameter.
Example values include: |
errors.locationType |
The location or part of the request that caused the error. Use with location to pinpoint the error. For example, if you specify an invalid value for a parameter, the locationType will be parameter and the location will be the name of the parameter.
Example values include |
errors.message |
Description of the error.
Example values include |
errors.reason |
Example values include invalid , invalidParameter , and required . |
message |
Description of the error. Same as errors.message . |
HTTP Status and Error Codes
This section provides a non-exhaustive list of HTTP status and error codes that
the Cloud Storage JSON API uses. The 1xx
Informational and 2xx
Success codes are not discussed here. For more information, see Response Status
Codes in RFC 7231 §6, RFC 7232 §4,
RFC 7233 §4, RFC 7235 §3, and RFC 6585.
302—Found
Reason | Description |
---|---|
found | Resource temporarily located elsewhere according to the Location header. |
303—See Other
Reason | Description |
---|---|
mediaDownloadRedirect | When requesting a download using alt=media URL parameter, the direct URL path to use is prefixed by /download . If this is omitted, the service will issue this redirect with the appropriate media download path in the Location header. |
304—Not Modified
Reason | Description |
---|---|
notModified | The conditional request would have been successful, but the condition was false, so no body was sent. |
307—Temporary Redirect
Reason | Description |
---|---|
temporaryRedirect | Resource temporarily located elsewhere according to the Location header. Among other reasons, this can occur when cookie-based authentication is being used, e.g., when using the Storage Browser, and it receives a request to download content. |
308—Resume Incomplete
Description |
---|
Indicates an incomplete resumable upload and provides the range of bytes already received by Cloud Storage. Responses with this status do not contain a body. |
400—Bad Request
[Domain.]Reason | Description |
---|---|
badRequest | The request cannot be completed based on your current Cloud Storage settings. For example, you cannot lock a retention policy if the requested bucket doesn’t have a retention policy, and you cannot set ACLs if the requested bucket has uniform bucket-level access enabled. |
badRequestException | The retention period on a locked bucket cannot be reduced. |
cloudKmsBadKey | Bad Cloud KMS key. |
cloudKmsCannotChangeKeyName | Cloud KMS key name cannot be changed. |
cloudKmsDecryptionKeyNotFound | Resource’s Cloud KMS decryption key not found. |
cloudKmsDisabledKey | Cloud KMS key is disabled, destroyed, or scheduled to be destroyed. |
cloudKmsEncryptionKeyNotFound | Cloud KMS encryption key not found. |
cloudKmsKeyLocationNotAllowed | Cloud KMS key location not allowed. |
corsRequestWithXOrigin | CORS request contains an XD3 X-Origin header. |
customerEncryptionAlgorithmIsInvalid | Missing an encryption algorithm, or the provided algorithm is not «AE256.» |
customerEncryptionKeyFormatIsInvalid | Missing an encryption key, or it is not Base64 encoded, or it does not meet the required length of the encryption algorithm. |
customerEncryptionKeyIsIncorrect | The provided encryption key is incorrect. |
customerEncryptionKeySha256IsInvalid | Missing a SHA256 hash of the encryption key, or it is not Base64 encoded, or it does not match the encryption key. |
invalidAltValue | The value for the alt URL parameter was not recognized. |
invalidArgument | The value for one of fields in the request body was invalid. |
invalidParameter | The value for one of the URL parameters was invalid. In addition to normal URL parameter validation, any URL parameters that have a corresponding value in provided JSON request bodies must match if they are both specified. If using JSONP, you will get this error if you provide an alt parameter that is not json . |
notDownload | Uploads or normal API request was sent to a /download/* path. Use the same path, but without the /download prefix. |
notUpload | Downloads or normal API request was sent to a /upload/* path. Use the same path, but without the /upload prefix. |
parseError | Could not parse the body of the request according to the provided Content-Type. |
push.channelIdInvalid | Channel id must match the following regular expression: [A-Za-z0-9\-_\+/=]+ |
push.channelIdNotUnique | storage.objects.watchAll ‘s id property must be unique across channels. |
push.webhookUrlNoHostOrAddress | storage.objects.watchAll ‘s address property must contain a valid URL. |
push.webhookUrlNotHttps | storage.objects.watchAll ‘s address property must be an HTTPS URL. |
required | A required URL parameter or required request body JSON property is missing. |
resourceIsEncryptedWithCustomerEncryptionKey | The resource is encrypted with a customer-supplied encryption key, but the request did not provide one. |
resourceNotEncryptedWithCustomerEncryptionKey | The resource is not encrypted with a customer-supplied encryption key, but the request provided one. |
turnedDown | A request was made to an API version that has been turned down. Clients will need to update to a supported version. |
userProjectInvalid | The user project specified in the request is invalid, either because it is a malformed project id or because it refers to a non-existent project. |
userProjectMissing | The requested bucket has Requester Pays enabled, the requester is not an owner of the bucket, and no user project was present in the request. |
wrongUrlForUpload | storage.objects.insert must be invoked as an upload rather than a metadata. |
401—Unauthorized
[Domain.]Reason | Description |
---|---|
AuthenticationRequiredRequesterPays | Access to a Requester Pays bucket requires authentication. |
authError | This error indicates a problem with the authorization provided in the request to Cloud Storage. The following are some situations where that will occur:
|
lockedDomainExpired | When downloading content from a cookie-authenticated site, e.g., using the Storage Browser, the response will redirect to a temporary domain. This error will occur if access to said domain occurs after the domain expires. Issue the original request again, and receive a new redirect. |
required | Access to a non-public method that requires authorization was made, but none was provided in the Authorization header or through other means. |
403—Forbidden
[Domain.]Reason | Description |
---|---|
accountDisabled | The account associated with the project that owns the bucket or object has been disabled. Check the Google Cloud console to see if there is a problem with billing, and if not, contact account support. |
countryBlocked | The Cloud Storage JSON API is restricted by law from operating with certain countries. |
forbidden | According to access control policy, the current user does not have access to perform the requested action. This code applies even if the resource being acted on doesn’t exist. |
insufficientPermissions | According to access control policy, the current user does not have access to perform the requested action. This code applies even if the resource being acted on doesn’t exist. |
objectUnderActiveHold | Object replacement or deletion is not allowed due to an active hold on the object. |
retentionPolicyNotMet | Object replacement or deletion is not allowed until the object meets the retention period set by the retention policy on the bucket. |
sslRequired | Requests to this API require SSL. |
stopChannelCallerNotOwner | Calls to storage.channels.stop require that the caller own the channel. |
UserProjectAccessDenied | The requester is not authorized to use the project specified in the userProject portion of the request. The requester must have the serviceusage.services.use permission for the specified project. |
UserProjectAccountProblem | There is a problem with the project used in the request that prevents the operation from completing successfully. One issue could be billing. Check the billing page to see if you have a past due balance or if the credit card (or other payment mechanism) on your account is expired. For project creation, see the Projects page in the Google Cloud console. For other problems, see the Resources and Support page. |
404—Not Found
Reason | Description |
---|---|
notFound | Either there is no API method associated with the URL path of the request, or the request refers to one or more resources that were not found. |
405—Method Not Allowed
Reason | Description |
---|---|
methodNotAllowed | The HTTP verb is not supported by the URL endpoint used in the request. This can happen, for example, when using the wrong verb with the /upload or /download URLs. |
408—Request Timeout
Reason | Description |
---|---|
uploadBrokenConnection | The request timed out. Please try again using truncated exponential backoff. |
409—Conflict
Reason | Description |
---|---|
conflict | A request to change a resource, usually a storage.*.update or storage.*.patch method, failed to commit the change due to a conflicting concurrent change to the same resource. The request can be retried, though care should be taken to consider the new state of the resource to avoid blind replacement of another agent’s changes. |
410—Gone
Description |
---|
You have attempted to use a resumable upload session or rewrite token that is no longer available. If the reported status code was not successful and you still wish to complete the upload or rewrite, you must start a new session. |
411—Length Required
Description |
---|
You must provide the Content-Length HTTP header. This error has no response body. |
412—Precondition Failed
Reason | Description |
---|---|
conditionNotMet | At least one of the pre-conditions you specified did not hold. |
orgPolicyConstraintFailed | Request violates an OrgPolicy constraint. |
413—Payload Too Large
Reason | Description |
---|---|
uploadTooLarge | This error arises if you:
|
416—Requested Range Not Satisfiable
Reason | Description |
---|---|
requestedRangeNotSatisfiable | The requested Range cannot be satisfied. |
429—Too Many Requests
[Domain.]Reason | Description |
---|---|
usageLimits.rateLimitExceeded | A Cloud Storage JSON API usage limit was exceeded. If your application tries to use more than its limit, additional requests will fail. Throttle your client’s requests, and/or use truncated exponential backoff. |
499—Client Closed Request
Description |
---|
The resumable upload was cancelled at the client’s request prior to completion. This error has no response body. |
500—Internal Server Error
Reason | Description |
---|---|
backendError | We encountered an internal error. Please try again using truncated exponential backoff. |
internalError | We encountered an internal error. Please try again using truncated exponential backoff. |
502—Bad Gateway
This error is generated when there was difficulty reaching an internal service.
It is not formatted with a JSON document. Please try again using
truncated exponential backoff.
503—Service Unavailable
Reason | Description |
---|---|
backendError | We encountered an internal error. Please try again using truncated exponential backoff. |
504—Gateway Timeout
This error is generated when there was difficulty reaching an internal service.
It is not formatted with a JSON document. Please try again using
truncated exponential backoff.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-02-07 UTC.
--Scan 1 item.
[
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:12:07.012"
}
]
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
--Successfully posted from B4A app to web service.
--Web service response:
{
"items": [
{
"RecordsInserted": "ok"
}
]
}
** Activity (uploadscandetail) Pause, UserClosed = true **
** Activity (setup) Resume **
** Activity (setup) Pause, UserClosed = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (scan) Create, isFirst = false **
** Activity (scan) Resume **
** Activity (scan) Pause, UserClosed = false **
** Activity (scan) Create, isFirst = false **
** Activity (scan) Resume **
** Activity (scan) Pause, UserClosed = false **
** Activity (scan) Create, isFirst = false **
** Activity (scan) Resume **
** Activity (scan) Pause, UserClosed = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (setup) Create, isFirst = false **
** Activity (setup) Resume **
** Activity (setup) Pause, UserClosed = false **
** Activity (uploadscandetail) Create, isFirst = false **
** Activity (uploadscandetail) Resume **
--Trying 7 records, which are all the same PLU item.
--It will fail with 500 internal server error.
--Following JSON character count: 1151
[
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:17.821"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:18.445"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:19.076"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:19.696"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:20.359"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:21.260"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:23.341"
}
]
ResponseError. Reason: Internal Server Error, Response: <!DOCTYPE html>
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>500 Internal Server Error</h1>
The server encountered a fatal error processing this request and could not continue.
<p>
<hr>
<address>Alpha Anywhere Application Server Application Server/12.0 Build/4119-4825 at SAV-APP1 Port 80</address>
</body></html>
** Activity (uploadscandetail) Pause, UserClosed = true **
** Activity (setup) Resume **
** Activity (setup) Pause, UserClosed = false **
** Activity (scanneditemsview) Create, isFirst = false **
** Activity (scanneditemsview) Resume **
** Activity (scanneditemsview) Pause, UserClosed = true **
** Activity (setup) Resume **
** Activity (setup) Pause, UserClosed = false **
** Activity (uploadscandetail) Create, isFirst = false **
** Activity (uploadscandetail) Resume **
--I then deleted one record, making 6 records.
--All the same PLU items.
--Post works fine.
--Following JSON character count: 987
[
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:17.821"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:18.445"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:19.696"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:20.359"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:21.260"
},
{
"hid": 1783,
"plu": "012000151163",
"qty": 1,
"price": "3.74",
"userid": "mark",
"scandatetime": "2017-10-20 12:14:23.341"
}
]
{
"items": [
{
"RecordsInserted": "ok"
}
]
}
** Activity (uploadscandetail) Pause, UserClosed = true **
** Activity (setup) Resume **
** Activity (setup) Pause, UserClosed = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = true **
При разработке API часто бывает так, что абсолютно все ответы даже с непредвиденными ошибками нужно отдавать в json-формате. В плане PHP, ошибки и эксепшены перехватывать достаточно легко. А вот 500, 502, 504, 404 и прочие ошибки могут генерироваться уже не на стороне PHP, а на стороне веб-сервера, например, nginx. В таком случае нужно править конфигурацию веб-сервера. Можно создать отдельный файл errors.conf:
error_page 500 =200 /500.json;
location /500.json {
return 500 '{"error": {"status_code": 500,"status": "Internal Server Error"}}';
}
error_page 502 =200 /502.json;
location /502.json {
return 502 '{"error": {"status_code": 502,"status": "Bad Gateway"}}';
}
error_page 503 =200 /503.json;
location /503.json {
return 503 '{"error": {"status_code": 503,"status": "Service Temporarily Unavailable"}}';
}
error_page 504 =200 /504.json;
location /504.json {
return 504 '{"error": {"status_code": 504,"status": "Gateway Timeout"}}';
}
error_page 400 =200 /400.json;
location /400.json {
return 400 '{"error": {"status_code": 400,"status": "Bad Request"}}';
}
error_page 401 =200 /401.json;
location /401.json {
return 401 '{"error": {"status_code": 401,"status": "Unauthorized"}}';
}
error_page 403 =200 /403.json;
location /403.json {
return 403 '{"error": {"status_code": 403,"status": "Forbidden"}}';
}
error_page 404 =200 /404.json;
location /404.json {
return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
}
error_page 408 =200 /408.json;
location /408.json {
return 408 '{"error": {"status_code": 408,"status": "Request Timeout}}';
}
error_page 418 =200 /418.json;
location /418.json {
return 418 '{"error": {"status_code": 418,"status": "I'm a teapot"}}';
}
А затем в добавить в конфигурацию нужного домена строку:
include errors.conf;
Можете кстати попробовать добавить это в контексте всех http серверов, судя по документации это не запрещено.
Кратко как это работает. Директива error_page имеет такой синтаксис:
error_page код ... [=[ответ]] uri;
Т.е. для указанного кода ответа можно переопределить сам код ответа, например, возвращать всегда код 200, а код ошибки сообщать уже в json-ответе. Также нужно указать uri с содержимым ответа. Это может быть как файл на диске, так и внутренний локейшен. Чем, собственно, и воспользуемся.
В объявлении локейшена нет ничего необычного, поэтому сразу рассмотрим его содержимое. Директива return может быть описана тремя способами:
return код [текст];
return код URL;
return URL;
В данном случае нас интересует только первый вариант. При указании любого кода, за исключением кодов 301, 302, 303, 307 и 308 можно задать тела ответа, которое будет отправлено клиенту. Также в тексте тела ответа можно использовать переменные.
Ещё один способ отдавать ошибки nginx в json-формате
Можно воспользоваться другим вариантом и хранить тексты ответов в отдельных файлах.
error_page 511 /errors/511.json;
error_page 507 /errors/507.json;
error_page 506 /errors/506.json;
error_page 451 /errors/451.json;
error_page 431 /errors/431.json;
error_page 429 /errors/429.json;
error_page 428 /errors/428.json;
error_page 424 /errors/424.json;
error_page 423 /errors/423.json;
error_page 422 /errors/422.json;
error_page 505 /errors/505.json;
error_page 504 /errors/504.json;
error_page 503 /errors/503.json;
error_page 502 /errors/502.json;
error_page 501 /errors/501.json;
error_page 500 /errors/500.json;
error_page 426 /errors/426.json;
error_page 417 /errors/417.json;
error_page 416 /errors/416.json;
error_page 415 /errors/415.json;
error_page 414 /errors/414.json;
error_page 413 /errors/413.json;
error_page 412 /errors/412.json;
error_page 411 /errors/411.json;
error_page 410 /errors/410.json;
error_page 409 /errors/409.json;
error_page 408 /errors/408.json;
error_page 407 /errors/407.json;
error_page 406 /errors/406.json;
error_page 405 /errors/405.json;
error_page 404 /errors/404.json;
error_page 403 /errors/403.json;
error_page 402 /errors/402.json;
error_page 401 /errors/401.json;
error_page 400 /errors/400.json;
location ^~ /errors/ {
internal;
root <PATH TO PARENT FOLDER OF ERRORS FOLDER>;
}
Post Views:
2 738