Inviting people with Trello API - php

i'm trying to invite a person via email to Trello from my website. Here is the API reference. When I try to invite him, the plain reply is "invalid key". Here is my function:
public function inviteEmployeeToTrello ($email, $name, $isAdmin)
{
$organazationTrelloID = 'myOrganazationID';
$trelloAuthToken = 'myTrelloAuthToken';
$trelloInviteUrl = 'https://trello.com/1/organizations/'.$organazationTrelloID.'/members';
if ($isAdmin == 1)
{
$type = 'admin';
}
else
{
$type = 'normal';
}
$fields = array(
'fullName' => $name,
'email' => $email,
'type' => $type,
'token' => $trelloAuthToken
);
// open connection
$ch = curl_init();
// set the url, number of PUT vars, PUT data
curl_setopt($ch, CURLOPT_URL, $trelloInviteUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// exec
$replyRaw = curl_exec($ch);
$reply = json_decode($replyRaw, true);
// close connection
curl_close($ch);
dd($ch);
}

CURLOPT_POSTFIELDS does not want a JSON,
if you want a urlencoded request, use http_build_query($fields) , or if you want a multipart/form-data request, just give it $fields array directly. (the API doc's doesn't seem to mention which request types it accept, though. urlencoded is the most common one.)

As the error code says, you forgot to pass your application key. Here's an example from the API reference :
https://api.trello.com/1/organizations/publicorg?members=all&member_fields=username,fullName&fields=name,desc&key=[application_key]&token=[optional_auth_token]
You have to include it in your query, hence in your case, add it to the
$fields array :
$fields = array(
'fullName' => $name,
'email' => $email,
'type' => $type,,
'key' => $trelloAppKey
'token' => $trelloAuthToken
);

Related

How to return errors from MailChimp API v3.0 batch operation

I’m struggling with the new MailChimp API and the batch functionality, specifically, how to return any errors from the underlying operations that were batched, not the batch operation itself.
My code is below and works to add the two test subscribers. The response only shows success for the overall batch:
[errored_operations] => 0
If I run it again, it will return a similar response, but with two errors:
[errored_operations] => 2
Other than that, there is no indication as to what failed or why. In this case, we know that it’s because the users are already subscribed. If I try to add a single user without the batch call, using POST /lists/{list_id}/members, I get a response that details exactly what failed.
stdClass Object
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Member Exists
[status] => 400
[detail] => mary#jackson.net is already a list member. Use PUT to insert or update list members.
[instance] =>
)
How can I capture individual errors when adding (or updating or deleting) hundreds of subscribers?
I have tried just looping through users, making multiple individual calls, and that works: it adds the users and/or provides detailed error reporting. But it seems goofy to make 500 calls when the API is set up to handle this in a single call. Thanks for any ideas!
Here is my code:
$list_id = 'xyz123';
$subscribers = array(
array(
'email' => 'jeff#jackson.net',
'status' => 'subscribed',
'firstname' => 'Jeff',
'lastname' => 'Jackson'
),
array(
'email' => 'mary#jackson.net',
'status' => 'subscribed',
'firstname' => 'Mary',
'lastname' => 'Jackson'
)
);
$add_subs_batch = add_subs_batch($list_id, $subscribers);
echo '<pre>add_subs_batch: ';
print_r($add_subs_batch);
echo '</pre>';
function add_subs_batch($list_id, $data) {
$method = 'POST';
$batch_path = 'lists/' . $list_id . '/members';
$result = mc_request_batch($method, $batch_path, $data);
if($result && $result->id) {
$batch_id = $result->id;
$batch_status = get_batch_status($batch_id);
return $batch_status;
}
else {
return $result;
}
}
function get_batch_status($batch_id, $i=1) {
$method = 'GET';
$target = 'batches/'.$batch_id;
$result = mc_request($method, $target, $data);
sleep(1); // wait 1 second and try
if($result->status == 'finished' ) {
return $result;
}
else {
return get_batch_status($batch_id, $i+1);
}
}
function mc_request_batch( $method, $batch_path, $data = false ) {
$api_key = '12345-us1';
$dataCenter = substr($api_key,strpos($api_key,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/';
$target = 'batches';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $target );
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT' );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if( $data ) {
$batch_data = new stdClass();
$batch_data->operations = array();
foreach ($data as $item) {
$batch = new stdClass();
$batch->method = $method;
$batch->path = $batch_path;
$batch->body = json_encode( array(
'email_address' => $item['email'],
'status' => $item['status'],
'merge_fields' => array(
'FNAME' => $item['firstname'],
'LNAME' => $item['lastname']
)
) );
$batch_data->operations[] = $batch;
}
$batch_data = json_encode($batch_data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $batch_data );
$response = curl_exec( $ch );
}
curl_close( $ch );
return json_decode($response);
}
You will get an id in response of the batch operation. This is 'Batch ID' which is a string that uniquely identifies the batch request.
To get the status of a batch request, you have to call a GET request to the URL, /batches/{batch_id}.
From the response, you can find a URL in response_body_url field which has the gzipped archive of the results of all the operations in the batch call.
Reference:
http://developer.mailchimp.com/documentation/mailchimp/reference/batches
http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-batch-operations/
Note
For security reasons, response_body_url is only valid for 10 minutes.
After 10 minutes, generate another with a GET call to
/3.0/batches/{batch_id}.
After you make the batch operation request, results are available for
7 days.

