how to create transaction without plan in braintree js+python?(whiteout subscription) - javascript

I am using braintree payment gateway in my application.
i am able to create the transactions with selecting the plan, but what i needed is to create the transaction without selecting any plan. One time payment.
my code
create_sub = braintree.Subscription.create({
"payment_method_token": the_token,
"plan_id": PLAN_ID
})
here subscription is created.
payment_method_result = braintree.PaymentMethod.create({
"customer_id": merchant_customer_id,
"payment_method_nonce": nonce,
"options": {
"make_default": True
}
})
here payment_method is got created
here what i want is to create transaction directly without subscribing.
and save all transaction related data to transaction model.

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
You can create a one-time transaction with Braintree's Python API library using the following call:
result = braintree.Transaction.sale({
"amount": "10.00",
"payment_method_token": the_token,
"options": {
"submit_for_settlement": True
}
})
This creates a single transaction with no affiliation to any plan. In place of the "payment_method_token", you may also use "payment_method_nonce", passing in the nonce received from your client. You can find the full list of available parameters in Braintree's API Documentation.

Related

Error with AWS SDK-JS API when Retrieving Seller Partner Product Catalog Inventory

I need to retrieve the product catalog of my seller partner on Amazon. Although the API refers to this as "Inventory," I couldn't find this term in the SDK documentation. I assume that the "Catalog" namespace is the equivalent.
Update:
My custom application requires a list of the following product values:
ASINs
UPCs
SKUs
FNSKUs
I have read the documentation and found an API that returns what I need, which can be found here:
https://developer-docs.amazon.com/sp-api/docs/fba-inventory-api-v1-use-case-guide
According to the documentation, I need to create a signature in order to use the API. However, it is noted that if I use the AWS SDK, I do not need to calculate the signature myself. Therefore, I understand that the best practice is to use the AWS SDK.
I have the necessary IAM role permissions and the SP-API app has been published. I am currently attempting to use the AWS SDK.
I have made some changes based on recommendations, but I am not completely sure what else I need to do. Here is my current code:
```
export const /*bundle */ start = async () => {
const client = new MarketplaceCatalogClient({
region: REGION,
credentials: {
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: ACCESS_SECRET_KEY,
},
});
const params = {
/** input parameters */
};
const answer = await client.send(
new ListEntitiesCommand({ Catalog: "AWSMarketplace", EntityType: "ContainerProduct" })
);
console.log(100, answer);
return answer;
};
```
I got the next answer with "AmiProduct" or "ContainerProduct":
{
'$metadata': {
httpStatusCode: 200,
requestId: '91fc5fed-6cdc-42d6-97ec-1ed3cc9d5796',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
EntitySummaryList: []
}
I'm having difficulty understanding how to correctly implement this. Any guidance would be greatly appreciated.
The docs should be better. I spent a good 15 mins on the docs at https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html and failed to find a full list of valid EntityType values.
Some EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/seller-products.html
AmiProduct
ContainerProduct
It looks like these types correspond to the product types in the index of the seller guide here -> https://docs.aws.amazon.com/marketplace/latest/userguide/machine-learning-products.html. It's not clear what the other valid values are.
Some other EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/private-marketplace.html
Experience
Procurement Policy
It looks the way to go for now is to scrounge these valid values from examples in the docs https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html. Not the best developer experience :grimace:
Assuming you are a seller, that you have registered successfully with your AWS account. You can then use Marketplace APIs.
To use them, you have to create an IAM role or a user with policies to grant access to invoke the selected APIs like listEntities, describeEntity, etc.
Here I again assume you have the Cognito authorized credentials if using AWS SDK.
Now to view the list of products successfully published, you use listEntites command.
You can only view AMI or Containter product types. Read here.
It uses minimum two required parameters Catalog and EntityType. The former has a fixed value AWSMarketplace, and latter can have a value either AmiProduct or ContainerProduct.
To get a detailed information about a specific product, you use describeEntity command. It takes minimum 2 required parameters Catalog and EntityID.
The former again has a fixed value AWSMarketplace. For latter, you'll obtain it from the listEntites response.

nodeJS Paypal REST API to revise plan give broken but working link

I'm trying to integrate Paypal into my app in NodeJS. I'm using REST API since the official npm packet is deprecated.
Let's suppose I have a product with two plans, planA and planB, necessary for recurring payments like subscriptions. Suppose a customer subscribe to planA, which costs 10$. After a while, he wants to switch to planB, which costs 20$, to unlock premium content in the platform.
I found the API: POST/v1/billing/subscriptions/{id}/revise
with which one should be able to send the planID planB to switch to it. You can also send effective_time field to specify when the change is effective. After calling this API, Paypal reply with 6 links, and I use the first (approve) to redirect the customer to Paypal domain to confirm it's will to switch the plan. After the user login, confirm and click "Accept and subscribe" to the new plan, the page always give me the following error: Things don't appear to be working at the moment. Please try again later.
, despite the plan change goes fine (I can verify it through dashboard).
I'm wondering what can I do to avoid that error.
I want to clarify that in the settings, through the dashboard, under Account settings -> Website payments -> Website preferences, I temporarily have the option Block non-encrypted website payment to Off.
Thank you all in advance!
The setting "Block non-encrypted website payment" is not relevant to this issue, and will have no effect. It applies exclusively to legacy HTML-only payments, which you should not concern yourself with.
Edit: ah yes, a redirect integration requires an application_context with a return_url. For usage with the SDK, no redirect_url is used, hence why the field is not required by the API.
Previous answer follows:
The issue you describe seems to be a problem with the PayPal site, and possibly only occurs in sandbox mode or with certain browsers/cookies. You can test as desired and contact PayPal's support if needed.
It is also possible to do a revise with the JS SDK rather than a redirect. For a client-side-only integration (no API), this can be done using actions.subscription.revise. Search for that text within the SDK reference.
To combine the JS SDK with the API call you are using, have your button code fetch the revised subscription ID from your server. Here is a sample for a create, which you can adapt to be a revise as it's essentially the same thing (you'd just likely be using a /revise endpoint /path/on/your/server)
<script src="https://www.paypal.com/sdk/js?client-id=..........&vault=true&intent=subscription"></script>
<div id="paypal-button-container"></div>
<script>
paypal.Buttons({
style: {
label:'subscribe' //Optional text in button
},
createSubscription: function(data, actions) {
return fetch('/path/on/your/server/paypal/subscription/create/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(serverData) {
console.log(serverData);
return serverData.id;
});
},
onApprove: function(data, actions) {
/* Optional: At this point, notify your server of the activated subscription...
fetch('/path/on/your/server/paypal/subscription/activated/' + data.subscriptionID , {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(serverData) {
//
});
*/
//You could additionally subscribe to a webhook for the BILLING.SUBSCRIPTION.ACTIVATED event (just in case), as well as other future subscription events
//Ref: https://developer.paypal.com/docs/api-basics/notifications/webhooks/event-names/#subscriptions
// Show a message to the buyer, or redirect to a success page
alert('You successfully subscribed! ' + data.subscriptionID);
}
}).render('#paypal-button-container');
</script>

