PayPal Orders API Express Checkout - CaptureOrder ID issue - javascript

bit of a beginner with some of this, but I am struggling understanding some of the walk throughs on the Paypal API checkout. I am ok with PHP but not really got round to fully understanding JavaScript* yet.
So, I have got the client side JAvascript for the check out buttons as shown on the Paypal API as follows:
<script>
paypal.Buttons(
{
env: 'sandbox', // sandbox | production
commit: true,
createOrder: function() {
return fetch('samples/AuthorizeIntentExamples/CreateOrder.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
})
.then(function(res) {
return res.json();
}).then(function(data) {
return data.id; // Use the same key name for order ID on the client and server
});
},
onApprove: function(data)
{
return fetch('samples/AuthorizeIntentExamples/CaptureOrder.php', {
method:'post',
headers: {
'content-type': 'application/json',
'id':data.id
},
body: JSON.stringify({
orderID: data.id
})
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Transaction funds captured from ' + details.payer_given_name);
})
}
}).render('#paypal-button-container');
</script>
The CreateOrder side of the code is working fine. I receive the JSON with the payment ID etc. However I am struggling to understand how get the OrderID to the CaptureOrder function. The paypal seems to skirt around this and just states "PUT ORDER ID HERE" in the captureOrder function:
namespace Sample\AuthorizeIntentExamples;
require ($_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php');
include ($_SERVER['DOCUMENT_ROOT'].'/vendor/paypal/paypal.php');
use PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
use Sample\PayPalClient;
class CaptureOrder
{
/**
* Below method can be used to build the capture request body.
* This request can be updated with required fields as per need.
* Please refer API specs for more info.
*/
public static function buildRequestBody()
{
return '{
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "GBP",
"value": "100.00"
}
}
]
}';
}
/**
* Below function can be used to capture order.
* Valid Authorization id should be passed as an argument.
*/
public static function captureOrder($authorizationId, $debug=false)
{
$request = new AuthorizationsCaptureRequest($authorizationId);
$request->body = CaptureOrder::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
/* print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Capture ID: {$response->result->id}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line */
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response->result;
}
}
/**
* Driver function for invoking the capture flow.
*/
if (!count(debug_backtrace()))
{
CaptureOrder::captureOrder('ORDER ID HERE', true);
}
Do I need to store the JSON results of CreateOrder in a SLQ database and call the order number from there to Capture Order or am I missing something and the client side JavaScript* code in the Paypal workflow Posts the orderID onApprove?
UPDATE:
So I have been and played around and I cannot understand why the order ID is not being sent to CaptureOrder when approved.
onApprove: function(data) {
return fetch('/my-server/capture-paypal-transaction', {
headers: {
'content-type': 'application/json'
},
**body: JSON.stringify({
orderID: data.id
})**
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Transaction funds captured from ' + details.payer_given_name);
})
}
The orderID does not seem to be here, despite the orderID being returned in data.id at the CreateOrder stage.
I get the following error "Uncaught TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body". This is despite follwoing the PayPal documentation.
I then tried POST data in the header
onApprove: function(data) {
return fetch('/my-server/capture-paypal-transaction', {
headers: {
'content-type': 'application/json',
'id': data.id
}
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Transaction funds captured from ' + details.payer_given_name);
})
}
This stopped the uncaught error, but the data sent in post 'id' was undefined. The then caused the API to return "RESOURCE ID NOT FOUND".
I just dont seem to get how the JAvaScript passes the OrderID between the function in CreateOrder and the function in OnApprove.
Trying my best to learn, but I the paypal documentation seems to assume a lot or miss bits out.

Related

How do I pass use Authorize from Paypal Orders API in my method & what should I return?

I have a pending fetch request that is waiting for the authorize method below to execute on my backend.
I need to use the authorize request details from PayPal orders api from here
and implement that in the method below. I have attempted to do that below but I'm not sure if it's correct.
async authorize(): Promise<PAR> {
var res = HTTPClient.request(
'https://api-m.sandbox.paypal.com/v2/checkout/orders',
{
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization':
'Bearer access-token',
},
body: JSON.stringify({
intent: 'AUTHORIZE',
purchase_units: [
{ amount: { currency_code: 'USD', value: '100' } },
],
}),
},
);
return (await res).responseText;
}
Sorry if I'm not able to explain it properly, please feel free to ask for anything else you may need for this. This is my first time doing something in TypeScript & I got into node very very recently too.

Nodejs request post with body include api key

I have been trying about a week but I couldn't make a post request to get a result.
I tried a bunch of middlewares (exp: 'request', 'axios', 'reqclient','superagent etc..) but I couldn't make it.
Please provide me a simple post request with sending API key and body.
I also read all the documentation.
Please check below to see what I want :
*Authentication API key required.
*O-Auth Scopes trades
*Input One of: user_id + token or user_url is required.
here is my one of try :
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'api-site.com/Offer/v1/',
headers: {
'User-Agent': 'Request-Promise',
'Authorization': 'Basic 123123asdasd123123'
},
body: {
user_url: "site.com/user/user1234123",
otherparams: "parameter"
},
json: true
};
request(options)
.then(function (response) {
Console.log(response);
})
.catch(function (err) {
console.log('Error ', err.message);
});
I am getting this output :
Error : 401 - {"status":401,"time":1540458426,"message":"API Key Required"}
I tried some other request post middle-wares and played with content-type (application/json. dataForm, x-www-form-urlencoded) or
changed the location of my API key from header to body or
tried my API key inside of auth{authorization: "API Key"}
tried much more.
the result didn't change. I got the same output or errors.
EDIT :
this is the link that I am trying to do but got stack :
check here
Solved !
Everything works great. Problem was I needed to send my API Key base64 string.
Buffer.from("your_api_key_value" + ":", "ascii").toString("base64")

