How do I get more information after subscribing? - paypal

I don't know how to get more information after subscription.
The following returns an error:
paypal.Buttons({
createSubscription: function (data, actions) {
console.log(data)
return actions.subscription.create({
'plan_id': PP_PLAN_ID
})
},
onApprove: function (data, actions) {
console.log(data)
fetch(`https://api.sandbox.paypal.com/v1/billing/subscriptions/${data.subscriptionID}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.facilitatorAccessToken}`
}
})
.then((r) => {
return r.json()
})
.then((r) => {
console.log(r)
})
}
}).render('#paypal-button-container')
Error response
{
"name": "NOT_AUTHORIZED",
"message": "Authorization failed due to insufficient permissions.",
"debug_id": "e0ba8b67ee540",
"details": [
{
"issue": "PERMISSION_DENIED",
"description": "You do not have permission to access or perform operations on this resource."
}
],
"links": [
{
"href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#NOT_AUTHORIZED",
"rel": "information_link",
"method": "GET"
}
]
}
I'm guessing some configuration is missing because of the permission error. Any pointers?

This is not a client-side operation, and a ClientID access token will not have permission.
You need to obtain the access token from a server, using a ClientID and Secret: https://developer.paypal.com/docs/api/overview/#get-an-access-token

Related

flutter login with dio package