Braintree: test nonces are resulting in Payment Method Nonce is Invalid

I am in the process of using the sandbox to test creating a new recurring billing subscription using a fake nonce but I keep getting an error indicating the
payment nonce is invalid, here is the object I am sending to the gateway.subscription.create method:
{
paymentMethodNonce: 'fake-valid-nonce',
planId: 'ip19',
price: 2.5,
options: { startImmediately: true }
}
This is the error I am receiving when I make me call to gateway.subscription.create:
[
ValidationError {
attribute: 'payment_method_nonce',
code: '91925',
message: 'Payment method nonce is invalid.'
}
]
I am using the fake nonces listed in this article, https://developer.paypal.com/braintree/docs/reference/general/testing/node#nonce-fake-valid-nonce
I am passing the sandbox credentials when I make my initial connection but it seems like it is not honoring the fake nonce.
None of them have ever worked? They should work at least once. Otherwise, if you have a payment method in your vault, do something like braintree.PaymentMethodNonce.create('token').payment_method_nonce.nonce to generate a new nonce for server-side testing.
Payment method nonces can only be used in certain specific conditions. Fake nonces do not support these specific use cases. You need to use a payment method token to create a subscription or use a generated payment method nonce from the specific client workflows mentioned in the API reference.

Automatically assign a customer to a specific customer group on sign-up - Bigcommerce

