how to create a POST with request in php or javascript - javascript

how to create a post with request in php or javascript for steam web API
Example post:
https://api.steampowered.com/IEconService/CancelTradeOffer/v1/?key=STEAM_API_KEY&tradeofferid=TRADE_OFFER_ID
when i use it in a browser i get:
Method Not Allowed
This API must be called with a HTTP POST request
In C# this was written as:
private bool CancelTradeOffer(ulong tradeofferid)
{
string options = string.Format("?key={0}&tradeofferid={1}", ApiKey, tradeofferid);
string url = String.Format(BaseUrl, "CancelTradeOffer", "v1", options);
Debug.WriteLine(url);
string response = SteamWeb.Fetch(url, "POST", null, null, false);
dynamic json = JsonConvert.DeserializeObject(response);
if (json == null || json.success != "1")
{
return false;
}
return true;
}

If you are using jQuery then there is a very handy function to do this.
$.post( "http://api.example.com/get-some-value", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
But be careful about cross domain ajax when calling it from JS.
EDIT
For the comment.
You have to include jQuery into your page and then you can call anything within the very useful and handy $( document ).ready() that jQuery supplies.
$(document).ready(function(){
$.post( "http://api.example.com/get-some-value", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
})

UPDATE:
Try this:
$url = 'https://api.steampowered.com/IEconService/CancelTradeOffer/v1/';
$postData = array();
$postData['key'] = $STEAM_API_KEY;
$postData['tradeofferid'] = $TRADE_OFFER_ID;
$parameters=json_encode($postData);
$headers = array( "Accept-Encoding: gzip",
"Content-Type: application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
$resultt = curl_exec($ch);
var_dump($resultt);
curl_close($ch);
Or use this as a function to POST values
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}

Final Answer:
PHP Curl Post, works OK :)
Please give credits to WD :)
$url = 'http://api.steampowered.com/IEconService/CancelTradeOffer/v1/';
$postData = array();
$postData['key'] = ""; // insert variable
$postData['tradeofferid'] = ""; // insert variable
$fields = '';
foreach($postData as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($postData));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
var_dump($result);
curl_close($post);
jQuery Post, works OK :)
Please give credits to SRC :)
<script src="jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$.post( "http://api.steampowered.com/IEconService/CancelTradeOffer/v1/", { key: "SteamApiKey", tradeofferid: "TradeOfferID" })
//This part does not work -- but is not needed to post data
//.done(function( data ) {
// alert( "Data Loaded: " + data );
//});
})
</script>
To Check Trade Offer status in PHP use:
//Check if trade offer was canceled
//Get File and avoid error if the server is down
$CheckTradeOfferID = ""; // add variable
$BotSteamApiKey = ""; // add variable
if (!$data = #file_get_contents("https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key=".$BotSteamApiKey."&tradeofferid=".$CheckTradeOfferID."&format=json")) {
print 'Steam Api is Down';
} else {
$json=json_decode($data,true);
$TradeOffersResponse = $json['response'];
if (empty($TradeOffersResponse)) {
print "Trade Offer ID not found!!!";
}else{
$trade_offer_state = $json['response']['offer']['trade_offer_state'];
$TRANSLATE_Trade_Offer_State = "Unknown";
if($trade_offer_state == "1"){ $TRANSLATE_Trade_Offer_State = "Invalid"; }
if($trade_offer_state == "2"){ $TRANSLATE_Trade_Offer_State = "Trade Offer Sent"; }
if($trade_offer_state == "3"){ $TRANSLATE_Trade_Offer_State = "Trade Offer Accepted"; }
if($trade_offer_state == "4"){ $TRANSLATE_Trade_Offer_State = "The User Sent A Counter Offer"; }
if($trade_offer_state == "5"){ $TRANSLATE_Trade_Offer_State = "Trade Offer not accepted before the expiration date"; }
if($trade_offer_state == "6"){ $TRANSLATE_Trade_Offer_State = "The sender cancelled the offer"; }
if($trade_offer_state == "7"){ $TRANSLATE_Trade_Offer_State = "User Declined the Trade Offer"; }
if($trade_offer_state == "8"){ $TRANSLATE_Trade_Offer_State = "Some of the items in the offer are no longer available"; }
print $TRANSLATE_Trade_Offer_State;
}
}

