Paypal sandbox post error 401 (Unauthorized) - paypal

enter image description hereI have been following a tutorial for a paypal sandbox using react-paypal-express-checkout and have followed it exactly, but when I try to open the paypal window it closes instantly and throws this error.
Photo:Photo Here
Text:
http.js:147 POST https://www.sandbox.paypal.com/v1/payment-experience/web-profiles 401 (Unauthorized)
types.js:121 Uncaught Error: Request to post https://www.sandbox.paypal.com/v1/payment-experience/web-profiles failed with 401 error. Correlation id: bfca9a9c3fdfc
{
"name": "AUTHENTICATION_FAILURE",
"debug_id": "bfca9a9c3fdfc",
"message": "Authentication failed due to invalid authentication credentials or a missing Authorization header",
"information_link": "https://developer.paypal.com/docs/api/payment-experience/#errors",
"details": []
}
at XMLHttpRequest.xhrLoad (http.js:114)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
_RECEIVE_MESSAGE_TYPE.<computed> # types.js:121
receiveMessage # index.js:114
messageListener # index.js:140
setTimeout (async)
dispatchPossiblyUnhandledError # exceptions.js:16
(anonymous) # promise.js:122
setTimeout (async)
reject # promise.js:120
dispatch # promise.js:179
reject # promise.js:127
dispatch # promise.js:179
reject # promise.js:127
dispatch # promise.js:186
reject # promise.js:127
(anonymous) # promise.js:157
dispatch # promise.js:184
reject # promise.js:127
(anonymous) # promise.js:51
respond # client.js:147
_RECEIVE_MESSAGE_TYPE.<computed> # types.js:126
receiveMessage # index.js:114
messageListener # index.js:140
serialize.js:175 Uncaught Error: Error: Request to post https://www.sandbox.paypal.com/v1/payment-experience/web-profiles failed with 401 error. Correlation id: bfca9a9c3fdfc
{
"name": "AUTHENTICATION_FAILURE",
"debug_id": "bfca9a9c3fdfc",
"message": "Authentication failed due to invalid authentication credentials or a missing Authorization header",
"information_link": "https://developer.paypal.com/docs/api/payment-experience/#errors",
"details": []
}
at XMLHttpRequest.xhrLoad (http.js:114)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at deserializeError (serialize.js:175)
at serialize.js:212
at util.js:140
at eachArray (util.js:102)
at each (util.js:116)
at replaceObject (util.js:138)
at util.js:147
at eachObject (util.js:109)
at each (util.js:118)
at replaceObject (util.js:138)
Heres the page for my button and all the tutorial guy changes is the sandbox id which I did:
import React from 'react';
import PaypalExpressBtn from 'react-paypal-express-checkout';
export default class MyApp extends React.Component {
render() {
const onSuccess = (payment) => {
// Congratulation, it came here means everything's fine!
console.log("The payment was succeeded!", payment);
// You can bind the "payment" object's value to your state or props or whatever here, please see below for sample returned data
}
const onCancel = (data) => {
// User pressed "cancel" or close Paypal's popup!
console.log('The payment was cancelled!', data);
// You can bind the "data" object's value to your state or props or whatever here, please see below for sample returned data
}
const onError = (err) => {
// The main Paypal's script cannot be loaded or somethings block the loading of that script!
console.log("Error!", err);
// Because the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js"
// => sometimes it may take about 0.5 second for everything to get set, or for the button to appear
}
let env = 'sandbox'; // you can set here to 'production' for production
let currency = 'USD'; // or you can set this value from your props or state
let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout
// Document on Paypal's currency code: https://developer.paypal.com/docs/classic/api/currency_codes/
const client = {
sandbox: 'ASloDPNYZO9LtigzQd58tcYQHuORCH3TlvPS-LWMdwzIWiEiefonUQE7KmWCE-WkaEaiiJb54RSNcrLE',
production: 'YOUR-PRODUCTION-APP-ID',
}
// In order to get production's app-ID, you will have to send your app to Paypal for approval first
// For sandbox app-ID (after logging into your developer account, please locate the "REST API apps" section, click "Create App"):
// => https://developer.paypal.com/docs/classic/lifecycle/sb_credentials/
// For production app-ID:
// => https://developer.paypal.com/docs/classic/lifecycle/goingLive/
// NB. You can also have many Paypal express checkout buttons on page, just pass in the correct amount and they will work!
return (
<PaypalExpressBtn env={env} client={client} currency={currency} total={total} onError={onError} onSuccess={onSuccess} onCancel={onCancel} />
);
}
}