I've been told by BC support that this isn't possible, but I would be surprised if there really wasn't a way.
I need to be able to automatically assign a customer to a specific customer group when they create an account. My thought:
I would add an extra field to the sign-up form
Provide a user with a code (a string or number)
User enters code when creating new account
User hits submit
On form submit I would grab the value of the extra field:
var codeInput = document.getElementById('code-input').value;
I would then compare that value to a pre-defined string, and if there is a match, I would assign that customer to groupX (with a group id of 8):
if ( codeInput === "codeIGaveToTheUser" ) {
currentUserGroupID = 8;
}
Is it possible to assign a customer to a specific group on sign-up like this (or any other way)?
Any help is much appreciated.
Although using BigCommerce webhooks would ensure the highest success rate of executing your customer group assignment app, it requires quite a bit of setup on BigCommerce (creating a draft app, getting an oAuth key, jumping jacks, etc), and may be a bit of overkill for your requirements.
Here's an easier way, in my {mostly} humble opinion, that takes advantage of much of what you included in your original question. Any solution though will nonetheless require an external server to handle the customer group assignment through the BigCommerce API.
Within the BigCommerce control panel, add in the extra field to the user sign up form like you mentioned.
So as you can see, this new input field has been added natively to the default registration page:
So now, when a user creates an account on your site, the value for the Signup Code (the custom field created) will be directly accessible through the API for that customer's account. Take a look at what that JSON data looks like:
Okay, so this is nice and all, but how do we automate it?
To do so, we will have to let our external application know that a customer just registered. Furthermore, our external application will need some sort of reference to this newly created customer, so that it knows which customer to update the customer group for. Normally a BigCommerce webhook would notify us of all this, but since we aren't using a BigCommerce webhook, here's the alternative method to triggering the external script.
We will trigger our external application via the BigCommerce Registration Confirmation page - createaccount_thanks.html. This page is loaded immediately after a customer creates an account, so it is the perfect place to insert our trigger script.
Additionally, now that the customer is logged in, we can access the customer's email address via a BigCommerce Global system variable -%%GLOBAL_CurrentCustomerEmail%%.
We should make an HTTP request from this page to our external application along with the customer's email address. Specifically, we can make an XMLHttpRequest via JavaScript, or to be modern, we'll use Ajax via jQuery. This script should be inserted before the closing </body> tag on createaccount_thanks.html.
Example of POST request (although a GET would suffice as well):
<script>
$(function() {
$('.TitleHeading').text('One moment, we are finalizing your account. Please wait.').next().hide(); // Let the customer know they should wait a second before leaving this page.
//** Configure and Execute the HTTP POST Request! **//
$.ajax({
url: 'the_url_to_your_script.com/script.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({email:"%%GLOBAL_CurrentCustomerEmail%%"}),
success: function() {
// If the customer group assignment goes well, display page and proceed normally. This callback is only called if your script returns a 200 status code.
$('.TitleHeading').text('%%LNG_CreateAccountThanks%%').next().show();
},
error: function() {
// If the customer group assignment failed, you might want to tell your customer to contact you. This callback is called if your script returns any status except 200.
$('.TitleHeading').text('There was a problem creating your account').after('Please contact us at +1-123-456-7890 so that we can look into the matter. Please feel free to continue shopping in the meantime.');
}
});
});
</script>
Now finally, you just need to create your serverside application responsible for handling the request above, and updating the customer's customer group. You can use any language that you desire, and BigCommerce even offers several SDK's you can use to save mega development time. Just remember that you need to host it somewhere online, and then insert its URL to the JS script above.
PHP Example (quick & dirty):
git clone https://github.com/bigcommerce/bigcommerce-api-php.git
curl -sS https://getcomposer.org/installer | php && php composer.phar install
<?php
/**
* StackOverflow/BigCommerce :: Set Customer Group Example
* http://stackoverflow.com/questions/37201106/
*
* Automatically assigning a customer group.
*/
//--------------MAIN------------------------//
// Load Dependencies:
require ('bigcommerce-api-php/vendor/autoload.php');
use Bigcommerce\Api\Client as bc;
// Define BigCommerce API Credentials:
define('BC_PATH', 'https://store-abc123.mybigcommerce.com');
define('BC_USER', 'user');
define('BC_PASS', 'token');
// Load & Parse the Email From the Request Body;
$email = json_decode(file_get_contents('php://input'))->email;
// Execute Script if API Connection Good & Email Set:
if ($email && setConnection()) {
$customer = bc::getCollection('/customers?email=' .$email)[0]; //Load customer by email
$cgid = determineCustomerGroup($customer->form_fields[0]->value); //Determine the relevant customer group ID, via your own set string comparisons.
bc::updateCustomer($customer->id, array('customer_group_id' => $cgid)) ? http_send_status(200) : http_send_status(500); //Update the customer group.
} else {
http_send_status(500);
exit;
}
//-------------------------------------------------//
/**
* Sets & tests the API connection.
* #return bool true if the connection successful.
*/
function setConnection() {
try {
bc::configure(array(
'store_url' => BC_PATH,
'username' => BC_USER,
'api_key' => BC_PASS
));
} catch (Exception $e) {
return false;
}
return bc::getResource('/time') ? true : false; //Test Connection
}
/**
* Hard define the customer group & signup code associations here.
* #param string The code user used at signup.
* #return int The associated customergroup ID.
*/
function determineCustomerGroup($signupCode) {
switch ($signupCode) {
case 'test123':
return 1;
case 'codeIGaveToTheUser':
return 8;
default:
return 0;
}
}
So then you would do your customer group string comparisons directly in the serverside program. I'd recommend you rewrite your own BC API script as the one above in quality is really something along the lines of functional pseudo-code, but more so present to show the general idea. HTH
You would need to set up a server to listen for webhooks unless you wanted to do a cron job. We have some basic information on the developer portal, but I included more resources below. From there, you'd need to choose your server language of choice to listen for the webhooks once they been created, respond correctly (200 response if received), execute code based on this information, and then take action against the BC API.
So if you were looking for a code, you'd need to listen for the store/customer/created webhook, and have your code look for a custom field that contained the code. If it was present, then take action. Else, do nothing.
https://developer.github.com/webhooks/configuring/
http://coconut.co/how-to-create-webhooks
How do I receive Github Webhooks in Python

