I am using the following code to initiate a member add request to a list in MailChimp.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
$email = 'test#domain.com';
$first_name = 'name';
$last_name = 'last name';
$api_key = 'xx-us18'; // YOUR API KEY
// server name followed by a dot.
// We use us13 because us13 is present in API KEY
$server = 'us18.';
$list_id = 'xx'; // YOUR LIST ID
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $first_name,
'LNAME' => $last_name
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'api.mailchimp.com/3.0/lists/'.$list_id.'/members');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
echo $result;
?>
But what happened is the response is 404.
{
type: "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
title: "Resource Not Found",
status: 404,
detail: "The requested resource could not be found.",
instance: "78a35efa-ef43-471d-9e70-aecdc992d2e6"
}
Does anyone know what I am doing wrong? What might be the reason for this error?
Extra Infos: API Key is valid, If I provide that wrong, I am getting another error.
List-id is also true.
I am running this code on localhost with MAMP.
The issue was I used web_id instead of list_id.
When I changed that, the issue was resolved.
Related
Can't seem to find an error in my PHP code. I am trying to add a customer over Shopify API, below is my code. I tried the same URL using Postman and it worked - the user gets added when I add the same JSON string. So I know that API is enabled properly with correct permissions within Shopify.
$API_KEY = '****';
$PASS = '****';
$STORE_URL = '****';
$DATE = "2021-07";
$USER_EMAIL = 'test#test.com';
$baseUrl = 'https://'.$API_KEY.':'.$PASS.'#'.$STORE_URL.'/admin/api/'.$DATE.'/customers.json';
// post to: POST /admin/api/2021-07/customers.json
$data = array('customer' =>
array(
'first_name' => 'Promo',
'last_name' => 'User',
'email' => $USER_EMAIL,
'accepts_marketing' => 'true',
),
);
echo "test post data:";
echo json_encode($data);
$session = curl_init( $baseUrl );
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($session, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($session, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
$response = curl_exec($session);
curl_close($session);
$json = json_decode( $response, true );
echo "test return data:";
var_dump($json);
The code prints the following, returning NULL and no customer is added:
test post data:{"customer":{"first_name":"Promo","last_name":"User","email":"test#test.com","accepts_marketing":"true"}}test return data:NULL
Can anyone spot what am I doing wrong here?
Never mind, I just figured it out.
The line
curl_setopt($session, CURLOPT_CUSTOMREQUEST, 'PUT');
Should be
curl_setopt($session, CURLOPT_CUSTOMREQUEST, 'POST');
I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.
I have this code below that adds a user to a pre-existing list in Mailchimp.
$apikey = '<api_key>';
$auth = base64_encode( 'user:'.$apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $name
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
var_dump($result);
die('Mailchimp executed');
This code only adds users to the list and when I try add the details of the same user twice it throws the following error on the second attempt:
test#user.com is already a list member. Use PATCH to update existing members.
How do I go about using PATCH to update user details? I'm not sure where to specify it.
I figured out where I'm going wrong. When the user is initially added to the list the response provides an ID. I need to store the ID in my database with those person's details and reference the ID in the url I'm making a call to when I want to update the user's details in the Mailchimp List.
https://us2.api.mailchimp.com/3.0/lists/<list_id_goes_here>/members/<members_id_goes_here>
Thanks #TooMuchPete for the correct curl command.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
You're looking for the CURLOPT_CUSTOMREQUEST option in cURL.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
But, since this is now your second question in as many days asking how to use built-in cURL library, it might be worth using something a little better. If you're on PHP 5.4 or better, I recommend Guzzle. PHP Requests is also very good, though, and works with PHP 5.3.
Try this one. It's working for me. I am using this function. Hope it should be solved your problem.
<?php
/**
* Created by PhpStorm.
* User: Faisal
* Website: www.faisal-ibrahim.info
* Date: 2/12/2016
* Time: 10:07 AM
*/
if (isset($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = 'faisal.im048#gmail.com';
}
$data = [
'email' => $email,
'status' => 'subscribed',
'firstname' => 'Faisal',
'lastname' => 'Ibrahim'
];
$api_response_code = listSubscribe($data);
echo $api_response_code;
/**
* Mailchimp API- List Subscribe added function.In this method we'll look how to add a single member to a list using the lists/subscribe method.Also, We will cover the different parameters for submitting a new member as well as passing in generic merge field information.
*
* #param array $data Subscribe information Passed.
*
* #return mixed
*/
function listSubscribe(array $data)
{
$apiKey = "cf8a1fd222a500f27f9e042449867c7c-us15";//your API key goes here
$listId = "e8f3f5f880";// your trageted list ID
$memberId = md5(strtolower($data['email']));
$dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => [
'FNAME' => $data['firstname'],
'LNAME' => $data['lastname']
]
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
All I want is basically to login, display info from a simple filter like all open bugs in a milestone. Once I get that far ill be able to work off the documentation
I'm hoping to use simple PHP, that's because I'm new to PHP so the more complicated the coding is the harder it will be for me to figure it out.
This script is the closest I've come to being successful:
<?php
define('JIRA_URL', 'https://mysite.atlassian.net');
define('USERNAME', 'me#gmail.com');
define('PASSWORD', '11111');
function post_to($resource, $data) {
$jdata = json_encode($data);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_URL => JIRA_URL . '/rest/api/2/' . $resource,
CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
function create_issue($issue) {
return post_to('issue', $issue);
}
$new_issue = array(
'fields' => array(
'project' => array('key' => 'FOO'),
'summary' => 'Test via REST',
'description' => 'Description of issue goes here.',
'issuetype' => array('name' => 'Story')
)
);
$result = create_issue($new_issue);
if (property_exists($result, 'errors')) {
echo "Error(s) creating issue:\n";
var_dump($result);
} else {
echo "New issue created at " . JIRA_URL ."/browse/{$result->key}\n";
var_dump($result);
}
?>
It returns New issue created at http://mysite.atlassian.net/browse/
But when I put the var_dump ($result) in there that just returns null so I have no idea if the jira URL is wrong or my password or if its outdated code for the new rest API.
If I could just make 1 simple query to the API and see anything returned on my PHP page I would be a happy camper. The example above creates a new issue, that's just the example I was using but I'm fine with just returning any sort of data so my main issue is getting a valid connection and returning some info so I know its working and can't start trying some different things then.
I have admin access but I wasn't clear if I needed to enable something on the admin side.
I figured out what i needed to do, there are lots of examples on the net but i couldnt find one simple like this so hopefully it helps someone else
$username = 'xxx';
$password = 'xxx';
$url = 'https://xxx.atlassian.net/rest/api/2/Issue/Bug-5555';
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$issue_list = (curl_exec($curl));
echo $issue_list;
Following to this page...
https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-basic-authentication
We need to use header authentication these days which looks - modifying the example in this tread - like:
$username = 'user';
$password = 'pass';
$url = 'https://www.jiradomain.com/rest/api/2/issue/PROJECT-321/worklog';
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode("$username:$password")) );**
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'rw+');
curl_setopt($curl, CURLOPT_STDERR, $verbose);
$issue_list = (curl_exec($curl));
echo $issue_list;
$result = curl_exec($curl);
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($curlHandle),
htmlspecialchars(curl_error($curlHandle)));
}
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
I need to send some data from my form in html to webservice. (For do this, i need to do the operation of POST)
I have seen research that I can transmit information using php cURL. But in all examples, i don't view to send data to webservice, only to file php that print $_POST variable.
I have this webservice: http://192.168.1.1/fastfood/event/attendee (example)
And i try to send data in an array.
For example i try to send: attendee = array( 'name' => $_POST['name'] , 'lastname' => $_POST['lastname'] , 'address' => $_POST['address'] );
Then, the web service takes out the array data. ¿How to do this?
UPDATE 1:
This is my code that i'm doing now... But don't work :(
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$attendee = array(
'name' => "$name",
'lastname' => "$lastname",
'address' => "$address"
);
$url_target = 'http://192.168.1.1/fastfood/event/attendee';
//$header = array('Content type: multipart/form-data');
$user = 'root';
$pass = '123';
$userpasswd = "$user:$pass";
$ch = curl_init($url_target);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
//curl_setopt($ch, CURLOPT_URL, $url_target);
//curl_setopt($ch, CURLOPT_HEADER, TRUE);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
$getInfo = curl_getinfo($ch);
curl_close($ch);
The variable $result return me a FALSE, and the variable $getInfo return me a http_code = 500, Content-Type = Null.
Reading the documentation of cURL when i send a data like a array, the content type should be a "multipart/form-data" but, also, don't work for me.
// Here is the data we will be sending to the service
$data = array(
'name' => $_POST['name'],
'lastname' => $_POST['last_name'],
'address' => $_POST['address']
);
$curl = curl_init('http://192.168.1.1/fastfood/event/attendee');
curl_setopt($curl, CURLOPT_POST, 1); //Choosing the POST method
curl_setopt($curl, CURLOPT_URL, 'http://localhost/helloservice.php'); // Set the url path we want to call
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data); // Insert the data
// Send the request
$result = curl_exec($curl);
// Free up the resources $curl is using
curl_close($curl);
echo $result;
Written by Chad Lung at GiantFlyingSaucer