The react-paypal-express-checkout repository does not reference v1/payment-experience/web-profiles , so I am not sure where your error is actually coming from
The v1/payment-experience/web-profiles API requires a valid ClientId and a Secret for authentication.

Related

SolidJS Create Resource - Uncaught Error in Promise

I'm new to SolidJS and I'm having a weird error with resources. Here is my code:
export const authUserResource = createResource(
() => axios.get<AuthUser>('/expense-tracker/api/oauth/user').then((res) => res.data)
);
export const MyComponent = () => {
const [data] = authUserResource;
createEffect(() => console.log('HasChecked', data.loading, data.error, data()));
return (
// ...
)
}
The intent of the API call is to retrieve data on the currently authenticated user, or to return a 401 if the user is not currently authenticated. My intent is to then redirect the user based on their authentication status.
Well, the API is called and it is returning a 401 because the user is not authenticated. All of this is expected. What is not behaving is the SolidJS resource.
If the API returns a 401, I would expect the SolidJS resource data to meet these conditions:
data.loading === false
data.error instanceof Error
data() === undefined
Instead, I am finding that it is still at these conditions, based on the console.log statement in the above code example:
data.loading === true
data.error === undefined
data() === undefined
I also get an "Uncaught Error in Promise" error message in the browser JS console.
I'm hoping to figure out what I am doing wrong here to make the resource correctly handle the error so that I can gracefully handle this in my application.

Why is my PaymentMethod ID not detected when I run my AWS stripe application via Docker?

I am learning web development and I am currently working on creating a lambda test application for stripe. The paymentMethod id from the front-end is not being detected by my lambda function when I run it locally by calling sam local start-api. I am doing my development on VS Code.
I followed the instructions on this page to create and run my application. My directory structure looks like this:
hello_world/app.py has my Lambda function.
The code for invoking the lambda end-point in script.jslooks like this:
var stripe = Stripe('pk_test_DIGITS');
var elements = stripe.elements();
form.addEventListener('submit', function(event) {
// We don't want to let default form submission happen here,
// which would refresh the page.
event.preventDefault();
stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: {
// Include any additional collected billing details.
name: 'Jenny Rosen',
},
}).then(stripePaymentMethodHandler);
});
function stripePaymentMethodHandler(result) {
if (result.error) {
// Show error in payment form
} else {
// Otherwise send paymentMethod.id to your server (see Step 4)
fetch('http://127.0.0.1:3000/payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payment_method_id: result.paymentMethod.id,
})
}).then(function(result) {
// Handle server response (see Step 4)
result.json().then(function(json) {
handleServerResponse(json);
})
});
}
}
I ran the application on the browser by doing this:
When I click on Pay from my browser I can see the response in the logs on my dashboard:
The following code is for my lambda function app.py:
import json
import stripe
import requests
import logging
stripe.api_key= "sk_test_DIGITS"
def process_payment(event, context):
try:
print("START PRINTING")
print(event)
print("END PRINTING")
intent = stripe.PaymentIntent.create(
payment_method = 'event["body"]["payment_method_id"]',
amount = 1555,
currency = 'usd',
confirmation_method = 'automatic',
confirm = True,
payment_method_types=["card"]
)
return {
"statusCode": 200,
"body": json.dumps({
'clientSecret': intent['client_secret'],
# "location": ip.text.replace("\n", "")
}),
}
except Exception as e:
return {
"statusCode": 400,
"body": json.dumps({
"message": str(e),
# "location": ip.text.replace("\n", "")
}),
}
My template.yaml is as follows:
Globals:
Function:
Timeout: 30
Resources:
StripePaymentProcessor:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.process_payment
Runtime: python3.6
Events:
Payment:
Type: Api
Properties:
Path: /payment
Method: post
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Payment function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/payment/"
HelloWorldFunction:
Description: "Payment Lambda Function ARN"
Value: !GetAtt StripePaymentProcessor.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Payment function"
Value: !GetAtt StripePaymentProcessorRole.Arn
While keeping the browser window open, I ran the sam build command and it worked properly. After that I ran the sam local invoke command and it produced the following output:
I do not understand why event is empty. Should it not show the JSON data that got produced when I hit the pay button?
To do some trouble-shooting, I ran sam local start-api, invoked the POST method on Postman by pasting the JSON body from my Stripe logs:
What I did on Postman makes no sense to me and the snippet above raised another question for me. I do not understand why I see "message": "string indices must be integers" as a response on Postman.
EDIT:
After following wcw's suggestion I edited my fetch code to look like this:
I did not not see any written matter on the console by changing my code in this way.
I am keeping the browser open via the command prompt and I ran sam local start-api via the VS code console to keep http://127.0.0.1:3000/payment open. When I clicked on the pay button, I got the following response:
So the image above seems to indicate that the lambda function is not detecting the paymentmethod body.

