Edit: I've fixed my original problem and have shown a metor example in my answer.
I'm getting a error 500 when trying to get the token for my PayPal API app in Meteor:
token = EJSON.stringify(Meteor.http.call "POST", "https://api.sandbox.paypal.com/v1/oauth2/token",
headers:
"Accept": "application/json"
"Accept-Language": "en_US"
auth: "user:pass"
params:
"grant_type":"client_credentials"
);
console.log("Token: "+token);
Output of this code:
Token: {"statusCode":500,"headers":{"server":"Apache-Coyote/1.1","date":"Fri, 15 Mar 2013 05:04:43 GMT","content-length":"0","connection":"close"},"data":null,"error":{}}
Obviously PayPal is returning a error 500 to me. I can't figure out what may be causing this. Of course Auth is actual data, not user:pass.
Why am I getting error 500?
Edit: Compiled Javascript
var token;
token = EJSON.stringify(Meteor.http.call("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", {
headers: {
"Accept": "application/json",
"Accept-Language": "en_US"
},
auth: "user:pass",
params: {
"grant_type": "client_credentials"
}
}));
console.log("Token: " + token);
Here's an example implementation to make paypal API calls with meteor.
In the startup of your program, fetch your token. Always replace clientid and clientsecret with your own.
token = EJSON.parse(Meteor.http.post("https://api.sandbox.paypal.com/v1/oauth2/token",
headers:
"Accept": "application/json"
"Accept-Language":"en_US"
auth: "clientid:clientsecret"
params:
"grant_type":"client_credentials"
#encoding: "base64"
).content).access_token;
Now, create a payment, shown here in a Meteor.methods method (and returning a URL for the client to go to):
buySingleItem: () ->
console.log "Starting new payment, user id: "+Meteor.userId()
result = Meteor.http.post("https://api.sandbox.paypal.com/v1/payments/payment",
headers:
"Authorization":"Bearer "+token
"Content-Type": "application/json"
data:
{
"intent":"sale"
"redirect_urls":
"return_url":"http://mysite.herokuapp.com/done",
"cancel_url":"http://mysite.herokuapp.com/cancel"
"payer":
"payment_method":"paypal"
"transactions":[
{
"amount":
"total":"3.00",
"currency":"USD"
"description":"My item description."
}
]
}
)
payment = result.data
console.log "PayPal redirect: "+payment.links[1].href
return payment.links[1].href
This will create a PayPal checkout style payment, within Meteor.
I would provide sample code, but I'm not familiar with Meteor.
Basically you have 2 issues here:
in your headers, you are not passing the client id or client secret. This should look like:
Authorization: Basic clientid:clientsecret
Also, in your request, your request should look like this:
response_type=token&grant_type=client_credentials
Looks like your in json then stringifying it, so whatever way you need to get the POST request I just put up there, once you get it, you should be good.
[edit]PayPal's doc's dont have you base64 encode the client id or secret[/edit]
Then, when you need to execute the payment you can do as below. See the whole payment process here.
Meteor.methods
'executePaypalPayment': (payerId) ->
payment = PaypalPayments.findOne({ userId: #userId },
{ sort: { 'create_time': -1 } })
token = Meteor.call 'getPaypalToken'
url = 'https://api.sandbox.paypal.com/v1/payments/payment/' +
payment.id + '/execute'
res = Meteor.http.post url,
headers:
Authorization: 'Bearer ' + token.access_token
'Content-Type': 'application/json'
data:
payer_id: payerId
payment = res.data
payment['userId'] = #userId
if payment.state is 'approved'
# we insert the sucessful payment here
PaypalPayments.insert payment
return if payment.state is 'approved' then true else false
Related
I'm trying to setup a website using Wordpress as Headless CMS, using the built-in REST API. Using NuxtJS to fetch the data. Now I want to restrict API access so I enabled/created Wordpress Application Password Authentication.
However, I can not seem to find detailed information on how the URL should be assembled with authentication parameters to fetch data from API endpoint.
Credentials have to be added to the URL that's being fetched?
async asyncData ({ $config: { apiUrl, apiUser, apiPassword } }) {
try {
const products = await (await fetch(`${apiUrl}/producten`)).json()
return {
products
}
}
catch (error) {
console.log(error)
}
},
apiUrl, apiUser, apiPassword are currently in nuxtjs.config.js, under publicRuntimeConfig. But 1) they should come in privateRuntimeConfig?
And 2) getting following as return (which is the correct response from the WP Rest API, because I need to pass auth-credentials somewhere, somehow...)
{ "code": "rest_not_logged_in", "message": "You are not currently logged in.", "data": { "status": 401 } }
Solved by adding options to fetch;
const fetchHeaderOptions = {
cache: 'no-cache',
method: 'GET',
credentials: 'omit', //To instead ensure browsers don't include credentials in the request
mode: 'no-cors',
headers: {
'Authorization': 'Basic ' + encode(`${apiUser}` + ":" + `${apiPassword}`),
'Content-Type': 'application/json; charset=UTF-8; application/x-www-form-urlencoded',
},
}
const products = await (await fetch(`${apiUrl}/products`, fetchHeaderOptions)).json()
Unable to share image content through share endpoint, image asset is uploaded through assets API but my request to share API which is copied directly from the example here https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/share-api?context=linkedin/compliance/context#share-content returns an error, invalid parameters in the request body [/Headers] see below details.
Request Headers:
{Authorization: Bearer ***
X-Restli-Protocol-Version: 2.0.0
}
Request Body
{"content":{"contentEntities":[{"entity":"urn:li:digitalmediaAsset:C5622AQEEn3mmqzCb5w"}],"title":"Great Result","landingPageUrl":"https://google.com.au","shareMediaCategory":"IMAGE"},"distribution":{"linkedInDistributionTarget":{}},"owner":"urn:li:person:zzR_UbXjsG","subject":"Great Result","text":{"text":"Great result, couldn't have gone better #realestate"}}
Scopes:
scope=r_emailaddress w_member_social w_organization_social r_basicprofile rw_company_admin rw_organization_admin
Error:
{"serviceErrorCode":100,"message":"Unpermitted fields present in REQUEST_BODY: Data Processing Exception while processing fields [/Headers]","status":403}
It looks like the error message has to do with the headers. Your request body is JSON, but you don't have a Content-Type header set, so this could be the problem:
Content-Type: application/json
Generally, you need a Content-Length header to be sent along with that, but most of the time the client you are using to send the request handles setting that one.
I'm not sure how you're making the request, but here is a fetch() example in JavaScript (make sure you put the correct auth token in the Authorization header):
const url = 'https://api.linkedin.com/v2/shares';
const requestBody = {
"content": {
"contentEntities": [
{
"entity": "urn:li:digitalmediaAsset:C5622AQEEn3mmqzCb5w"
}
],
"title": "Great Result",
"landingPageUrl": "https://google.com.au",
"shareMediaCategory": "IMAGE"
},
"distribution": {
"linkedInDistributionTarget": {}
},
"owner": "urn:li:person:zzR_UbXjsG",
"subject": "Great Result",
"text": {
"text": "Great result, couldn't have gone better #realestate"
}
};
async function makeRequest(url, requestBody) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ***',
'X-Restli-Protocol-Version': '2.0.0'
},
body: JSON.stringify(requestBody) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
// make the actual request
makeRequest(url, requestBody);
I have a firebase database and i need to do a classic post call, but i have a problem with token.
For example, in firebase for get user i use app().auth().currentUser.uid,
for a classic get list i use app().firestore().collection('prizes') and it work.
so, to get user token i do app().auth().currentUser.getIdToken()
and for post i do
export function postData(endpoint: string, data: any, token) {
return fetchJson(ENDPOINT_API + endpoint}, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token ? token : USER_TOKEN}`,
},
})
}
and result is
{"error":"Token invalid","message":"Cannot destructure property type of 'undefined' or 'null'."}
the token comes back to me, but I don't know if it's the correct way
This line:
Authorization: `Bearer ${token ? token : USER_TOKEN}`,
Replace it by:
'Authorization': `Bearer ${token ? token : USER_TOKEN}`,
I am new to WooCommerce REST API. I want to add product to cart and list all products of cart. I have added Co-Cart plugin to my server and I am using Co-Cart APIs for cart related functionality.
Issue I am facing is, I am not able to view cart products in my react native application. Here are the APIs I am using right now:
1. Add product to cart:
Method:POST
URL: https://www.myhost.com/wp-json/wc/v2/cart/add?token=user_token
Parameteres: {
"product_id": "9168",
"quantity": "1"
}
Response:{
"key": "af086cdab7954f11a518e3af68XXXXX",
"product_id": 111,
"variation_id": 0,
"variation": [],
"quantity": 1,
"data": {},
"data_hash": "b5c1d5ca8bae6d4896cf1807cdfXXXX",
"line_tax_data": {
"subtotal": [],
"total": []
},
"line_subtotal": 50000,
"line_subtotal_tax": 0,
"line_total": 50000,
"line_tax": 0
}
Getting proper response with status code 200 while adding product to cart from application.
2. View cart content
Method: GET
URL: https://www.myhost.com/wp-json/wc/v2/cart?token=user_token
Response: [] (Blank JSON array)
I don't know where are the products which are added to cart using same user. I don't how it manages session from mobile application or what extra parameters it requires to fetch cart items.
Please let me know where I am going wrong. I am using Co-Cart plugin API only.
**
EDIT
**
fetch(url, {
method: methodName,
async: true,
crossDomain: true,
headers: new Headers({
"Content-Type": "application/json",
"cache-control": "no-cache",
}),
body:data
}).then((response) => {
const statusCode = response.status;
console.log("fetchData StatusCode : "+statusCode);
console.log("fetchData response1 : " + JSON.stringify(response));
console.log("fetchData response2 : " + response);
return response.json();
}).then((responseJson) => {
console.log("fetchData responseJson : "+responseJson);
var response = JSON.stringify(responseJson);
console.log("fetchData responseJson stringify : " + response);
response = JSON.parse(response);
if (callBack != null) {
callBack("", response);
}
}).catch((error) => {
console.log("fetchData Api error : "+error);
if (callBack != null) {
console.log("fetchData Api error callBack != null 2");
callBack("Error", "");
}
});
url is a URL to send, data is raw data in JSON string format and method is either GET or POST.
Here is the answer of my own question.
It is somehow difficult to integrate WooCommerce store into Mobile Application without having prior knowledge of WooCommerce and its working criteria.
The issue was it was not adding products to my logged-in user's cart and that's why it was not getting all the products for that user as products were not added to the user's cart.
The issue why it was not syncing my cart with my current user was for cookie session for that particular user. I need to set cookie of that user in each API call header after login something like this:
fetch(url1, {
method: methodName,
async: true,
crossDomain: true,
headers: new Headers({
"Content-Type": "application/json",
"cache-control": "no-cache",
"cookie":"cookie value will goes here"
}),
body:data1
})
It just resolved my issue. Hope it helps!
I check the documentation, https://co-cart.github.io/co-cart-docs/#view-cart-contents and but nothing wrong with your.
Can you check if the Pretty permalinks in Settings > Permalinks so that the custom endpoints are supported. Default permalinks will not work.
I have a route in Rails API '/api/pay'. My client side post request successfully hits the controller action, however nothing I send in the body: JSON.stringify('...') gets through to the back-end. Other post requests I have made work just fine with the same format.
export const payForItem = (payData) => {
return dispatch => {
dispatch(payForItemStart());
// ?userID=${data.userID}&adID=${data.adID}&price=${data.price}
const data = {userID: payData.userID, adID: payData.adID, price: payData.price}
fetch(`/api/pay`, {
method: 'POST',
header: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
Here is what payData looks like.
Rails Api back-end params
Probably you've got typo in headers section. Should be plural headerS with s:
headers: {
"Content-Type": "application/json"
}