Stripe Connect Charge - Must authenticate as a connected account to be able to use customer parameter

I am trying to setup Stripe Connect and need to
charge the buyer by creating a customer first,
then generate a token and finally
charge the customer with this token.
This works fine as long as the buyer and seller are not the owners of the Stripe Connect Platform.
I.e. let's assume the following email corresponds to the account holder:
admin#admin.com
Now, we have two sellers:
seller_1#sellers.com
admin#admin.com
And we have one buyer:
buyer_1#buyers.com
My code works when buyer_1 buys from seller_1. All goes fine and an application fee is charged.
The problem however arises when buyer_1 wants to buy from admin#admin.com.
Eventhough admin#admin.com is connected to the account platform (I go through the same process as for seller_1), I keep getting the error:
message: "Must authenticate as a connected account to be able to use customer parameter. See https://stripe.com/docs/api#create_card_token for more details."
param: "customer"
raw: Object
rawType: "invalid_request_error"
requestId: "req_8EtIue0F4JWFmQ"
stack: 400
type: "StripeInvalidRequestError"
I use the following tutorial to save a customer and charge customers:
// store
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("SECRETKEY");
// (Assuming you're using express - expressjs.com)
// Get the credit card details submitted by the form
var tokenID = request.body.stripeToken;
// Create a Customer
stripe.customers.create({
source: tokenID,
description: "Example customer"
}, function(err, customer) {
});
// Create token
// Create a Token from the existing customer on the platform's account
stripe.tokens.create(
{ customer: CUSTOMER_ID, card: CARD_ID },
{ stripe_account: CONNECTED_STRIPE_ACCOUNT_ID }, // id of the connected account
function(err, token) {
// callback
}
);
I know this question is not recent but I have come across this same problem several times in my development testing.
The problem was fixed when I did a db:reset or removed the user(customer account) and reauthorized.
It turned out I had duplicate connect accounts for the same user, for old plans and the api_key was old.
Since I was in development and testing, I also found it useful to clear the test data from Stripe, on the dashboard >business settings >data > Delete all test data
Hope that helps.
Same thing happened to me. It's somewhat deceiving because Stripe let's you connect your account directly to the same account in the Settings (where it says "test the OAuth flow"), like a single account is acting as both the platform and the connected account. However, when you attempt to actually create charges or customers on the connected account, you get the above error.
I had this problem when testing charges using Stripe Connect. It turned out that when I went through the process of connecting a test business to my app (via the Connect To Stripe test page they provide) I was also already logged into my app's Stripe account in another browser window. This ended up saving my app's account data in the place of the new "test business" which kept causing charges to fail with that error.
When I went through the same process logged out of Stripe, it worked fine and charges were processed normally.
The answer was to simply change the customer id as the customer and the card is as source.
You can find the complete source code of a working example Stripe Connect with Ionic here:
https://www.noodl.io/market/product/P201601151251248/stripe-connect-guide-with-complete-source-code-all-you-need-to-start-accepting-money-on-behalf-of-others

Categories