Adding interest groups When creating new subsciber in Mailchimp API 3

Hoping for some help as can't find an answer anywhere.
I am using the following PHP function to add a subscriber to mailchimp. This works fine. What I need to do is add the user with one or more group interests assigned. So for example I have a Group named "Test Group" which contains two interests "Test 1" and "Test 2". How would I amend the below function to include 1 or more interest values?
function mc_subscribe($email, $fname, $lname, $apikey, $listid, $server) {
$auth = base64_encode( 'user:'.$apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'api.mailchimp.com/3.0/lists/'.$listid.'/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);
return $result;
};
The documentation contains enough information to figure this out, even though it doesn't say so directly.
You'll need to add an interests object to your request. It should take interest IDs as keys and boolean values as false. So you could update your code above as follows:
$data = array(
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
),
'interests' => array(
'9143cf3bd1': true
)
);
Note that you'll need to get the IDs from the API, as there's no way to collect them from the web app, and also you should remove the apikey element from your request it is no longer used.

Use collapse key for 2 type ofmessages gcm

In my gcm android app I am sending 2 types of messages from application server.I got the idea about what is collapse key, but Idont know how to use.These are the two types of messages.
1.
$message = array(
"price" => "signal",
"type" => $user_type,
"date" => $date1,
"name" => $signal_name,
"buy" => $price,
"stop" => $stop,
"tv" => $trig_value,
"tp" => $profit,
"res" => $result,
);
second one
$message = array(
"price" => "instru",
"price1" => $trade1,
"price2" => "$trade2",
"price3" => "$trade3",
"price4" => "$trade4",
"price5" => "$date"
);
What I need is the last messages send for both of the message types persist in gcm server.How can I do that.I am giving the gcm class also .Please help.
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key='.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));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
You should add the collapse_key parameter to your JSON.
The JSON should look like this :
For example, for the first type :
{
"registration_ids":["...", "..."],
"collapse_key": "type1",
"data": {
"price" => "...",
"type" => "...",
...
},
}
For the second type, give a different value to collapse_key.
Based on your code and my limited knowledge of PHP, you need something like this :
$fields = array(
'collapse_key' => $collapse_key,
'registration_ids' => $registatoin_ids,
'data' => $message,
);
And the $collapse_key should be initialized based on the type of data you have in $message.

Getting error in setting Transdirect Shipping sender APi code

