How do I post to GraphQL from PHP - php

I have the following curl request to GraphQL. It works great, but in production shell_exex is not allowed. How do I re-write this curl post in valid PHP?
$curl_string = 'curl -g -X POST -H "Content-Type: application/json" -H "Authorization: Bearer "' . AIRTABLE_API_KEY;
$curl_second_string = ' -d \'{"query": "{fullCapaReview (id: \"' . $id . '\") {proposedRuleName submissionDate agencyContactName statusLawDept}}"}\' https://api.baseql.com/airtable/graphql/appXXXzzzzzzzzzz';
$curl_complete_string = "$curl_string $curl_second_string";
$result = shell_exec($curl_complete_string);
edit: I'm sorry, I put the wrong query. The query I had in mind was:
' -d \'{"query": "{dMsAgencies (agencyAcronym: \"' . $_agency . '\") {agencyAcronym fullCapaReview { id }}}"}\'
I make two similar calls. I will leave the original there because someone answered based on that.
This is what I have so far:
$curl = curl_init($url);
$query = 'query dMsAgencies($agencyAcronym: String) {agencyAcronym fullCapaReview { id }} ';
$variables = ["agencyAcronym" => $id ];
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['query' => $query, 'variables' => $variables]));
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json','Authorization: Bearer ' . AIRTABLE_API_KEY]);
$response = curl_exec($curl);
curl_close($curl);
console_log("Response : " . $response);
This is the error message I am getting. I just want to see if I am in the ballpark with my syntax.
Response : {"errors":[{"message":"Cannot query field \"agencyAcronym\" on type \"Query\".","locations":[{"line":1,"column":44}],"stack":["GraphQLError: Cannot query field \"agencyAcronym\" on type \"Query\"."," at Object.Field (/var/app/current/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js:46:31)"," at Object.enter (/var/app/current/node_modules/graphql/language/visitor.js:323:29)"," at Object.enter (/var/app/current/node_modules/graphql/utilities/TypeInfo.js:370:25)"," at visit (/var/app/current/node_modules/graphql/language/visitor.js:243:26)"," at validate (/var/app/current/node_modules/graphql/validation/validate.js:69:24)"," at graphqlMiddleware (/var/app/current/node_modules/express-graphql/index.js:133:32)"," at processTicksAndRejections (internal/process/task_queues.js:95:5)"]},{"message":"Variable \"$agencyAcronym\" is never used in operation \"dMsAgencies\".","locations":[{"line":1,"column":19}],"stack":["GraphQLError: Variable \"$agencyAcronym\" is never used in operation \"dMsAgencies\"."," at Object.leave (/var/app/current/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js:38:33)"," at Object.leave (/var/app/current/node_modules/graphql/language/visitor.js:344:29)"," at Object.leave (/var/app/current/node_modules/graphql/utilities/TypeInfo.js:390:21)"," at visit (/var/app/current/node_modules/graphql/language/visitor.js:243:26)"," at validate (/var/app/current/node_modules/graphql/validation/validate.js:69:24)"," at graphqlMiddleware (/var/app/current/node_modules/express-graphql/index.js:133:32)"," at processTicksAndRejections (internal/process/task_queues.js:95:5)"]}]}
message":"Cannot query field \"agencyAcronym\" on type \"Query\"
{"message":"Variable \"$agencyAcronym\" is never used in operation \"dMsAgencies\".","locations":[{"line":1,"column":19}]

The queries are not the same, but assuming that you are aware, your PHP example also has a syntax issue.
query dMsAgencies($agencyAcronym: String) {
agencyAcronym
fullCapaReview {
id
}
}
If you compare this with the example in the docs (when using variables) you can see that you are currently not using the $agencyAcronym variable anywhere (and there probably isn't a query named agencyAcronym in your schema). Here is one example (using the query from your first snippet):
query dMsAgencies($agencyAcronym: String) {
fullCapaReview (id: $agencyAcronym) {
proposedRuleName
submissionDate
agencyContactName
statusLawDept
}
}

Related

Filemaker api retruns 958 error code in php

I am trying to access FileMaker by using curl PHP. here I am not using filmmaker PHP class. I am importing the records from the filmmaker into the Prestashop site. when admin delete the product in the Prestashop its also deleted in the FileMaker database
$nome = 'http://ipaddress:port/fmi/xml/FMPXMLRESULT.xml?-db=tablename&-lay=export&recordid=$recordid&-delete';
$cURL = curl_init($nome);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_FAILONERROR, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, $header_fields);
$response = curl_exec($cURL);
if ($cURL_err = curl_errno($cURL)) {
die(__FILE__ . "(" . __LINE__ . "): Communication Error: (' . $cURL_err . ')" .
curl_error($cURL));
}
curl_close($cURL);
//Removed the Headers.
when I am executing the code filmmaker return error code 958.
after some analyze.
if we want edit,delete,update the record in the filemaker.we must use the -recid.
i made mistake on API
$nome = 'http://ipaddress:port/fmi/xml/FMPXMLRESULT.xml?-db=tablename&-lay=export&recordid=$recordid&-delete';
it should be
$nome = 'http://ipaddress:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&-recid=$recordid&-delete';
after changed its working correctly.Here I attached some example API for getting records and update the records.
GET all records
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=layout&-findall
Get range of records
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=Magazzino&-lay=export&-max=100&-findall
Get specific Record
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&fieldname=field_value&-find
Insert New
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&fieldname=field_value&-new
edit record
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&-recid=record_id&-edit
NOTE: Two way to access filmmaker database 1.using FileMaker class.2.using API

Converting command-line cURL where URL is piped to python

I have this command-line cURL example:
curl -X PUT -H "X-Auth-Token: $AUTH_TOKEN" \
-d "{\"data\":{\"name\":\"Device1 Callflow\", \"numbers\":[\"1001\"], \"flow\":{\"module\":\"device\",\"data\":{\"id\":\"$DEVICE_ID\"}}}}" \
http://ip.add.re.ss:8000/v2/accounts/$ACCOUNT_ID/callflows | python -mjson.tool
My task is to convert this into a PHP function, where the needed values are passed into the function:
function someFunc($AUTH_TOKEN, $ACCOUNT_ID, $DEVICE_ID, $numbers) {}
Normally, I use this sort of code:
function setLimits($auth_token, $accountID, $feature1_cnt, $feature2_cnt) {
$service_url = "http://ip.add.re.ss:8000/v2/accounts/$accountID/limits";
$data = '{"data":{"feature1": ' . $feature1_cnt . ',"feature2": ' . $feature2_cnt . '}}';
$ch = curl_init($service_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Auth-Token: $auth_token",'Content-Type: application/json', 'Content-Length: ' . strlen($data)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
$info = curl_getinfo($ch);
curl_close($ch);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
$decoded = json_decode($response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
return(true);
}
BUT, for a specific API call, I need to pass this as the service URL:
http://ip.add.re.ss:8000/v2/accounts/$ACCOUNT_ID/callflows | python -mjson.tool
How do I do that?
First, change:
$data = '{"data":{"feature1": ' . $feature1_cnt . ',"feature2": ' . $feature2_cnt . '}}';
to:
$data = [
"data" => [
"feature1" => $feature1_cnt,
"feature2" => $feature2_cnt
]
];
You will make a mistake typing out JSON, and it won't be easy to find or fix.
Second, python -mjson.tool
json.tool [...] to validate and pretty-print:
PHP's JSON validation is pretty much just checking if json_decode() returned NULL, and then you can check json_last_error() and json_last_error_msg() for error info. It is not robust.
You can encode JSON in "pretty-printed" format with:
json_encode($foo, JSON_PRETTY_PRINT);
But I can't think of an earthly reason why you would want to do that other than if there are human eyeballs that are going to be looking at it.
Lastly, in answering your question I've realized that I have no actual idea what you're getting at and you really need to clarify why you think you need to do anything you asked about. [other than the validation, I suppose]

Send php array of device tokens to Urban Airship push

I am very suck. I am trying to send to a php array of device id's with urban airship. I am using the first example found here. Everything works, with "audience"=>"all". Every registered device gets hit. I need to make a query of a database, that has a bunch of device id's in it, and send to those device id's. What do I change "audience"=>"all" to so I can do that. I have tried everything!
Here is the code incase the link breaks:
<?php
define('APPKEY','XXXXXXXXXXXXXXX'); // Your App Key
define('PUSHSECRET', 'XXXXXXXXXXXXXXX'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
$contents = array();
$contents['badge'] = "+1";
$contents['alert'] = "PHP script test";
$contents['sound'] = "cat.caf";
$notification = array();
$notification['ios'] = $contents;
$platform = array();
array_push($platform, "ios");
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo $content; // just for testing what was sent
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
echo "Got negative response from server, http code: ".
$response['http_code'] . "\n";
} else {
echo "Wow, it worked!\n";
}
curl_close($session);
?>
It depends on what device OS you are trying to send to. Via their documentation here:
http://docs.urbanairship.com/reference/api/v3/push.html#atomic-selectors
you will need to set the correct device type to it's corresponding ID. For example:
android:
"audience" : {
"apid" : "b8f9b663-0a3b-cf45-587a-be880946e880"
}
ios:
"audience" : {
"device_token" : "C9E454F6105B0F442CABD48CB678E9A230C9A141F83CF4CC03665375EB78AD3A"
}
I found a possible solution for this from urban airship help center... They suggest this. And its working for me.
You can send to multiple device tokens or APIDs in a single request. I would suggest using our new API v3 and batching up your requests. There are a couple ways to do this:
1) Send to multiple devices in one payload
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '{"audience" : {"OR": [{"device_token":"<DeviceToken1>"}, {"device_token":"<DeviceToken2>"}, {"device_token":"<DeviceToken3>"}]}, "notification" : {"alert" : "Hello iOS devices!"}, "device_types" : ["ios"]}' https://go.urbanairship.com/api/push/
OR
2) Put multiple payloads together in one batch
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '[{"audience": {"device_token": "<DeviceToken1>"}, "notification": {"alert": "Hello, I was sent along with a batch of other pushes!"}, "device_types": ["ios"]}, {"audience": {"device_token": "<DeviceToken2>"}, "notification": {"alert": "I was also sent with a batch of other pushes!"}, "device_types": ["ios"]}, {"audience": {"device_token": "<DeviceToken3>"}, "notification": {"alert": "Me three!"}, "device_types": ["ios"]}]' https://go.urbanairship.com/api/push/
Switched to the PHP 2 library for Urban Airship and I was able to send to individual device tokens. I was also able to read tokens out of an array, and assign the array value as the target. Version 2 found here.

Docusign REST call from CodeIgniter

I'm trying to call the DocuSign REST login information within a CodeIgniter application. The Docusign sample code shows:
// Input your info here:
$integratorKey = '...';
$email = '...#....com';
$password = '...';
$name = 'John Doe';
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
I keep getting a status response of 0. When I echo out the curl all the xml tags have been converted to lowercase (which won't work with Docusign). Has anyone done this call within CodeIgniter? How did you accomplish it? I know my credentials are good because I can do a command line curl and get a response.
I'm not sure what CodeIgniter is doing and why the tags would be converted to lower case but you're right in that DocuSign expects xml tags to begin with a capital letter so that might not work. What you can do, though, is use JSON headers and request bodies instead.
For instance, instead of an XML formatted authentication header like
<DocuSignCredentials>
<Username>username</Username>
<Password>password</Password>
<IntegratorKey>integrator_key</IntegratorKey>
</DocuSignCredentials>
You could use the corresponding JSON auth header like
{
"Username": "username",
"Password": "password",
"IntegratorKey": "integrator_key"
}
The "nodes" still start with a capital but since it's not xml I'm wondering if CodeIgniter maybe leaves it alone. Examples of this can be found at the DocuSign Developer Center on this page.

PHP - run GET curl, get result

I wanna run a GET curl in php A to get data from php B.
This is an example in php A (I got from here http://support.qualityunit.com/061754-How-to-make-REST-calls-in-PHP)
//next example will recieve all messages for specific conversation
$service_url = 'http://localhost/test/getFrom.php?id=1';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
And I tried this example as well (Trying to use curl to do a GET, value being sent is allows null)
In php B.
It will get the ID, run some script and will generate an ARRAY.
I want to get this ARRAY from B to A.
B will run only when A request GET from B.
The problem is I don't how the ARRAY can pass from B to A.
Please give some advice THANK YOU.
The code you provided is expecting back a JSON encoded array. The easiest way to do this is simply JSON encode your array in PHP B and echo it to the page.
Then CURL will be able to read the contents of PHP B, decode and process as required.
// PHP B
<?php
// Check for $_GET params
// Get ID
$id = $_GET['id'];
// Do processing, query etc
....
// Format and display array as JSON
echo(json_encode($result_array));
die();
?>
Also note:
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
The code is expecting the array to be formatted in a particular way. So either match your array in PHP B to the same format, or update the code to your needs.

Categories