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.
Related
I have a Django API application using Django rest framework which works just fine. I have another PHP laravel application that is supposed to consume the API. When I post data to the API endpoint using curl, the data is stored and an object is returned.
I am supposed to grab this object and use the data. However, the object that is returned is printed on the page when I visit the route that executes the post request.
When I do dd($data) with the variable that is supposed to contain the returned data, I get a boolean (true when the data was posted successfully and false if something went wrong).
Route::get('test-create-client', function (){
try {
$data = ApiController::createClient('John D', '0711111111', '', 'Male', '1980'.'-'.date('m-d'));
} catch (Exception $exception) {
return $exception->getMessage();
}
dd($data); // I get a boolean from here
});
//creatClient from the ApiController
public static function createClient($name, $phone, $care_of, $gender, $date_of_birth)
{
$url = "client/clients/";
$client = '{
"name": "'.$name.'",
"telephone_number": "'.$phone.'",
"alternative_telephone_number": "'.$alt_phone.'",
"care_of": "'.$care_of.'",
"gender": "'.$gender.'",
"date_of_birth": "'.$date_of_birth.'",
}';
return ServicesApiController::RunCurlPostServices($url, $client);
}
//CurlRequest
public static function RunCurlPostServices($url, $json)
{
$ch = curl_init(env('SERVICES_API_URL').$url);
curl_setopt($ch, CURLOPT_POST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
I need $data to have the data returned by the API endpoint and not a boolean value.
In order for curlpost to return the content returned by an API request, I had to set CURLOPT_RETURNTRANSFER to true. For some reason I had missed it out.
So updating my curl request to
public static function RunCurlPostServices($url, $json)
{
$ch = curl_init(env('SERVICES_API_URL').$url);
curl_setopt($ch, CURLOPT_POST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
Fixed the issue.
This helped.
Thanks for the effort #Rezrazi
Laravel does not have a built in http client, for that you need to use a tool or a package.
I recommend guzzle and its documentation
You can use it this way in your GET method
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://myapplication.com/endpoint');
$data = $res->getBody();
I am new to REST and have been tasked with retrieving SurveyMonkey survey data using the V3 API. I am using PHP. My code is as follows:
$fields = array(
'title'=>'New Admission Survey',
'object_ids' => array($surveyID));
$fieldsString = json_encode($fields);
$curl = curl_init();
$requestHeaders = array(
"Authorization" => 'bearer abc123',
"Content-Type" => 'application/json',
'Content-Length: ' . strlen($fieldsString));
$baseUrl = 'https://api.surveymonkey.net/v3';
$endpoint = '/surveys/';
curl_setopt($curl, CURLOPT_URL, $baseUrl . $endpoint);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeaders);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $fieldsString);
$curl_response = curl_exec($curl);
if($curl_response == false){
echo('Well, crap');
$info = curl_getinfo($curl);
echo('<pre>');print_r($info);echo('</pre>');
echo('<pre>');print_r(curl_error($curl));echo('</pre>');}
else {
echo('Test: ' . $curl_response);}
curl_close($curl);
I am getting the following error:
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
I have verified the Auth Token I am using is the one issued to me when I registered my app (done today).
Am I missing something? Most of the questions and answers deal with V2 of the SurveyMonkey API. I am using V3.
Thanks for your help!
I'm not sure if this will help the specific error you're encountering, but have you tried using this API wrapper? https://github.com/ghassani/surveymonkey-v3-api-php
This API wrapper simplified my tasks considerably:
<?php
// Init the client.
$client = Spliced\SurveyMonkey\Client(MY_CLIENT_ID, MY_ACCESS_TOKEN);
// Get a specific survey.
$survey = $client->getSurvey(MY_SURVEY_ID);
// Get all responses for this survey.
/** #var Spliced\SurveyMonkey\Response $responses */
$responses = $client->getSurveyResponses(MY_SURVEY_ID);
// Get a specific response.
/** #var Spliced\SurveyMonkey\Response $response */
$response = $client->getSurveyResponse(MY_SURVEY_ID, RESPONSE_ID, TRUE);
/* etc... */
I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.
I've just read the following on the MailChimp website:
MailChimp API v3.0 is now live!
Prior versions will no longer be supported after 2016, so all API users should begin transitioning to v3.0.
As a result, I would like to move to v3.0 of the API. Please could I have a function, in PHP, that returns a boolean, that will check whether an email address is subscribed to a specific MailChimp list. I do not want to subscribe that user, but merely check whether they are subscribed or not.
If you use the mailchimp-api it looks like that
include 'Mailchimp.php';
use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp('your**api***key');
function emailExistsMc($subscriberMail, $list_id){
global $MailChimp;
$subscriber_hash = $MailChimp->subscriberHash($subscriberMail);
$result = $MailChimp->get("lists/$list_id/members/$subscriber_hash");
if($result['status'] == '404') return false;
return true;
}
If $result['status'] is 404 then the resource was not found. Other possible values for $result['status'] are stated in the docs:
subscribed
unsubscribed
cleaned
pending
transactional
UPDATE: I answered another question with a more elaborate tutorial of how to do this with jQuery .ajax(): Adding subscribers to a list using Mailchimp's API v3
Looking at the Mailchimp documentation and assuming you have a given list in mind, it looks like you would call this endpoint with a GET:
/lists/{list_id}/members/{subscriber_hash}
To do this in PHP, I found a nice script sitting on github. Their last function would probably do the trick for you:
function mc_checklist($email, $debug, $apikey, $listid, $server) {
$userid = md5($email);
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/lists/'.$listid.'/members/' . $userid);
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_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
if ($debug) {
var_dump($result);
}
$json = json_decode($result);
echo $json->{'status'};
}
If that function doesn't work, the only wrapper I could find for the v3 library works in conjunction with Laravel - Mailchimp v3 API PHP wrapper.
I use the DrewM library
function isSubscribed($emailAddress, $listId) {
$chimp = new \DrewM\MailChimp\MailChimp($apiKeyHere);
$subscriberHash = $chimp->subscriberHash($emailAddress);
$result = $chimp->get('lists/' . $listId . '/members/' . $subscriberHash);
return ($chimp->success() && isset($result['id']));
}
I refered google play android api to check the purchase and consumption status of an in-app item. but return the error as below:
C:\Program Files\VertrigoServ\www\inapp\index.php:74:null
Not Found
I can not understand why he does not return me not a valid json, it just returns me a text saying "Not Found"
I use the function to getToken(), she works perfect... but the function
getStatusInapp($pProductIdStr, $lAccessToken) doesn't work
What I doing wrong?
function getToken(){
GLOBAL $lPackageNameStr; // Name of package Name (com.example.app)
GLOBAL $client_id; // my client id from google
GLOBAL $client_secret; // my client secret from google
GLOBAL $refresh_token; // the refresh token
GLOBAL $pReceiptStr; // token of inap purchase
$url ="https://accounts.google.com/o/oauth2/token";
$fields = array(
"client_id"=>$client_id,
"client_secret"=>$client_secret,
"refresh_token"=>$refresh_token,
"grant_type"=>"refresh_token");
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST,count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$lResponse_json = (curl_exec($ch));
$lAccessToken = json_decode($lResponse_json)->{'access_token'};
//close connection
curl_close($ch);
return $lAccessToken;
}
function getStatusInapp($pProductIdStr, $lAccessToken){
GLOBAL $lPackageNameStr; // Name of package Name (com.example.app)
GLOBAL $client_id; // my client id from google
GLOBAL $client_secret; // my client secret from google
GLOBAL $refresh_token; // the refresh token
GLOBAL $pReceiptStr; // token of inaap purchase
/*
# What is the correct way to sku?
$pProductIdStr = "teste_01";
------------ or --------------
$pProductIdStr = "com.example.app.teste_01";
------------ or --------------
$pProductIdStr = "inap:com.example.app:teste_01";
# On Google Play Developer Console the sku is:> teste_01
*/
$lURLStr = ("https://www.googleapis.com/androidpublisher/v2/applications/$lPackageNameStr/purchases/$pProductIdStr/purchases/$pReceiptStr");
$curl = curl_init($lURLStr);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = "Authorization: Bearer " . $lAccessToken;
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);
$json_response = curl_exec($curl);
curl_close($curl);
//echo $json_response;
$responseObj = json_decode($json_response,true);
var_dump($responseObj);
echo $json_response;
}
/*
| Execute...
*/
getStatusInapp($pProductIdStr, getToken());
Looks like you have the API endpoint path wrong. The Purchases.products: get documentation describes the url as:
https://www.googleapis.com/androidpublisher/v2/applications/packageName/purchases/products/productId/tokens/token
Change your $lURLStr to:
"https://www.googleapis.com/androidpublisher/v2/applications/$lPackageNameStr/purchases/products/$pProductIdStr/tokens/$pReceiptStr"