Capture Error on Subscription Smart Button Integration with SDK - Both Sandbox and Live

Case: Error when setting up a subscription via Smart Payment Buttons
Remark: In the Live environment I did get charged in my account for the transaction
Error: There is a capture error, and from 3 days of testing in both Sandbox AND Live cases there is not one solution found
For Sandbox Mode, I found a few references for the exact same error, but for those people it a. seems to have vanished overnight and 2. those weren't subscription models but regular purchase modes.
The following are the scripts and it shouldn't be that hard as I am making it, we set up a similar billing environment couple years ago and that worked almost immediately, that wasn't a subscription though.
Further details:
- I did setup the correct env settings as well in the composer files.
- Product is there
- Plan is there
- We use Seat based Pricing (0.01 cent and then we multiply the total amount in dollars *100)
////////////////////////////////////
// Error 500
////////////////////////////////////
// Via Console
POST https://www.paypal.com/smart/api/order/9VU587...34202/capture 500
// Via Network
{ack: "error", message: "Unhandled api error", meta: {calc: "4ac27dc9b8a70",…},…}
////////////////////////////////////
// Smart Button Script
////////////////////////////////////
<script src="https://www.paypal.com/sdk/js?vault=true&client-id=<?= $paypal_sandbox_id ?>&currency=<?php echo $currency ?? "USD"; ?>&debug=false"></script>
<script>
paypal.Buttons({
// Set up the subscription
createSubscription: function (data, actions) {
return actions.subscription.create({
'plan_id': 'P-6NH76920JR31236564LYU3X4Y',
'quantity': total_billed_vat * 100
});
},
// Finalize the transaction
onApprove: function (data, actions) {
console.log('onApprove', data);
// Authorize the transaction
return actions.order.capture().then(function (details) {
console.log('capture', details);
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
// Call your server to save the transaction
return fetch('../api/paypal/paypal-transaction-complete.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
});
}).then(function (response) {
// Show a success message to the buyer
alert('actions.order.capture done ' + details.payer.name.given_name + '!');
});
},
onCancel: function (data, actions) {
// Show a cancel page or return to cart
alert('Feel free to retry when you are ready');
}
}).render('#paypal-button-container');
</script>
The PHP Serverside Script:
////////////////////////////////////
// ../api/paypal/paypal-transaction-complete.php
////////////////////////////////////
<?php
namespace Sample;
require __DIR__ . '/vendor/autoload.php';
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;
class GetOrder
{
// 2. Set up your server to receive a call from the client
/**
*You can use this function to retrieve an order by passing order ID as an argument.
*/
public static function getOrder($orderId)
{
// 3. Call PayPal to get the transaction details
$client = PayPalClient::client();
$response = $client->execute(new OrdersGetRequest($orderId));
/**
*Enable the following line to print complete response as JSON.
*/
//print json_encode($response->result);
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
// To print the whole response body, uncomment the following line
// echo json_encode($response->result, JSON_PRETTY_PRINT);
}
}
/**
*This driver function invokes the getOrder function to retrieve
*sample order details.
*
*To get the correct order ID, this sample uses createOrder to create a new order
*and then uses the newly-created order ID with GetOrder.
*/
if (!count(debug_backtrace()))
{
GetOrder::getOrder($data->orderID, true);
}
The SDK Used for v2 of the PayPal integration.
////////////////////////////////////
// SDK Installed in ../api/paypal/
////////////////////////////////////
{
"require": {
"paypal/paypal-checkout-sdk": "^1.0"
}
}
Used Manual Source: https://developer.paypal.com/docs/subscriptions/integrate/
One of the Found Issue Resources: https://www.paypal-community.com/t5/REST-APIs/BASIC-Smart-Payment-buttons-integration-help/td-p/1844051
This is the type of "500 Internal Service Error" API response that you're best off reaching out to PayPal's support for (MTS), rather than Stack Overflow, since it's effectively being thrown on the PayPal server end without details and needs to be traced back. However, I do happen to have some knowledge and in this case my suspicion would be that the transaction amount is not matching the purchase unit amount. Maybe this is something you can correct with a simpler request, i.e. test with a simple static number like $10 from start to finish and see if the problem does not occur.