Bad request while trying to access Github's v4 API with graphql.js

I am trying to retrieve some data from Github's GraphQL API using graphql.js library.
var graph = graphql("https://api.github.com/graphql", {
method: "POST",
headers: {
"Authorization": "Bearer <my-token-here>",
"Content-Type": "application/json"
},
fragments: {
rateLimitInfo: "on RateLimit {cost,remaining,resetAt}"
}
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
id
}
}
`,{
name: "freeCodeCamp",
owner: "freeCodeCamp"
}).then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
My promise is not being fulfilled and always failing. I am getting an HTTP response with code 400 (Bad Request) and the error argument of the catch function reads:
{
message: "Problems parsing JSON",
documentation_url: "https://developer.github.com/v3"
}
I have already tried passing the variables as JSON, like so:
{
"name": "freeCodeCamp",
"owner": "freeCodeCamp"
}
But it didn't help. I got the same bad request.
Looking at the Network tab of Chrome's inspector I see what the request payload is. Adding it here in case it give any clues or help.
query=query%20repo(%24name%3A%20String!%2C%20%24owner%3A%20String!)%7Brepository(name%3A%24name%2C%20owner%3A%24owner)%7Bid%7D%7D&variables=%7B%22name%22%3A%22freeCodeCamp%22%2C%22owner%22%3A%22freeCodeCamp%22%7D
What am I doing wrong?
The default behaviour of graphql.js is to send the body in form-url-encoded format whereas Github GraphQL api accepts only JSON format. From graphql.js readme :
As default, GraphQL.js makes a POST request. But you can change the
behavior by setting asJSON.
var graph = graphql("http://localhost:3000/graphql", {
asJSON: true
});
You can see the difference here
The following will work as expected :
var graph = graphql("https://api.github.com/graphql", {
headers: {
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
},
asJSON: true
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
id
}
}
`, {
name: "freeCodeCamp",
owner: "freeCodeCamp"
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
});

understanding a http request and nested function in ajax

I am referencing this code to build a twitch viewer app, which I'm having difficulties in understanding:
$(document).ready(function() {
let usernames = ["user1", "user2", "user3", "user4"];
usernames.forEach(function(user) {
let http = "https://api.twitch.tv/kraken/streams/" + user;
function getAjax(getdata) {
$.ajax({
url: http,
headers: {
'Client-ID': 'myclientid'
},
success: function(data) {
getdata(data)
}
});
}
});
})
What does 'headers' do exactly? I looked it up on twitch and couldn't find a detailed description. It doesn't look like it gives/adds anything to my http request. Twitch says the header "securely identify my application." but wasn't sure what that mean. I thought if it works similar to an API key it should be included in the request.
What does the 'getdata' function in this code do? does it simply store the data i receive from the ajax request?
1) Headers are included in the request. You should be able to see them in the developer tools; this is what it looks like in Firefox
2) getdata is a callback function that is passed into getAjax by consumers, which can then act on the data as necessary, for example...
getAjax(function(data) {
// do something with data
})
Note also, you're redeclaring the function in each iteration of the loop, but not actually calling it anywhere. You probably want something more like this...
$(document).ready(function() {
let usernames = ["user1", "user2", "user3", "user4"];
function getAjax(url, getdata) {
$.ajax({
url: url,
headers: {
'Client-ID': 'myclientid'
},
success: function(data) {
getdata(data)
}
});
}
usernames.forEach(function(user) {
let http = "https://api.twitch.tv/kraken/streams/" + user;
getAjax(http, function(data) {
// do something with data
})
});
})

Yammer Open Graph Post - How do i do it?

I am trying to figure out how the payload should be constructed for a Open Graph object to submit to yammer. I can post a standard message, but i would like to post an opengraph message instead.
{
"activity":{
"actor":{"name":"Sidd Singh",
"email":"sidd#xyz.com"},
"action":"create",
"object": {
"url":"https://www.sched.do",
"title":"Lunch Meeting"
},
"message":"Hey, let’s get sushi!",
"users":[
{"name":"Adarsh Pandit",
"email":"adarsh#xyz.com"}
]
}
}
This is some code nicked from their API documentation but doesn't show me how i should use this in javascript. Can someone assist me? Below is my existing code that posts a standard message...
yam.request({
url: "https://www.yammer.com/api/v1/messages.json?network_id=networkname", //this is one of many REST endpoints that are available
method: "POST",
beforeSend: function (req) { //send the access_token in the HTTP header
req.headers.Authorization = "Bearer " + access_token;
},
data: {
"network": "networkname",
"body": "Test Post",
"group_id": "3719771"
},
success: function (data) { //print message response information to the console
toastr.success('An Item was successfully posted to Yammer', "Yammer Network");
},
error: function (user) {
toastr.error('There was an error eith the request', "Yammer Network");
}
});
This post answered your question: Yammer Open Graph API Error 400
Simply replace the key value pairs in the data{} with the activity json strings. Also remember to change the RESTful api endpoint to https://api.yammer.com/api/v1/activity.json

Categories