Related

display success message from PHP POST with AJAX

I have a form which I would like to display a success message when the server returns a 200 code as a response from a POST method.
It seems like AJAX is the way to do this, but as I am relatively new to even vanilla JS, I cant work out the way to implement this. What is the function needed to 'listen' to the server response?
If not AJAX, how would you go about it?
EDIT to include code example
PHP
<?php
$data = array(
"applicants"=> [
array(
"email"=> $_POST["email"],
"firstName"=> $_POST["firstName"],
"lastName"=> $_POST["lastName"],
"telephone"=> $_POST["telephone"]
)
],
"buyerType" => $_POST["buyerType"],
);
$data = json_encode($data);
$ch = curl_init();
$headers = [
"x-api-key: xxxxxx",
"accept: application/json",
"content-Type: application/json",
];
curl_setopt($ch, CURLOPT_URL, 'https://api.smartr365.com/api/v1/mortgage/lead/create');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
var_dump($response);
// TO DEBUG ---
// $responseData = json_decode($response, true);
//var_dump($data);
var_dump($status_code);
// var_dump($response);
curl_close ($ch);
?>
The Javascript is too long to show, as it has quite extensive validation, but the crux of the script, which enables the 'submit' button is:
// final validation for the form
const checkBox = document.getElementById("accept");
const submitBtn = document.getElementById("submitButton");
checkBox.addEventListener("click", function() {
let valid = false;
let isFormValid = false;
if (checkFirstName() == valid &&
checkLastName() == valid &&
checkEmail() == valid &&
checkTelephone() == valid) {
isFormValid = true;
}
if (checkBox.checked && isFormValid == true) {
submitBtn.disabled = false;
} else {
submitBtn.disabled = true;
}
});
// real time validation
const debounce = (fn, delay = 500) => {
let timeoutId;
return (...args) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};
//event delegation
form.addEventListener('input', debounce(function(e) {
switch (e.target.id) {
case 'firstName':
checkFirstName();
break;
case 'lastName':
checkLastName();
break;
case 'email':
checkEmail();
break;
case 'telephone':
checkTelephone();
break;
}
}));

Allow form to send POST request but prevent page from reloading - Javascript

I am working on a signup form with an integrated v2 reCAPTCHA and I ran into the issue that when submitting the form which includes the reCAPTCHA, it is reloading the page. I have a php function to validate the reCAPTCHA:
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' =>'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'Success!';
} else {
echo 'Error';
}
}
When the form submits it gives a POST variable g-recaptcha-response to the page it's on as there is no action attribute to the form
So, I need to get the POST request but I can't let the page reload because that would get rid of other data on the page.
I tried using event.preventDefault(); when the form is submitted, but that also prevented the form from submitting the POST variable.
I have no idea how I would get the POST variable through javascript because the reCAPTCHA is not actually an input.
But if there was a way to get the value of the reCAPTCHA through javascript, then I could use ajax to send the POST request to the function.
If you include the query strings in the script url:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
then you can use grecaptcha.getResponse as it says in the google reCAPTCHA documentation:
https://developers.google.com/recaptcha/docs/display
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
<script type="text/javascript">
var verifyCallBack = function(response) {
alert(response);
};
var widgetId;
var onloadCallback = function() {
widgetId = grecaptcha.render('recaptcha', {
'sitekey' : 's',
'theme' : 'light'
});
}
</script>
<form>
<div id="recaptcha"></div>
<input type="submit" name="submit" value="submit">
</form>
$('form').submit(function(e) {
e.preventDefault();
var response = grecaptcha.getResponse(widgetId);
$.ajax({
url: 'validate_captcha.php',
type: 'POST',
data: {'g-recaptcha-response': response},
success: function(data) {
alert(data);
},
error: function(error) {
alert(error);
}
});
});
And then in validate_captcha.php:
<?php
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' => 'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'success';
} else {
echo 'error';
}
}
?>
So now in your javascript, you can use the data variable inside success:function(data) in an if statement:
if(data == 'success') {
registerUser(name, email, password); // not a real function, just an example
}