I am trying to implement transdirect.com shipping set sender API to my website but i am getting error i don't know what is the main cause of it.
here is the snippet::
$params = array(
'session' => $session,
'postcode' => '2164',
'name' => 'abc',
'company'=>'abc',
'email' => $email ,
'phone' => '4561237',
'streetName' => 'abcStreet',
'streetNumber' => '28',
'streetType' => 'St',
'suburb' => 'JHONFEILD',
'state' => 'NSW',
'pickupDate' => date( 'Y-m-d' ),
'pickupTime' => '1-4pm',
'hydraulicGate' =>'false'
);
$query = http_build_query($params);
$query = 'http://transdirect.com.au/api/v2/booking/sender?'.$query;
$result = json_decode( curl_sender( $query, $session, $email, $arg = 'sender') );
// curl_sender method::
function curl_sender( $url, $session, $email, $arg ) {
if ( $arg == 'sender' ) {
$datastring = "postcode=2164&name=Tara Trampolines&company=abc&email=".$email."&phone=0280049375&streetName=Unit 4/28 Victoria St&streetNumber=28&streetType=St&suburb=SMITHFIELD&state=NSW&pickupDate". date( 'Y-m-d' )."&pickupTime=1-4pm&hydraulicGate=false";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data1 = curl_exec( $ch );
curl_close( $ch );
return $data1;
}
I am getting:
stdClass Object (
[message] => Must be authenticated-please create a session first.
[code] => 403
)
Here is the link from we have implemented the api::
http://transdirect.com.au/api/v2/documentation
please specify how we can authenticate each method.
Any help will be appreciable, Thanks in advance.
You've to create a valid session before you requesting the API.
Create the session:
$credentials = array(
'email' => 'test#example.com',
'password' => 'secret'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Take a look at the session part: http://transdirect.com.au/api/v2/documentation
You can't mix the session creation process and the real API request.
Create session
Create API request with this session from step 1.
I'm not sure but I think you don't have to use the valid session as any parameter.
The documentation says only create a valid session, there is no parameter specified to append the session, so creation is maybe enough.
This is maybe very important for you:
Confirm booking with any special instructions etc. Once the booking is
confirmed your session is cleared and you will need to
re-authenticate.

get amp; symbol using http_build_query

I am submitting some data from website1 to website2 using curl.
When I submit data via then on receiving end I get it like
Array
(
[ip] => 112.196.17.54
[amp;email] => test#test.com
[amp;user] => test123,
[amp;type] => point
[amp;password] => password
)
According to me http_build_query() producing wrong results.
"ip" field is correct rest are incorrect.
Please let me know why it happens.
curl function is given below: http_build_query($config)
function registerOnPoints($username ,$password,$email,$ip , $time )
{
$ch = curl_init("http://website2c.com/curl-handler");
curl_setopt(
$ch, CURLOPT_RETURNTRANSFER, 1);
$config = array( 'ip' => $ip,
'user' => $username,
'email' => $email,
'password'=> $password,
'time' => $time,
'type' => 'point') ;
# add curl post data
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($config));
curl_setopt($ch, CURLOPT_POST, true);
# execute
$response = curl_exec($ch);
# retreive status code
$http_status = curl_getinfo($ch , CURLINFO_HTTP_CODE);
if($http_status == '200')
{
$response = json_decode($response);
} else {
echo $http_status;
}
// Close handle
curl_close($ch);
}
If it is php version issue then, clearly speaking I have no permission to change the version of php because only the curl function is producing error rest project is completed and working as expected.
Please help me.
i guess you could try:
http_build_query($config, '', '&');
Or alternative:
$paramsArr = array();
foreach($config as $param => $value) {
$paramsArr[] = "$param=$value";
}
$joined = implode('&', $paramsArr);
//and use
curl_setopt($ch, CURLOPT_POSTFIELDS, $joined);

Categories