I wanted to share this and also seek testing by others to hone this code. If you use maven link, this may be helpful to you in making a project on there from an online form. We use the form submission to do several internal functions with our file sever and the like.
At any rate here is the code. Further testing needs done specifically around the PUT function:
///// CREATE THE MAVEN LINK PROJECT /////
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// MAKE SURE CURL DOES NOT OUTPUT TO PAGE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//SET HEADERS FOR AUTH
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer !---INSERT-0-AUTH-TOKEN---!', 'Expect:'
));
//PUT REQUIRES ADDITIONAL HEADERS
if ($method == "PUT")
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT',
'Authorization: Bearer !---INSERT-0-AUTH-TOKEN---!', 'Expect:'
));
curl_setopt($curl, CURLOPT_URL, $url);
$vars = curl_exec($curl);
return $vars;
}
// CREATE THE WORKSPACE: NOTE, I left my post variables in here - however should be noted that a script was used (not included) to ensure against injection.
// build the data according to the jason standards for mavenlink's API
$Data = array('workspace[title]' => $_POST['Description'], 'workspace[creator_role]'=> "maven", 'workspace[description]'=> strip_tags($_POST['Details']), 'workspace[price]'=>$_POST['CostBudget'], 'workspace[due_date]'=>date("Y-m-d",strtotime($_POST['ProjectDue'])), 'workspace[project_tracker_template_id]'=> "285045" );
$DecodeMe = CallAPI("POST","https://api.mavenlink.com/api/v1/workspaces.json",$Data);
$Decoded = json_decode($DecodeMe,true); // be sure to set the option to true so your array comes back as associative
// INVITE USERS:
//////// BASE USERS
$InviteUrl = "https://api.mavenlink.com/api/v1/workspaces/".$Decoded['results'][0]['id']."/invite.json";
$Data2 = array('invitation[full_name]' => "User Fullname", 'invitation[email_address]'=> "email#email.com", 'invitation[invitee_role]'=> "maven" );
$Decoded2 = json_decode(CallAPI("POST",$InviteUrl,$Data2),true);
// repeat the above or use a do while script to process more.
// THE END
Related
Situation
I am trying to make a call to the Shopify REST API where I have more than 50-250 results but I am not able to get the Link Header from the cURL Response which contains the Pagination Links.
Sample of Link Headers from the API Documentation for Cursor-Pagination (https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api)
#...
Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
#...
The link rel parameter does show up, but the Link is empty as below.
My Shopify Call function
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
$headers = [];
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// this function is called by curl for each header received
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
function($ch, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[trim($header[0])] = trim($header[1]);
return $len;
}
);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'Sphyx App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl,CURLOPT_ENCODING,'');
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
$request_headers[] = 'Accept: */*'; // Copied from POSTMAN
$request_headers[] = 'Accept-Encoding: gzip, deflate, br'; // Copied from POSTMAN
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method !== 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$result = curl_exec($curl);
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $result, 2);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => json_decode($response[1],true));
}
}
But when I use a POSTMAN Collection, I get a proper formatted response without the Link getting truncated/processed.
I have tried a lot of things here available via the StackOverflow Forums as well as Shopify Community, but I'm unable to parse the Response Header the same way as shown by API Examples or POSTMAN
My issue does seem to be with the PHP Code, but I'm not a pro with cURL. Thus, I'm not able to make it further :(
Also, I'm not able to understand why POSTMAN's Headers are in Proper Case whereas mine are in Lower Case
Thanks in Advance!
Found my answer :
https://community.shopify.com/c/Shopify-APIs-SDKs/Help-with-cursor-based-paging/m-p/579640#M38946
I was using a browser to view my log files. So the data is there but it's hidden because of your use of '<'s around the data. I had to use the browser inspector to see the data. Not sure who decided this syntax was a good idea. Preference would be two headers that one can see and more easily parse since using link syntax is not relative to using an API.
My suggestion would be 2 headers:
X-Shopify-Page-Next: page_info_value (empty if no more pages)
X-Shopify-Page-Perv: page_info_value (empty on first page or if there is no previous page).
Easy to parse and use.
But having this buried as an invalid xml tag, having them both in the same header and using 'rel=' syntax makes no sense at all from an API perspective.
I am trying to simply add/ remove (well subscribe/ unsubscribe rather than delete) email addresses upon sign up of my website to a MailChimp list using the API. When the user is approved on my site, the email address is added via API successfully if the correct checkbox is ticked. However I can not for the life of me get unsubscribe to work. I think I'm having issues with the PATCH method. The code doesn't error, however the user status in the list does not change to unsubscribed and if I echo out the API call I simply get the following:
{"id":"EMAIL_HASH","email_address":"EMAIL_UNHASHED","unique_email_id":"3dae8dd13a","email_type":"html","status":"subscribed","merge_fields":{"FNAME":"","LNAME":"","MMERGE3":"","MMERGE4":"","MMERGE5":"","MMERGE6":"","MMERGE7":"","MMERGE8":"","MMERGE9":"","MMERGE10":""},"interests":{"edf7fefb79":false},"stats":{"avg_open_rate":0,"avg_click_rate":0},"ip_signup":"","timestamp_signup":"","ip_opt":"77.68.14.17","timestamp_opt":"2018-11-23T14:02:27+00:00","member_rating":2,"last_changed":"2018-11-23T14:02:27+00:00","language":"","vip":false,"email_client":"","location":{"latitude":0,"longitude":0,"gmtoff":0,"dstoff":0,"country_code":"","timezone":""},"tags_count":0,"tags":[],"list_id":"LIST_ID","_links":[{"rel":"self","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Response.json"},{"rel":"parent","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/CollectionResponse.json","schema":"https://us6.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Members.json"},{"rel":"update","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"PATCH","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Response.json","schema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/PATCH.json"},{"rel":"upsert","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"PUT","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Response.json","schema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/PUT.json"},{"rel":"delete","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"DELETE"},{"rel":"activity","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/activity","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Activity/Response.json"},{"rel":"goals","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/goals","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Goals/Response.json"},{"rel":"notes","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/notes","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Notes/CollectionResponse.json"},{"rel":"delete_permanent","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/actions/delete-permanent","method":"POST"}]}
which seems more like a dump of possible actions, rather than a response to my call. Needless to say LIST_ID and EMAIL_HASH are accurate and not in the final code.
curl options are as follows, am I possibly missing something require to patch but not POST?
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
curl_setopt($curl, CURLOPT_USERPWD, "user:API_KEY");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
Any help would be appreciated as extensive googling has not returned this problem, predominantly it's people trying to re-add deleted subscribers which this obviously isn't.
$url = 'https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/'.md5(strtolower($email));
$api_data = array(
'status' => 'unsubscribed'
);
$api_data = json_encode($api_data);
$test_call = CallAPI("PATCH","$url",$api_data);
The PHP using the custom function to call the API. I think I've included the relevant curl info from inside the function but if not please just let me know.
Your function doesn't set any data for a PATCH request. You need to set CURLOPT_POSTFIELDS same as with a POST request:
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
if ($data){
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
Incidentally, the same should be done for a PUT request or any other request type where you need to pass data parameters. You may also want to take a look at my answer here for a function that can both create and update list members.
I've written a basic API script in PHP using cURL - and successfully used a version of it on another API, this one is specifically to handle domain DNS management on DigitalOcean - and I can't send data?
Prelude...
I understand there is a PHP library available, I'm not after something that full featured or bloated with dependencies - just something small to use locally and primarily to help me understand how RESTful API's work a little better in practice - an educational exercise
The offending Code...
function basic_api_handle($key, $method, $URI, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$key,
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
var_dump(basic_api_handle($api_key, 'POST', 'https://api.digitalocean.com/v2/domains', array('name' => 'my-domain.tld', 'ip_address' => '1.2.3.4')));
This works with a GET request, such as listing the domains on the account but seems to fail at posting/sending data... this results in "unprocessable_entity" and "Name can't be blank" - as the name is not blank and is correctly formatted (as far as I can tell) it suggests to me the data is not being sent correctly?
Solution Attempts so far...
I've tried json encoding the data (seen in code), not json encoding, url encoding with and without json encoding and various other options with no luck.
I've seen a few posts online about this exact same issue specifically with DigitalOcean's API (and a another) but no one had an explanation (other than give up and use the library or something to that affect).
Using cURL directly from a terminal does work etc so there is nothing wrong with the API for creating a domain.
As far as I understand, the authentication is working, and the general setup works as I can list domains within the account, I just cant POST or PUT new data. I've been though the API's documentation and can't see what I'm doing wrong, maybe some sort of wrong encoding?
Any help would be much appreciated! :)
Edit:
After much work and research even other simple API handlers do not work with Digital Ocean (such as https://github.com/ledfusion/php-rest-curl) - is there something this API in particular needs or am I missing something fundamental about API's in general?
Technically this is not an fix but a work around. Thank you everyone for your comments and ideas, unfortunately nothing worked/fixed the code and the bounty expired :(
Although I have no idea why the PHP cURL option didn't work (the HTTP works, just Digital Ocean spitting errors for unknown reason linked to validation of the post data)...
I do have a new method that DOES WORK finally... (thanks to jtittle post on the Digital Ocean Community forum)
Just incase that link dies in the future... he's the working function using streams and file_get_contents and not curl...
<?php
function doapi( $key, $method, $uri, array $data = [] )
{
/**
* DigitalOcean API URI
*/
$api = 'https://api.digitalocean.com/v2';
/**
* Merge DigitalOcean API URI and Endpoint URI
*
* i.e if $uri is set to 'domains', then $api ends up as
* $api = 'https://api.digitalocean.com/v2/domains'
*/
$uri = $api . DIRECTORY_SEPARATOR . $uri;
/**
* Define Authorization and Content-Type Header.
*/
$headers = "Authorization: Bearer $key \r\n" .
"Content-Type: application/json";
/**
* If $data array is not empty, assume we're passing data, so we'll encode
* it and pass it to 'content'. If $data is empty, assume we're not passing
* data, so we won't sent 'content'.
*/
if ( ! empty( $data ) )
{
$data = [
'http' => [
'method' => strtoupper( $method ),
'header' => $headers,
'content' => json_encode( $data )
]
];
}
else
{
$data = [
'http' => [
'method' => strtoupper( $method ),
'header' => $headers
]
];
}
/**
* Create Stream Context
* http://php.net/manual/en/function.stream-context-create.php
*/
$context = stream_context_create( $data );
/**
* Send Request and Store to $response.
*/
$response = file_get_contents( $uri, false, $context );
/**
* Return as decoded JSON (i.e. an array)
*/
return json_decode( $response, true );
}
/**
* Example Usage
*/
var_dump(doapi(
'do-api-key',
'get',
'domains'
));
I used this to actually post the data successfully...
var_dump(doapi(
$api_key,
'post',
'domains',
array("name" => (string) $newDomain, "ip_address" => "1.2.3.4")
));
Add the Content-Length header and use CURLOPT_POST option for POST requests
function basic_api_handle($key, $method, $URI, $data) {
$json = json_encode($data)
$headers = array(
'Authorization: Bearer '.$key,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URI);
if ( $method === 'POST' ) {
curl_setopt($curl, CURLOPT_POST, 1);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
array_push($headers, 'Content-Length: ' . strlen($json) );
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers)
curl_setopt($ch, CURLOPT_POSTFIELDS, $json );
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
Maybe this will work for you:
function basic_api_handle($key, $method, $URI, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); // <-- Should be set to "GET" or "POST"
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // <-- Maybe the SSL is the problem
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"); // <-- I am not familiar with this API, but maybe it needs a user agent?
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$key,
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_POST, count($data)); // <-- Add this line which counts the inputs you send
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
It can also be a problem of a header you should sent and your missing it.
It could be a 307 or 308 http redirect.
Maybe "https://api.digitalocean.com/v2/domains" redirects to another url.
If this is the case, try adding:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
to make curl follow the redirection and keep the parameters.
It is suggested that you also use:
curl_setopt($curl, CURLOPT_POSTREDIR, 3);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
to keep the request body.
Hope it helps.
You can also try use CURLOPT_POST
I write a python script like this:
import web
import commands
urls = ('getprint', 'GetPrint', 'postprint', 'PostPrint')
app = web.application(urls, globals())
class GetPrint:
def GET(self):
return "Hello, this is GetPrint function :D"
class PostPrint:
def POST(self):
# I don't know how to access to post data!!!
if __name__ == "__main__": app.run()
I want to use this script as a web service and call It via a php script from another machine. My php script to call the python web service is like this:
<?php ...
require('CallRest.inc.php');
...
$status = CallAPI('GET', "http://WEBSERVICE_MACHINE_IP:PORT/".$arg);
echo $status;
...
$data = array("textbox1" => $_POST["textbox1"]);
CallAPI('POST', 'http://WEBSERVICE_MACHINE_IP:PORT/'.$arg, $data);
... ?>
And the header file 'CallRest.inc.php' is:
<?php
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
?>
The class GetPrint work correctly but I don't know how to pass the post parameters to the python web service and how to access them into class PostPrint.
To access POST data on your Python code you should define right after your def POST(self) a variable such as data = web.input(). Then you can access the fields as shown here, For example: data.param1, data.name, and so on. So your code should look as follows:
class PostPrint:
def POST(self):
data = web.input()
param1 = data.param1
name = data.name
...
The Stripe API allows for Curl calls to be made. For example, the command:
curl https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:
returns the subscription of customer cus_5ucsCmNxF3jsSY.
How can I use PHP to call this curl command (I am trying to avoid using the PHP Stripe libraries).
I am trying the following:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print($output);
// close curl resource to free up system resources
curl_close($ch);
?>
However, it seems that curl does not take the -u parameter of the URL. I get the following error:
{ "error": { "type": "invalid_request_error", "message": "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/." }
How can I pass the -u sk_test_REDACTED: parameter to my curl call?
I ran into the same issue. I wanted to use PHP's CURL functions instead of using the official stripe API because singletons make me nauseous.
I wrote my own very simple Stripe class which utilizes their API via PHP and CURL.
class Stripe {
public $headers;
public $url = 'https://api.stripe.com/v1/';
public $method = null;
public $fields = array();
function __construct () {
$this->headers = array('Authorization: Bearer '.STRIPE_API_KEY); // STRIPE_API_KEY = your stripe api key
}
function call () {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
switch ($this->method){
case "POST":
curl_setopt($ch, CURLOPT_POST, 1);
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
default:
if ($this->fields)
$this->url = sprintf("%s?%s", $this->url, http_build_query($this->fields));
}
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true); // return php array with api response
}
}
// create customer and use email to identify them in stripe
$s = new Stripe();
$s->url .= 'customers';
$s->method = "POST";
$s->fields['email'] = $_POST['email'];
$customer = $s->call();
// create customer subscription with credit card and plan
$s = new Stripe();
$s->url .= 'customers/'.$customer['id'].'/subscriptions';
$s->method = "POST";
$s->fields['plan'] = $_POST['plan']; // name of the stripe plan i.e. my_stripe_plan
// credit card details
$s->fields['source'] = array(
'object' => 'card',
'exp_month' => $_POST['card_exp_month'],
'exp_year' => $_POST['card_exp_year'],
'number' => $_POST['card_number'],
'cvc' => $_POST['card_cvc']
);
$subscription = $s->call();
You can dump $customer and $subscription via print_r to see the response arrays if you want to manipulate the data further.