How do I pass a PHP array to a JavaScript variable?

I have the following JavaScript that sends parameters to a PHP file:
function getOutput()
{
$.ajax({
url:'myPHPFile.php',
data:{APIKey:$APIKey,Password:$APIPass,Alias:$Alias,DataCenter:$DataCenter},
type:'POST',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function ()
{
$('#output').html('Bummer: there was an error!');
}
});
return response.responseText;
}`
Which changes the following HTML to the output of the PHP file:
test
Here is the PHP
<?php
// echo nl2br("\nIntializing api.php \n");
// DATA SECTION
$APIKey = $_POST["APIKey"];
$APIPass = $_POST["Password"];
$AccountAlias = $_POST["Alias"];
$dataCenter = $_POST["DataCenter"];
$data = array(
"APIKey" => $APIKey,
"Password" => $APIPass,
);
$url_send = 'https://api.ctl.io/REST/Auth/Logon/';
$json_data = json_encode($data);
function sendPostData($url, $post, $cook = null){
// echo "Beginning sendPostData($url, $post, $cook)";
$ch = curl_init($url);
$headers= array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (!empty($cook))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','Cookie:'.$cook));
}
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
};
$myresult = sendPostData($url_send, $json_data);
// print_r ($myresult);
$decodedresult = json_decode($myresult);
// print_r ($decodedresult);
'/reply-(.*?)-private/';
preg_match_all('/Tier3(.*?)path=/', $myresult, $matches);
$cookies = array();
foreach($matches[0] as $item)
{
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$prefix = 'Tier3.API.Cookie=';
$cookie = implode(" ",$matches[0]);
// Call the customer server list
$data = array(
'AccountAlias' => $AccountAlias,
'Location' => $dataCenter
);
$data_url = 'https://api.ctl.io/REST/Server/GetAllServersForAccountHierarchy/';
$data_string = json_encode($data);
$dataResult = sendPostData($data_url,$data_string, $cookie);
print_r($dataResult);
return $dataResult;
`
How can I get the $dataResult PHP array into a javascript variable so I can parse it? It is a big JSON response from an API.
Thanks.
Ajax calls are (normally) asynchronous, this means that the return response.responseText; will be executed immediately and should even raise an error related to response being undefined.
You'll have the response in the complete event of the ajax call and is inside there where you should go on with the execution of the script. jQuery will parse the JSON automatically and response will be the resulting object.
At the other side, the PHP script should just print the result of json_encode() and nothing else in order for the response to be valid JSON.

formating return json in html

I need help formatting json return in html from my jquery json result.
this my html code :
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "testerer"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "test.php",
data: data,
success: function(data) {
$(".the-return").html(data["json"]);
}
});
return false;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="test.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="testerer" value="" placeholder="Favorite restaurant" />
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="the-return"></div>
and this my test.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "testerer": testerer(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function udemy(){
$courseid = $_POST['testerer'];
$client_id = 'xxx';
$client_secret = 'xxxxx';
// set HTTP header
$headers = array(
"Authorization: Basic " . base64_encode($client_id . ":" . $client_secret),
"Content-Type: application/vnd.api+json"
);
$url = 'https://xxx/' . $courseid . '/';
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);
}
always got return like this :
"{\"_class\": \"course\", \"id\": 5816, \"title\": \"XXx xxx xxx\", \"url\": \"\/xxx-xxx\/\",
I need result readable.
It's not clear what your $data should contain, but it looks like the problem is that you're calling json_encode() twice on the same data:
$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);
Convert JSON data into string
JSON.stringify(data["json"])
add as below
$(".the-return").html(JSON.stringify(data["json"]));