i try to login to the api with dio and i cant handle it
my scenario is:
login with user name,password and server returned session like this:
{
"function": "request_session_generate",
"params": {
"username": "myuser",
"password": "mypass"
}
}
and when send request post method returned session like below code:
{
"result": 0,
"data": {
"session": "mysession...",
"session_status": "generated"
}
}
and second post method for validate this session ... put the session and otp code(google authenticator) like this:
{
"function": "request_session_validate",
"params": {
"session": "mysession",
"otp": "123456"
}
}
when put the session in to the session params server returned:
{
"result": 0,
"data": {
"session": "newSession",
"session_status": "validated"
}
}
how can get the session in the body response first method and use it in the second function for validate
my first function implement code :
class ApiClient {
final Dio _dio = Dio();
Future<Response?> login() async {
try {
Response response = await _dio.post(
'myserver/api',
options: Options(
headers: {
"apikey": "00000000-0000-0000-0000-000000000000",
},
),
data: {
"function": "request_session_generate",
"params": {
"username": "myuser",
"password": "mypass"
}
},
);
//returns the successful user data json object
if(response.statusCode == 200){
return response.data;
}
} on DioError catch (e) {
//returns the error object if any
return e.response!.data;
}
return null;
}
and my implemention for validate and not worked:
Future<Response?> validate() async {
try {
Response responsevalidate = await _dio.post(
'myserver/api',
data: {
"function": "request_session_validate",
"params": {
"session": "mysession",
"otp": "123456"
}
},
);
//returns the successful user data json object
return responsevalidate.data;
} on DioError catch (e) {
//returns the error object if any
return e.response!.data;
}
//IMPLEMENT USER LOGIN
}
how can get session in first function and use it in second function for validate?
use the json decode or something else ?
thank you for help me

PayPal Integration and payment status in react native

I'm trying to integrate PayPal as a payment method in my react-native app. I get an access token by hitting https://api.sandbox.paypal.com/v1/oauth2/token API, but when I'm trying to pass access token to payment API https://api.sandbox.paypal.com/v1/payments/payment got response with status code 400 or 500 both are varying.
My code is
let currency = '100 INR'
currency.replace("INR", "")
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"total": currency,
"currency": "INR",
"details": {
"subtotal": currency,
"tax": "0",
"shipping": "0",
"handling_fee": "0",
"shipping_discount": "0",
"insurance": "0"
}
}
}],
"redirect_urls": {
"return_url": "https://example.com",
"cancel_url": "https://example.com"
}
}
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('AUrtJxcHfMUlDjHgV2FHMOUnzMkUeu86_km7h67uEHzH5b5RN7Vo-q8AYPtcdz7Iaioc46xW0H9JQZmT:EMbbJ-YqQLT6liuPtJURq2pAgh9WuUTDKmV355_VIeADst0BMlnUNKiHVLK7itCyZFXrEQOex9p93WO8')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data.access_token)
this.setState({accessToken:data.access_token})
// console.log(JSON.stringify(dataDetail))
fetch ('https://api.sandbox.paypal.com/v1/payments/payment',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+(this.state.accessToken)
},
body:dataDetail
}
)
.then(response => {
console.log('response=====',response)
// const { id, links } = response.data
// const approvalUrl = links.find(data => data.rel == "approval_url")
// this.setState({
// paymentId: id,
// approvalUrl: approvalUrl.href
// })
}).catch(err => {
console.log({ ...err })
})
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
}
)
Any one can help please ?
response
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "f2d967a5-2700-4f03-b2ac-2e4ec22f10e4", "offset": 0, "size": 232}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "f2d967a5-2700-4f03-b2ac-2e4ec22f10e4", "offset": 0, "size": 232}}, "bodyUsed": false, "headers": {"map": {"cache-control": "max-age=0, no-cache, no-store, must-revalidate", "content-language": "*", "content-length": "232", "content-type": "application/json", "date": "Tue, 23 Feb 2021 07:20:25 GMT", "paypal-debug-id": "27bb91ae40c3a"}}, "ok": false, "status": 400, "statusText": undefined, "type": "default", "url": "https://api.sandbox.paypal.com/v1/payments/payment"}
reference Link PAYPAL INTEGRATION IN REACT-NATIVE
https://api.sandbox.paypal.com/v1/payments/payment
v1/payments is a deprecated API. You should integrate the current v2/checkout/orders instead.
Here is some documentation -- you want "Create Order" and "Capture Order" API calls.
But, if you want to understand the problems with your v1 code, here they are fixed and with proper request+response data logging
Issues:
currency variable wasn't being set to a valid number w/o spaces
You need to JSON.stringify() your request body.
<script>
let currency = '100 INR';
currency = currency.replace("INR", "").trim() ; //this was a problem line, replace() is not in-place. And also extra space to trim
let accessToken = '';
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"total": currency,
"currency": "INR",
"details": {
"subtotal": currency,
"tax": "0",
"shipping": "0",
"handling_fee": "0",
"shipping_discount": "0",
"insurance": "0"
}
}
}],
"redirect_urls": {
"return_url": "https://example.com",
"cancel_url": "https://example.com"
}
}
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('AUrtJxcHfMUlDjHgV2FHMOUnzMkUeu86_km7h67uEHzH5b5RN7Vo-q8AYPtcdz7Iaioc46xW0H9JQZmT:EMbbJ-YqQLT6liuPtJURq2pAgh9WuUTDKmV355_VIeADst0BMlnUNKiHVLK7itCyZFXrEQOex9p93WO8')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data.access_token)
accessToken=data.access_token
// console.log(JSON.stringify(dataDetail))
let createRequest = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+(accessToken)
},
body:JSON.stringify(dataDetail)
}
console.log('Request body string',createRequest.body);
console.log('Request body (formatted)', JSON.stringify( JSON.parse(createRequest.body) ,null,4) );
fetch ('https://api.sandbox.paypal.com/v1/payments/payment',createRequest
)
.then(function(response) {
console.log('Response object', response);
return response.json()
})
.then(async(data) => {
console.log('Response data',data);
console.log('Response data (formatted)', JSON.stringify(data,null,4) );
}).catch(err => {
console.log({ ...err })
})
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
})
</script>

HTTP request to Cloud-Convert not working

