Struggling to figure out how to make graphql api calls with PHP. I'm trying to use the tezos domain API to convert a .tez domain to an address. My query is working well in their "playground", just can't get this translated to php.
Attempt 1:
$apiUrl = 'https://api.tezos.domains/graphql';
$query = '{
domains(where: { name: { in: "' . $wallet . '" } }) {
items {
address
}
}
}';
$data = #file_get_contents($apiUrl, false, stream_context_create([
'http' => [
'method' => 'POST',
'content' => json_encode(['query' => $query]),
]
]));
$results = json_decode($data, true);
echo $results;
$wallet = $results['data'];
Attempt 2:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tezos.domains/graphql" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"query":"{domains(where: {name: { in:"elli0t.tez"}}) {items {address}}}"}');
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Accept-Encoding: gzip, deflate, br',
'Content-Type: application/json',
'Accept: application/json',
'Connection: keep-alive',
'DNT: 1',
'Origin: https://api.tezos.domains' )
);
$result = curl_exec($ch);
print_r($result);
$info = curl_getinfo($ch);
print_r($info);
Attempt 2 at least returns me something.. it says I'm missing a query. Any thoughts?
Here is the curl command generated from the api's playground that appears to work. I'm just having trouble converting this to PHP:
curl 'https://api.tezos.domains/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://api.tezos.domains' --data-binary '{"query":"{\n domains(where: { name: { in: \"elli0t.tez\" } }) {\n items {\n address\n }\n }\n}"}' --compressed
From the GraphQL Docs I found this: a basic query with arguments:
{
human(id: "1000") {
name
height
}
}
Whereas your domains query looks like this:
{
domains(where: { name: { in: "' . $wallet . '" } }) {
items {
address
}
}
}
What strikes me as wrong syntax, because you can't find anywhere in the GraphQL Documentation an example for a structure like:
{
domains(where: { ... })
}
I don't know GraphQL, but I would pinpoint it on the colons inside the argument. The only thing I could find where this is allowed is using variables for creating mutations:
mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!)
{
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
So I guess what might be happening that the domain query breakes, or you are chaining your queries together.
I hope this might help you.
Related
Here's the code. Tried several variations of params. Any input would be great.
$endpoint = "https://api.stripe.com/v1/payments";
$params = array('limit' => '100', 'created[gte]' => '1627831313');
$url = $endpoint . '?' . http_build_query($params);
$ch = curl_init();
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: Bearer [OUR STRIPE KEY]';
curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
Here's the response we get:
curl https://api.stripe.com/v1/payments -u [OUR STRIPE KEY]: -d limit=3 -d created=1627831313 -G
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: created",
"param": "created",
"type": "invalid_request_error"
}
}
Silly question, are you just forgetting to write the $result somewhere to look at? Are you getting an empty response, or encountering an error?
Update: I think this is because you're calling the /payments endpoint, which is not what you want here. Change that path to /payment_intents (API ref). To get customers, subscriptions and invoices you'd need to make separate calls to each of those endpoints.
I am starting to use Wit.ai to enhance a small bot I made. I am able to make a request to the wit.ai by doing:
function sendToWitAI($query){
$witRoot = "https://api.wit.ai/message?";
$witVersion = "20170822";
$witURL = $witRoot . "v=" . $witVersion . "&q=" . $query;
$ch = curl_init();
$header = array();
$header[] = "Authorization: Bearer xxxxxxxx";
curl_setopt($ch, CURLOPT_URL, $witURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
return $server_output;
}
However, when receiving the output I just get the same message I sent. For example, if the user types "I want to make a reservation" my $server_output is now "I want to make a reservation" after all that chunk of code above.
Still, I know it reaches wit successfully because I can see it in the logs there and I know the bot says (from wit.ai):
{
"confidence": null
"action": null
"type": "action"
}
On top of this, if I just do a curl with the same query:
curl -XPOST 'https://api.wit.ai/converse?v=20170822&session_id=123abc&q=I%20want%20to%20make%20a%20reservation' \
> -H "Content-Type: application/json" \
> -H "Accept: application/json" \
> -H 'Authorization: Bearer xxxxxxxx'
I get the following output:
{
"confidence" : null,
"type" : "action",
"action" : null,
"entities" : {
"contact" : [ {
"suggested" : true,
"value" : "reservation",
"type" : "value",
"confidence" : 0.95062723294726
} ],
"intent" : [ {
"confidence" : 0.98638622681962,
"value" : "make_reservation"
} ]
}
}
I'm not sure where my error is or what I'm missing to properly handle use of the value like I need.
I've been googling non-stop but I can't find anything after they (wit.ai) deprecated "stories" and there's seldom anything about handling the response.
You're using 2 different end points: /message and /converse.
The log you pasted is from /converse so I'm not even sure your first call went through. Can you try a curl to /message like this
curl -XGET 'https://api.wit.ai/message?v=20170307&q=I%20want%20to%20make%20a%20reservation' \
-H 'Authorization: Bearer $TOKEN'
I'm trying to port this command to PHP:
curl -i -X POST http://website.com \
-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
-H "Accept: Application/json" \
-H "X-Requested-With: XMLHttpRequest" --data "var1=output1&var2=output2"
From bash it works.. I get this JSON output.
This is what I wrote in PHP to try to get the same result:
<?php
function blabla() {
$curl_parameters = array(
'var1' => "output1",
'var2' => "output2",
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://website.com");
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
"Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
"Accept" => "Application/json",
"X-Requested-With" => "XMLHttpRequest",
));
$output=curl_exec($ch);
curl_close($ch);
}
echo blabla();
?>
Unfortunately with this snippet I just get a 302 Found HTTP header as output (this).. seems like the variables are not passed (the --data part from the bash command).
The problem is with your CURLOPT_HTTPHEADER. It should be an array of strings like this:
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
'Accept: application/json',
'X-Requested-With: XMLHttpRequest',
));
How about just curl_setopt($ch,CURLOPT_POSTFIELDS, $curl_parameters);? I don't think you need to call http_build_query.
Try add curl follow 302 redirect
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Also make sure your http_build_query() function uses "&" as argument separator. On some PHP configurations it may be "& amp;" by default
$query = http_build_query($data, '', '&');
I made some php code and I was able to send notifications to devices using the regId.
I also managed to create a group of regId successfully receiving the notification_key as describe on the google documentation.
But I'm not able to send notifications to the group. I tried to use the same method to send the notification but instead of using the regId I am using the notification_key I received from GCM when creating the group, but this approach did not work, it gives me the NotRegistered error.
If i try to register with the same notification_key_name GCM say it is already registered.
I am not sure if I have to send it through another method or if I am doing something wrong.
When I send the notifications using the regId I receive this message
from GCM:
{"multicast_id":517...442,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:140...ecd"},{"message_id":"0:140...ecd"}]}
When I create the group I receive this message from GCM:
{"notification_key":"APA91....nz9Q"}
When I try to send the message to the group using the notification_key i received on the message above I receive this message from GCM:
{"multicast_id":80...63,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}
When I try to create the group again with the same notification_key_name I receive this message from GCM:
{"error":"notification_key already exists"}
Below is the code I am using.
<?php
class GCM {
const GOOGLE_API_KEY= " *** MY API KEY ***"; // Place your Google API Key
const PROJECT_KEY= " *** MY PROJECT KEY ***";
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message
);
$headers = array(
'Authorization: key=' . self::GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
public function requestNotificationKeyFromGCM($registatoin_ids, $username) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/notification';
$request = array(
'operation' => 'create',
'notification_key_name' => $username,
'registration_ids' => $registatoin_ids,
);
$headers = array(
'Authorization: key=' . self::GOOGLE_API_KEY,
'project_id: ' . self::PROJECT_KEY,
'content-type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
}
}
?>
I had similar issues while trying to send a gcm's with notification key. There is an issue in the documentation.
Instead of using:
curl -vvv -X POST --header "Content-Type: application/json" --header "project_id: <YOUR-PROJECT-ID>" --header "Authorization: key=<YOUR-PROJECT-SECRET-KEY>" --data #- "https://android.googleapis.com/gcm/send" << EOF
{
"registration_ids": ["<REGISTRATION-ID-FROM-DEVICE>"],
"data": {},
}
EOF
You have to use:
curl -vvv -X POST --header "Content-Type: application/json" --header "project_id: <YOUR-PROJECT-ID>" --header "Authorization: key=<YOUR-PROJECT-SECRET-KEY>" --data #- "https://android.googleapis.com/gcm/send" << EOF
{
"to": "<NOTIFICATION-ID>",
"data": {},
}
EOF
You can see more in my blog post: https://medium.com/appunite-edu-collection/d7df385b0ff4
I followed the documentation from Google's Documentation
(I'm pushing to both iOS and Android).
{
"to": "your_token_ID",
"data": {
"hello": "This is a Firebase Cloud Messaging Device Group Message!",
}
}
But it's not working so I tried:
{
"to": "your_token_ID",
"notification": {
"sound": "default",
"gcmSandbox": "true",
"badge": 1,
"title" : "Push Title",
"body": "Push Body"
}
}
This method is working for me, hope it helps somebody else.
Hi I'm trying to send this json object using the POST method but i'm not sure how to include the headers below, i was checking a lot of examples, but no one uses the headers below listed.
This is the code of my php processing page, this page will process the inputs received from a form.html and will create the json object to be transferred to the http server (external platform)
<?php
$host ="10.10.237.8";
$puerto = 21098;
$BUFF = 2048;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$conexion = socket_connect($socket, $host, $puerto);
if($conexion)
{
$msisdn=$_POST["msisdn"];
$mensaje=$_POST["mensaje"];
$php_array = array(
"numero" => $msisdn,
"mensaje" => "$mensaje",
);
$json_array=json_encode($php_array);
echo "Conexion Exitosa, puerto: " . $puerto."\n\n";
echo $json_array;
socket_write($socket, $json_array);
// Receive the results (if any) from the server
$server_response = socket_read($socket, $BUFF);
$decoded_response = json_decode($server_response, true); // decode the data received
echo $decoded_response['passphrase']; // and spit the results
}
else
{
echo "\nLa conexion TCP no se pudo realizar, puerto: ".$puerto;
}
socket_close($socket);
?>
these are the headers information, where i whould include them ? how to do it ? using cURL ? do you have a good example ?
POST /SMBULK/BATCH HTTP/1.0
Authorization: Basic dGVzdDp0ZXN0
Host: 10.10.237.8:21098
Content-Length: 395
User-Agent: Wget/1.12 (solaris2.10)
Content-Type: application/x-www-form-urlencoded
Connection: Keep-Alive
Accept: */*
I hope you can help me. The php code above is not working because some of the information (POST, Content-Length, Content-Type, User-Agent...etc ) is not being included (except "host" which did was included).
I managed to did this but it's not working:
<?php
$str_obj_json='{
"method":"SUBMIT","params":{
"batchType":"submit",
"batchId":"alvarons",
"origAddr":"550",
"origTon":2,
"userData":"Movistar les desea Feliz Navidad",
"submits":
[
{
"messId":"mess127_001",
"destAddr":"51975375377"}
]
}
}';
$ch = curl_init('http://10.10.237.8:21098/SMBULK/BATCH');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_obj_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: 395',
'Authorization: Basic dGVzdDp0ZXN0',
'User-Agent: Wget/1.12 (solaris2.10)',
'Connection: Keep-Alive',
'Accept: */*')
);
$result = curl_exec($ch);
?>
What is wrong ?
To send json object using cUrl you have to add "Content-Type: application/json" to header
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
'Content-type: application/json'
'Content-Length: 395',
'Authorization: Basic dGVzdDp0ZXN0',
'User-Agent: Wget/1.12 (solaris2.10)',
'Connection: Keep-Alive',
'Accept: */*');