Is there a way to set up recurring payments with the PayPal REST API?

I read this question and this one. They both said (a year ago) that recurring payments via the REST API was in the works. On my client's website, customers need to be able to pay either
in full (all at once — e.g., $1200 at check out)
in installments ($1200 over 6 months at $200 per month)
It is crucial that his website be notified when a customer pays. I have currently set this up for option #1:
app.get("/cart/checkout/paypal", isLoggedIn, isVerified, function (req, res) {
var user = req.user;
var paymentDetails = {
"intent": "sale",
"payer": { "payment_method": "paypal"},
"redirect_urls": {
"return_url": "http://localhost:5000/cart/checkout/success",
"cancel_url": "http://localhost:5000/cart"
},
"transactions": [
{ "amount": { "total": user.cart.finalPrice.toFixed(2), "currency": "USD"},
"description": "You are being billed for " + user.cart.finalPrice.toFixed(2)}
]
};
paypal.payment.create(paymentDetails, function (err, payment) {
if (err) console.log(err);
else {
if (payment.payer.payment_method === "paypal") {
req.session.paymentId = payment.id;
var redirectURL;
for (var i = 0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === "REDIRECT") redirectURL = link.href;
}
res.redirect(redirectURL);
}
}
})
})
Then, the "return_url" (/cart/checkout/success) grabs all the correct session info and my database processes it.
app.get("/cart/checkout/success", isLoggedIn, isVerified, function (req, res) {
var user = req.user,
paymentId = req.session.paymentId,
payerId = req.param("PayerID"),
details = { "payer_id": payerId };
...
Is there a similar setup for option #2 (recurring payments). If not, is there a way for PayPal to notify my server every time a user has paid an installment with the outstanding balance and amount paid/etc.?
Yes, there is now a way to do subscriptions within the new REST API. See the documentation.
OK, first you need to set the Client ID and secret you get from PayPal.
I have both a testing and live environment
All {xxx} are my private application variables
public function __construct()
{
$this->sandbox = {sandbox};
if($this->sandbox)
{
$this->host = 'https://api.sandbox.paypal.com';
$this->clientId = {clientIdSandbox};
$this->clientSecret = {clientSecretSandbox};
}
else
{
$this->host = 'https://api.paypal.com';
$this->clientId = {clientId};
$this->clientSecret = {clientSecret};
}
$this->get_access_token();
}
I then go and get the access token
private function get_access_token()
{
$curl = curl_init($this->host.'/v1/oauth2/token');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $this->clientId . ":" . $this->clientSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$response = curl_exec( $curl );
if (empty($response))
{
echo "NO RESPONSE for $url for function ".__FUNCTION__;
print_r(curl_getinfo($curl));
die(curl_error($curl));
curl_close($curl); // close cURL handler
}
else
{
$info = curl_getinfo($curl);
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 )
{
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
$jsonResponse = json_decode( $response );
$this->token = $jsonResponse->access_token;
$this->expires = time()+$jsonResponse->expires_in;
}
This then stores the access data in the classes properties
You then need three more sections. Create the subscription template, then retrieve the agreement, then create the agreement for the client.
In this method I send over the data Name, Desc, Period, Interval and Price. However you can just fill in manually. This will create the subscription that you can now sell.
public function create_subscription($name, $desc, $period, $interval, $price)
{
$data = array(
'name' => $name,
'description' => $desc,
'type' => 'INFINITE',
'payment_definitions' => array(
0 => array (
'name' => 'Payment Definition-1',
'type' => 'REGULAR',
'frequency' => $period,
'frequency_interval' => $interval,
'amount' => array(
'value' => $price,
'currency' => 'EUR',
),
'cycles' => '0',
),
),
'merchant_preferences' => array(
'return_url'=>{return_url},
'cancel_url'=>{cancel_url},
'auto_bill_amount' => 'YES',
'initial_fail_amount_action' => 'CONTINUE',
'max_fail_attempts' => '0',
),
);
$data=json_encode($data);
$url = $this->host.'/v1/payments/billing-plans';
return $this->make_post_call($url, $data);
}
From the above method you will get in return an id, use that for the method below to collect the data of the subscription and store it
public function retrieve_agreement($id)
{
$url = $this->host.'/v1/payments/billing-agreements/'.$id;
return $this->make_get_call($url);
}
This method will allow you to allocate and agreement to a client.
You will need the id of the aggreement with some data for you to be able add to the description.
public function create_agreement($subId, $data, $product)
{
$paypalId = ($this->sandbox) ? $product->paypal_test_sub_id : $product->paypal_sub_id;
$startDate = date('c', strtotime('+10 MINUTE'));
$data = array (
'name'=>'Subscription for subscription::'.$subId,
'description'=>{company}.' Subscription - ' . $data . ' - '.$product->name.' - '.$product->price .'€',
'start_date'=>$startDate,
'plan'=>array(
'id'=>$paypalId,
),
'payer'=>array(
'payment_method'=>'paypal',
),
'override_merchant_preferences'=>array(
'return_url'=>{return_url}.$subId.'/',
'cancel_url'=>{cancel_url}.$subId.'/',
),
);
$data=json_encode($data);
$url = $this->host.'/v1/payments/billing-agreements';
$response = $this->make_post_call($url, $data);
header("location:".$response['links'][0]['href']);
//return $response;
}
The return_url is the url that the end user will be sent to to complete the aggreement. I than use that to pass to the method below
public function execute_agreement($token)
{
$data=json_encode('');
$url = $this->host.'/v1/payments/billing-agreements/'.$token.'/agreement-execute';
return $response = $this->make_post_call($url, $data);
}
You will then need to create a scheduled task to use the retrieve_agreement method and see if a subscription has been cancelled or not.
This is a brief explanation.
if you require more please let me know.
Get and Post
private function make_post_call($url, $postdata)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$this->token,
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$response = curl_exec( $curl );
if (empty($response))
{
echo "NO RESPONSE for $url for function ".__FUNCTION__;
print_r(curl_getinfo($curl));
die(curl_error($curl));
curl_close($curl); // close cURL handler
}
else
{
$info = curl_getinfo($curl);
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 )
{
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
$jsonResponse = json_decode($response, TRUE);
return $jsonResponse;
}
private function make_get_call($url)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$this->token,
'Accept: application/json',
'Content-Type: application/json'
));
$response = curl_exec( $curl );
if (empty($response))
{
echo "NO RESPONSE for $url for function ".__FUNCTION__;
print_r(curl_getinfo($curl));
die(curl_error($curl));
curl_close($curl); // close cURL handler
}
else
{
$info = curl_getinfo($curl);
//echo "Time took: " . $info['total_time']*1000 . "ms\n";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 )
{
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
$jsonResponse = json_decode($response, TRUE);
return $jsonResponse;
}
I would recommend staying away from the REST API for now. It's just not complete yet, and the Classic API gives you so much more flexibility.
I'd go with Express Checkout with Recurring Payments, and then you'll want to use Instant Payment Notification (IPN) to handle processing payments, canceled profiles, etc.
IPN notifications will actually be triggered for any transaction that ever hits your account, so you can automate the processing of payments, refunds, disputes, subscriptions, etc. You can update your database, send email notifications, or anything else you need to automate based on these transaction types.
IPN is one of the most valuable tools PayPal provides, yet it's also one of the most underutilized.

Categories