I am trying to use fetch to POST an API call to Cloud Convert and getting the following error:
message: "The given data was invalid."
code: "INVALID_DATA"
errors: {...}
tasks: Array(1)
0: "The tasks field is required."
Here is my code (on Wix):
export async function convertMp4toMp3(fileUrl, filename) {
filename = filename.replace(/mp4/gi, "mp3")
let job = {
tasks: {
"import-2": {
"operation": "import/url",
"url": fileUrl
},
"task-1": {
"operation": "convert",
"input_format": "mp4",
"output_format": "mp3",
"engine": "ffmpeg",
"input": [
"import-2"
],
"audio_codec": "mp3",
"audio_qscale": 0
},
"export-1": {
"operation": "export/google-cloud-storage",
"input": [
"task-1"
],
"project_id": "project-id",
"bucket": "bucket",
"client_email": "client_emailXXXXXXX",
"file": filename,
"private_key": "My Private Key
}
}
}
let options = {
"method": "POST",
"body": job,
"headers": {
"Authorization": "Bearer MyApiKey",
"Content-type": "application/json"
}
}
let response = await fetch("https://api.cloudconvert.com/v2/jobs", options)
console.log(response.json())
}
As you can see, the "tasks" field is populated with the jobs...
The fetch API does not automatically encode JSON.
Try:
let options = {
"method": "POST",
"body": JSON.stringify(job),
"headers": {
"Authorization": "Bearer MyApiKey",
"Content-type": "application/json"
}
}

How to control document do not get or add additional property in loopbak?

I have a registration model in loopback over mongodb with fallowing properties:
"properties": {
"Fname": {
"type": "string",
"required": true
},
"Lname": {
"type": "string",
"required": true
},
"phone": {
"type": "string",
"required": true
},
"date": {
"type": "string",
"required": true
},
"time": {
"type": "string",
"required": true
}
}
in application I post some additional data with model required data, for controlling and processing in server side:
submitForm() {
let headers = new Headers(
{
'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
let data = JSON.stringify({
Fname: this.form.Fname,
Lname: this.form.Lname,
phone: this.form.phone,
time: this.form.time,
date: this.form.date,
uid: this.form.uid
});
//console.log(data);
let url = 'http://localhost:3000/api/registrations';
return new Promise((resolve, reject) => {
this.http.post(url, data, options)
.toPromise()
.then((response) => {
console.log('API Response : ', response.status);
resolve(response.json());
})
.catch((error) => {
console.error('API Error : ', error.status);
console.error('API Error : ', JSON.stringify(error));
reject(error.json());
});
});
}
In server side I have this code:
Registration.observe('before save', function (ctx, next) {
if (ctx.instance) {
// When Create (POST)
// ctx.instance have the json properties
console.log("Triggers when create");
if (checkUID(ctx.instance) ==200 ){
console.log('ok');
}
} else {
// When Update (UPDATE)
// ctx.data have the json properties
console.log("Triggers when update");
}
next();
});
but after successfully registration I saw that uid that was added into document and regardless to model's properties, document contains addition properties.
{
"Fname": "Eram",
"Lname": "SA",
"phone": "1234567890",
"date": "2017/10/06",
"time": "17:37:46",
"id": "59d78e3f5e5e6704205038aa",
"uid": "38bc3241a43073a7b40d186f24923cc5"
},

Sending push notification using ionicframework cloud api

Hello am trying to send push notification from my nodejs server to ionicframework API and am getting an error here is my code
var token = '66a5c472b52d3210b591f717b5b996312f8xxxxxxxxxxxx';
var title = 'test';
var message = 'message';
var options = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
json : {
"send_to_all": true,
"profile" : "my-profile",
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};
request(options, function(err, response, body) {
if (err) throw new Error(err);
console.log(body);
});
am getting this error
{ error:
{ message: 'JWT decode error occurred.',
link: null,
type: 'Unauthorized' },
meta:
{ status: 401,
version: '2.0.0-beta.0',
request_id: '75726406-3060-4329-a59e-3bd7f9ca90c8' } }
What could I be doing wrong
I think there is issue with your authorization header.
In header you're putting token, but please make sure it is API token.
Also make a postman request first and check whether it is working fine.
add content-type and authroization parts in header only..
then check the difference..
Thanks
Basu