How can i implement paypal checkout v2 server side / JS sdk - javascript

I'm trying to make an implementation for paypal using checkout.js, however, i need to store the details of the transaction once the payment it's completed but first, i'm having trouble getting the button values from the server side, my code goes as follows:
<script>
paypal.Buttons({
// Order is created on the server and the order id is returned
// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch('php/create.php', {
method: 'post'
}).then(function(response) {
return response.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Call your server to save the transaction
return fetch('/paypal-transaction-complete.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: details.id
})
});
});
}
}).render('#paypal-button-container');
</script>```
<?php session_start();
// PayPal configuration
define('PAYPAL_CONFIG', [
'URL' => "https://api-m.sandbox.paypal.com/",
'CLIENT_ID' => 'xxx',
'SECRET' => 'xxx',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PAYPAL_CONFIG['URL'] . "v2/checkout/orders");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, PAYPAL_CONFIG['CLIENT_ID'] . ":" . PAYPAL_CONFIG['SECRET']);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = [
"intent" => "sale",
"redirect_urls" => [
"return_url" => "http://localhost:8888/index.php",
"cancel_url" => "http://localhost:8888/index.php"
],
"payer" => [
"payment_method" => "paypal"
],
"transactions" => [
[
"amount" => [
"total" => $_SESSION['price'],
"currency" => "USD"
]
]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$response = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Invalid JSON response: " . json_last_error_msg());
var_dump($httpStatusCode);
return false;
}
if (!$result) {
error_log("cURL request failed with HTTP status code: " . $httpStatusCode);
var_dump($httpStatusCode);
return false;
}
return $result;
Whenever i try to click the paypal button, i keep getting a console error saying that Error: Unexpected end of Json input and closes the paypal window almost immediately
I've tried debbuging with several methods but i can't get it working, any suggestions?

(That code is not for checkout.js , which is older and deprecated ; you're using the current PayPal JS SDK)
Anyway, this issue:
Error: Unexpected end of Json input
Occurs when your server-side code is outputting something other than a purse JSON string, such as a var_dump or other echo statement. Your create and capture routes must output only a JSON string, never any other text or HTML.
You can get a log of the response being outputted to the XHR request in your browser's dev tools -> Network tab.

Related

PHP call not returning API data

I'm using this link to obtain Air Quality data from an API https://api-ninjas.com/api/airquality
I want to do this via PHP due to it being a requirement
I have my PHP file
<?php
// Display errors is set to on and should be removed for production
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Timing script execution
$executionStartTime = microtime(true);
$url='https://api.api-ninjas.com/v1/airquality?city=' . $_REQUEST['countryName'];
// Curl object is initiated
$ch = curl_init();
//Curl_setopt() takes three parameters(Curl instance to use, setting you want to change, value you want to use for that setting)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result=curl_exec($ch);
curl_close($ch);
$decode = json_decode($result, true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['result'] = $decode['result'];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
and then my JavaScript Function
function getAirQuality(countryName) {
$.ajax({
method: 'GET',
url: "assets/php/getAirQuality.php",
data: {
countryName: countryName
},
headers: {
'X-Api-Key': 'API_KEY'
},
contentType: 'application/json',
success: function(result) {
console.log(result);
$('#aqCO').html(result['CO']['concentration'] + ' ppm');
$('#aqSO').html(result['SO2']['concentration'] + ' ppm');
$('#aqO3').html(result['O3']['concentration'] + ' g/m3');
$('#aqNO2').html(result['NO2']['concentration'] + ' ppm');
$('#aqPM2').html(result['PM2.5']['concentration'] + ' µg/m3');
$('#aqPM10').html(result['PM10']['concentration'] + ' µg/m3');
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
});
}
However, the PHP file keeps complaining in the console Error: <br /> <b>Warning</b>: Undefined array key "result" in <b>C:\xampp1\htdocs\project1\assets\php\getAirQuality.php</b> on line <b>30</b><br /> {"status":{"code":"200","name":"ok","description":"success","returnedIn":"293 ms"},"result":null}
As you can see from the above website, the result should be like so
{
"CO": {
"concentration": 223.64,
"aqi": 2
},
"NO2": {
"concentration": 9.08,
"aqi": 11
},
"O3": {
"concentration": 26.46,
"aqi": 22
},
"SO2": {
"concentration": 0.78,
"aqi": 1
},
"PM2.5": {
"concentration": 4.04,
"aqi": 13
},
"PM10": {
"concentration": 6.23,
"aqi": 5
},
"overall_aqi": 22
}
I'm not sure what else it could be? I've tried result, results and data
UPDATE
So whilst I've got the data decoded fine
result
:
CO
:
{concentration: 223.64, aqi: 2}
NO2
:
{concentration: 19.71, aqi: 24}
O3
:
{concentration: 52.93, aqi: 44}
PM2.5
:
{concentration: 11.67, aqi: 37}
PM10
:
{concentration: 14.61, aqi: 13}
SO2
:
{concentration: 1.97, aqi: 2}
overall_aqi
:
44
I am trying to assign them to variable like so: $('#aqCO').html(result['CO']['concentration'] + ' ppm'); but it is returning Uncaught TypeError: Cannot read properties of undefined (reading 'concentration')
You can pass headers by creating an array and passing it via: CURLOPT_HTTPHEADER
$headers = ['X-Api-Key: API_KEY'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

401 unauthorized ajax call error to Watson Assistant API

I am trying to make ajax request to Watson Assistant API from client side only, so I had this code in php which is working fine but when I tried to make it in jQuery I got 401 unauthorized error.
PHP:
$data['input']['text'] = $_POST['message'];
if(isset($_POST['context']) && $_POST['context']){
$data['context'] = json_decode($_POST['context'], JSON_UNESCAPED_UNICODE);
}
$data['alternate_intents'] = false;
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
// Post the json to the Watson API via cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://watson-api-explorer.mybluemix.net/conversation/api/v1/workspaces/'.$workspace_id.'/message?version='.$release_date);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = trim( curl_exec( $ch ) );
curl_close($ch);
// Responce the result.
echo json_encode($result, JSON_UNESCAPED_UNICODE);
JS:
$.ajax({
url: apiUrl,
type: 'POST',
dataType: 'json',
data: {
message: message,
context: context
},
headers:{
'Authorization' : 'Basic' + btoa('f7be829c-ae6d-47d8-b2bd-65a40ad45aa' +':'+ 'hJcToxQ23Zk'),
},
contentType: 'application/json',
timeout:10000
})
Anything missing from the JS code?
Note: credentials mentioned are for example only.

PHP Simple HTML DOM with POST method?

How to use Simple HTML DOM with input POST method?
I try to do with cUrl:
$ch = curl_init();
$timeout=5;
$data = array('teks' => '4ia17');
$data=http_build_query($data);
curl_setopt($ch,CURLOPT_URL,"http://baak.gunadarma.ac.id/jadwal/cariJadKul");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$datas = curl_exec($ch);
curl_close($ch);
echo $datas;
the problem is :
problem
and i try to do this too
include("simple_html_dom.php");
$request = array(
'http' => array(
'header' => array("Content-Type: application/x-www-form-urlencoded"),
'method' => 'POST',
'content' => http_build_query(array(
'teks' => '4ia17'
)),
)
);
$context = stream_context_create($request);
$htmls = file_get_html("http://baak.gunadarma.ac.id/jadwal/cariJadKul",true, $context);
echo $htmls;
and the error is :
Warning: file_get_contents(http://baak.gunadarma.ac.id/jadwal/cariJadKul): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in C:\xampp\htdocs\php-youtube-dl-master\Downloader\simple_html_dom.php on line 75
can anyone please help me where lies the error is? or something i can do with?

Sending JSON over AJAX to PHP script

I am attempting to create a method to take a CSV file, parse it into JSON, then send it to BigCommerce using their REST API. Initially I was going to use Javascript to do the whole thing, and everything up until actually connected to BigCommerce to PUT the data worked. BigCommerce doesn't allow CORS, resulting in a 401 response from the server and none of my data actually being sent. Because of this, I was going to switch to do it with PHP but being able to get the specific JSON object is much harder than it was with Javascript. The solution I've come up with would be for me to parse the data in Javascript, send it line by line to the PHP script and the PHP script would then connect to BigCommerce and send it for me.
First off, is this possible?
Here is some of my Javascript code:
$(document).ready(function () {
$('[type=file]').change(function () {
if (!("files" in this)) {
alert("File reading not supported in this browser");
}
var file = this.files && this.files[0];
if (!file) {
return;
}
i=0;
Papa.parse(file, {
delimiter: ",", // auto-detect
newline: "", // auto-detect
header: true,
dynamicTyping: true,
preview: 0,
encoding: "",
worker: false,
comments: false,
step: function(results, parser) {
console.log("Row data:", results.data);
console.log("Row errors:", results.errors);
currentID = results.data[i]["id"];
currentResult = results.data[i];
sendToBC(currentID, currentResult);
i+1;
},
complete: function(results, file) {
console.log("Parsing complete:", results, file);
$("#parsed_JSON").css("display", "block");
$("#ready_btn").css("display", "block");
$("#select_file").css("display", "none");
$("#retry_btn").css("display", "block");
},
error: function(error, file) {
console.log("Parsing failed:", error, file);
alert("Parsing failed. Check file and refresh to try again.");
},
download: false,
skipEmptyLines: true,
chunk: undefined,
fastMode: undefined,
beforeFirstChunk: undefined,
withCredentials: undefined
})
});
function sendToBC(id,data) {
jQuery.ajax({
type: "PUT",
url: "https://store.mybigcommerce.com/api/v2/products/" + id + "/discountrules.json",
data: data,
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + btoa('username:key')
},
dataType:"json",
async: false,
success: function() {
alert("success")
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
You'll notice I had to do something weird with the i=0 and the i+1 in the middle of the papa code but that was because I couldn't do a for loop in the step function.
My php is just the basic curl functions:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array ('Accept: application/json', 'Content-Length: 0') );
curl_setopt( $ch, CURLOPT_VERBOSE, 0 );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_USERPWD, "username:key" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $complete);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec( $ch );
curl_close ($ch)
I dont have the most experience with PHP especially with passing values into it through AJAX, so any help would be great. I'm not really certain how passing values between the files really works and how I can send this data to the PHP the best way programatically.
Thanks.
Considering you get an string object like {"id": "77", "min": "1", "max": "6", "price": 10}. and you want to retrieve id (77) from the JSON object.
$str = '{"id": "77", "min": "1", "max": "6", "price": 10}';
$jsonObj = json_decode($str);
$jsonObj->id; // the id.
Here $jsonObj->id is the id via which you can call your API.
Alright, so the way I ended up doing it was just using PHP and building a JSON string on my own with the values retrieved from the array by their key. So I did:
contents[$i]['id']
to get the id of the current item and stored it in a variable and did that for all the other columns of the csv. Then I built a string like this:
$jsonObject[] = '{"min": '.$min.',"max": '.$max.',"type": "'.$type.'","type_value": '.$value.'}';
and sent it through the API to Bigcommerce using CURL.

Use a PHP variable in Javascript / Ajax without showing in the inspect element

i want to send emails with de mandrill api. I have mi apikey in a php var but when i do var apikey='<?php echo$apikey;?>'; this shows in the inspect elemnt.
its posibble hide, encrypt or something the variable with php, javascript, ajax or json?
this is and example of my code:
<?php
$apikey='aaaaaaaaaaaaaa';
?>
<script type="text/javascript">
var apikey='<?php echo$apikey;?>';
sendEmail();
function sendEmail() {
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': apikey,
'message': {
'from_email': 'FROM_EMAIL_GOES_HERE',
'to': [{
'email': $('.email').val(), // get email from form
'name': $('.name').val(), // get name from form
'type': 'to'
}
],
'autotext': 'true',
'subject': 'EMAIL_SUBJECT_GOES_HERE',
'html': "Hey *|COOLFRIEND|*, we've been friends for *|YEARS|*.", // example of how to use the merge tags
'track_opens': true,
'track_clicks': true,
}
}
}).done(function(response) {
console.log(response); // if you're into that sorta thing
});
});
</script>
You can setup a php service and use curl to do the transferring work. Then just have AJAX do the front end work and send the subject/body/etc to the php service.
#Lifz works great for me
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$result = curl_exec($ch);

Categories

Resources