PayPal Express checkout - does not seem to run successfully

So, I am trying to figure this out but cannot seem to get this right.
I am trying to integrate paypal express onto a website. I have the sandbox environment with the facilitator and buyer accounts.
I paste in the sample code and change the client values and transaction details etc... like so:
paypal.Button.render({
env: 'sandbox', // Optional: specify 'sandbox' environment
client: {
sandbox: 'My Client ID here'
},
payment: function () {
var env = this.props.env;
var client = this.props.client;
return paypal.rest.payment.create(env, client, {
intent: "sale",
payer: { payment_method: "paypal" },
transactions: [
{
amount: { total: '14.00', currency: 'GBP' },
description: "This is a payment description"
},
],
redirect_urls: {
return_url: "http://somesite.com/success",
cancel_url: "http://somesite.com/cancel"
}
});
},
commit: true, // Optional: show a 'Pay Now' button in the checkout flow
onAuthorize: function (data, actions) {
// Optional: display a confirmation page here
alert('confirmation here');
return actions.payment.execute().then(function () {
// Show a success page to the buyer
alert('success here');
});
}
}, '#paypal-button');
The issue I am facing is that when you hit the paypal button - in the popup I do not see the amount.
Then when continuing, I get an error from javascript like so:
JavaScript runtime error: Error: Payment Api response error:
{
"name": "INTERNAL_SERVICE_ERROR",
"message": "An internal service error has occurred",
"information_link": "https://developer.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR",
"debug_id": "a9ceebeb96bab"
}
Error: Payment Api response error:
{
"name": "INTERNAL_SERVICE_ERROR",
"message": "An internal service error has occurred",
"information_link": "https://developer.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR",
"debug_id": "a9ceebeb96bab"
}
at Anonymous function (https://www.paypalobjects.com/api/checkout.js:8325:17)
at _loop2 (https://www.paypalobjects.com/api/checkout.js:1509:25)
at SyncPromise.prototype.dispatch (https://www.paypalobjects.com/api/checkout.js:1542:17)
at SyncPromise.prototype.resolve (https://www.paypalobjects.com/api/checkout.js:1480:13)
at Anonymous function (https://www.paypalobjects.com/api/checkout.js:1533:25)
at _loop2 (https://www.paypalobjects.com/api/checkout.js:1509:25)
at SyncPromise.prototype.dispatch (https://www.paypalobjects.com/api/checkout.js:1542:17)
at SyncPromise.prototype.resolve (https://www.paypalobjects.com/api/checkout.js:1480:13)
at Anonymous function (https://www.paypalobjects.com/api/checkout.js:1533:25)
at _loop2 (https://www.paypalobjects.com/api/checkout.js:1509:25)
So how the heck do I know what the error is?
Second question: Hopefully when this is all working with your help, how can I get back the response and determine if its a success or failure of payment along with detailed information to log it on my website and display to the user? What about custom variables like paymentID generated from my site? Can I get that information back?
Thank you
You're missing some important information for the API.
Things like AMOUNT{}, and others.
https://developer.paypal.com/docs/integration/direct/create-process-order/
I have a problem with this as well, I can get to the actions.payment.execute() and I get an error, _loop2 etc etc.

UNPROCESSABLE ENTITY saving user on Ionic Platform Beta

I have moved from Ionic Platform Alpha to Beta.
I have implemented signup and
login with success, but everytime I try to execute
save action I get this error:
Failed to load resource: the server responded with
a status of 422 (UNPROCESSABLE ENTITY)
Just a snippet of my code:
user = Ionic.User.current();
console.log("User %s is authenticated: %s", user.id, user.isAuthenticated());
user.set('age', '25');
user.save();
This is the output:
User ee18171e-1384-4911-98ed-e1b2fc6e89bf is authenticated: true
Failed to load resource: the server responded with a status
of 422 (UNPROCESSABLE ENTITY) (https://api.ionic.io/auth/user...
Ionic User: Object {response: XMLHttpRequest, error: Error}
Analyzing the error this is shown:
Field may not be null
But I can't figure which field is null is this request ....
Does someone know how to perform a save action on Ionic Platform Beta?
Probably a little late for a reply here,
but just in case someone is looking for an answer.
When setting a user, Ionic is looking for an email address and password:
var details = {
'email': '$scope.data.email',
'password': $scope.data.password
}
Ionic.Auth.signup(details).then(
function(user){
user.migrate();
user.save(); // save the user to persist the migration changes
console.log('success');
},
function(user){
console(user + 'not added to ionic')
}
);
This will register the user