How to use Braintree V Zero on IOS app? - ios

I am coding an IOS app with Payment feature.
I decided to use Braintree V Zero.
At the very beginning, I use their excellent DropIn UI feature, and everything works fine.
But when payment happen, the Drop In UI required end-user to input his credit card or Paypal information every time.
Does any expect know how to implement one automatic charge solution by BrainTree V zero?
Like Uber's charge solution.
I guess maybe need to mark the user's credit card information from app side or service side?
router.get('/token', function (req, res) {
console.log('Kevin in token be called %s', req.param('aCustomerId'));
var aCustomerId = req.param('aCustomerId');
console.log('Kevin %s', aCustomerId);
gateway.clientToken.generate({customerId: aCustomerId}, function (error, response) {
res.send(response.clientToken);
console.log(response.clientToken);
});
});
Thank you in advanced!

Full disclosure: I work for Braintree.
The Braintree drop-in will display previously used payment methods for a customer, if you pass the customer_id in when generating a client token on your server.
​
Here's an example of how to do it in Node:
gateway.clientToken.generate({
customerId: aCustomerId
}, function (err, response) {
var clientToken = response.clientToken
});
​
Once a payment method is used, it will be saved in the drop-in and the customer will not have to enter it again. Pass the token of the saved payment method when creating a transaction:
​
gateway.transaction.sale({
amount: "10.00",
paymentMethodToken: theToken,
options: {
submitForSettlement: true
}
}, function (err, result) {
});
If you have any further questions, please feel free to contact Braintree support.
3133e

Related

How to handle user creation with Firebase social auth and a Rails backend

I am building a react native application with a rails backend but I decided to go for Firebase for authentication only since it's quite a bit cheaper than Auth0 or Okta.
The setup went fine but I am having trouble figuring out where to call my own backend to create/update a user in the sign in process.
This is my current sign in function that is triggered when pressing the 'Sign in with Facebook' button:
async function handleAuthentication() {
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
if (result.isCancelled) {
return;
}
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return Alert.alert('Error', 'Something went wrong while authenticating with Facebook.');
}
const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
// This token doesnt seem to work
await upsertUser(facebookCredential.token);
await auth().signInWithCredential(facebookCredential);
}
What I get back from the auth.FacebookAuthProvider.credential(data.accessToken) is an object with a token but that doesn't seem to be useful.
When I call auth().signInWithCredential(facebookCredential); I do get back the user data that I need to create a user BUT that already triggers the authentication system and sets the user as signed while he/she isn't created in the backend yet.
So ideally, I would like to create the user before calling signInWithCredential.
Although I'm not sure how to do this or with what token?
I use a Rails backend where I can also decode the token if necessary.
Any help would be greatly appreciated!

Stripe SDK integration using swift and flutter

I am trying to integrate Apple Pay in iOS using flutter. I am using method channels to communicate with swift and get the payment process completed. I have followed the documentation which is in this link
However, I believe I have stuck in the very ending part which I don't understand how to continue the flow. Since I am using flutter UIs, I don't need iOS ViewControllers.
This is the code that I have tried so far in the AppDelegate.swift:
func handleApplePayButtonTapped(result: FlutterResult){
let merchantIdentifier = "my.apple.merchant.id"
let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier:merchantIdentifier, country:"US", currency:"USD")
paymentRequest.paymentSummaryItems = [
PKPaymentSummaryItem(label:"Fancy Hat", amount:50.00),
PKPaymentSummaryItem(label:"iHats, Inc", amount:50.00),
]
if Stripe.canSubmitPaymentRequest(paymentRequest){
//next steps ???
result(String("Can submit payment request"))
}else{
result(String("Can't submit payment request"))
}
}
I am calling this code in flutter UI using this code:
Future<void> _doPayment() async {
String returnMsg;
try {
final bool result = await platform.invokeMethod('checkIfDeviceSupportsApplePay');
if(result){
final String status = await platform.invokeMethod('handleApplePayButtonTapped');
print(status);
}
returnMsg = '$result';
} on PlatformException catch (e) {
returnMsg = "Failed: '${e.message}'.";
}
print(returnMsg);}
I already have a Stripe publishable key as well as a Heroku deployed backend. If you checked my swift code, you will see where I am stuck at the moment.
As I have understood the flow, what is remaining to be done is
send the card details to the backend and get a token
using the token, send the payment details to the Stripe server
I am very new to swift language and code samples will be greatly helpful for me to continue with.
Thank you.
It looks like you're following the Stripe Custom iOS Integration, using the native PKPaymentAuthorizationViewController.
You should read through the integration steps here: https://stripe.com/docs/mobile/ios/custom#apple-pay
Basically, your next steps would be
instantiate a PKPaymentAuthorizationViewController with the paymentRequest
Set yourself to its delegate
present the PKPaymentAuthorizationViewController
implement the relevant delegate methods to get back an Apple Pay token (PKToken)
convert PKToken to STPToken (a Stripe token)
All these steps and more are detailed in the link above.

Parse Server + Stripe Connect - iOS

How do you setup Parse Server with Stripe Connect? I'm having a miserable time...
I'm trying to integrate my Parse Server (hosted on Heroku) with Stripe Connect (this is different that standard Stripe, in it allows you (the app) to transfer payments to a third party while taking a 'processing fee' while ONLY USING Parse Server + Xcode (as this is all that I'm familiar with).
For example, Lyft charges the customer's credit card, takes a percentage of the ride, and the remaining balance is transferred to the driver. How do I do this in Stripe automatically?!
Stripe's documentation did not give me an explicit example and I struggled for hours... Well, I finally got it and wanted to share it with you. Hope you all find this useful:
Assumptions:
You have an account on Stripe
You've added Stripe to your Parse Server example here. If you don't understand, message me for details.
You've added Stripe SDK to your Xcode project
You've setup Cloud Code on your Parse Server (again message if confused)
OK, so we are going to charge a credit card, pay the third party, but keep a 'fee'. First you'll go to the Stripe.com dashboard (click the top right of the screen, to view all of the options). Then click CONNECT and fill out the info.
IMPORTANT: YOU DO NOT NEED TO FILL OUT THE FIELDS "REDIRECT URI".
OK so now we need to create a CONNECTED STRIPE ACCOUNT. We do this by cloud code:
Parse.Cloud.define("createConnectedAccount", function(request, response) {
var stripe = require('stripe')('YOUR_SECRET_KEY');
stripe.accounts.create({
managed: false,
country: 'US',
email: 'example#gmail.com' //THIS IS YOUR THIRD PARTY ACCOUNT EMAIL ADDRESS
}, function(err, account) {
// asynchronously called
if (err) {
//other errror
response.error(err); // return error
} else {
//no error
response.success(account); // return charge success
}
});
});
This account is managed by the THIRD PARTY. When you run this code, it will create a Stripe account for this third party and send them an email (to the email listed). Basically, the email instructs them to Login, enter a password, and enter a bank account. When they activate the account, it will be 'connected' to your account.
Once connected, now it's time to write the "charge the card" method:
Parse.Cloud.define("charge", function(request, response) {
var stripe = require('stripe')('YOUR_SECRET_KEY');
stripe.charges.create({
amount: 100, //in CENTS
currency: "usd",
customer: request.params.customer, //customer is the id given by stripe when you create a customer. example: cus_EXAMPLE398FMFJKEP876
description: "example for people",
application_fee: 25, //again, in CENTS
}, {stripe_account: "3RD_PARTY_ACCOUNT_NUMBER"}, function(err, charge) { //the third party account number looks something like this acct_EXAMPLE352JFLE3207ME and can be found by clicking "Connected Accounts" (left side pane option after you set it up).
// asynchronously called
if (err && err.type === 'StripeCardError') {
// The card has been declined
response.error(err); // card declineded
} else if (err) {
//other errror
response.error(err); // return error
} else {
//no error
response.success(charge); // return charge success
}
});
});
Lastly, a quick picture of the "connected accounts" option on the left navigation pane:
Walah. You are done.
Hope this helps. Let me know if you have any questions.

Braintree client-token validation error

I am using braintree Drop-in UI with angularjs(frontend) and rails(Backend). I am creating a clientToken and sending it to braintree setup.
The client-token method,
#client_token = Braintree::ClientToken.generate(customer_id: current_user.braintree_customer_id,options: {
verify_card: true,
fail_on_duplicate_payment_method: true
})
So as you can see, I have taken 'fail_on_duplicate_payment_method' option. And trying to add the same payment method again.
Then, with that validation I am getting an error on the dropin saying "There was an error processing your request", but it is not coming to the error callback.
This is the setup, which is fine,
braintree.setup(vm.clientToken, 'dropin', {
container: 'dropin-container',
onPaymentMethodReceived: function(data)
{
alert('came recieved')
// console.log($scope.paymentForm)
vm.submit($scope.paymentForm, data.nonce)
},
onReady: function () {
vm.disablePay = false;
},
onError: function(type, message) {
alert('came error')
vm.serverError = message;
}
});
Here is the Image of the error,
The error in the network is,
callback_jsona7f3c885267b4f49aa13fbf01cecdb60({"error":{"message":"Credit card is invalid"},<br>"fieldErrors":[{"field":"creditCard","fieldErrors":[{"field":"number","code":"81724","message":"Duplicate card exists in the vault"}]}],"status":422})
I want to fetch this error into my view. I searched many links, but didn't get the answer I needed. Any help is appreciable.
Thankyou in Advance.
Full Disclosure: I work as a developer for Braintree
The onError callback is only triggered by client side errors and this is actually a server side error; however, the team is aware of this need and is working on a solution that will be available in a future release.

Check if user has valid auto-renewable subscription with Parse iOS SDK

I'm trying to implement an application with auto-renewable subscription. Users should pay to access all functions of my application. I already use Parse as backend for my application. It provides some API methods for inAppPurchases but there is nothing said about auto-renewable type. The only thing I have found is some two years old threads in the blog it is said that receipt verification was implemented only for downloadable purchases.
I have tried to use as it called in docs "Simple purchase" and it works fine but I can't figure out how can I check if my user already bought subscription or not.
Does anybody know is there way to do it via Parse API or This should implemented in another way?
As mentioned, receipt validation is only built into the Parse SDK for downloadable content, but it is fairly simple to to create a Cloud Code function that POSTs the app receipt to the iTunes Store for validation. Here are the Apple docs for server side validation: Validating Receipts with the App Store
Here is a what a basic function would look like:
Parse.Cloud.define('validateReceipt', function (request, response) {
var receiptAsBase64EncodedString = request.params.receiptData;
var postData = {
method: 'POST',
url: 'http://buy.itunes.apple.com/verifyReceipt',
body: { 'receipt-data': receiptAsBase64EncodedString,
'password': SHARED_SECRET }
}
Parse.Cloud.httpRequest(postData).then(function (httpResponse) {
// httpResponse is a Parse.Cloud.HTTPResponse
var json = httpResponse.data; // Response body as a JavaScript object.
var validationStatus = json.status; // App Store validation status code
var receiptJSON = json.receipt; // Receipt data as a JSON object
// TODO: You'll need to check the IAP receipts to retrieve the
// expiration date of the auto-renewing subscription, and
// determine if it is expired yet.
var subscriptionIsActive = true;
if (subscriptionIsActive) {
return response.success('Subscription Active');
}
else {
return response.error('Subscription Expired');
}
});
});
See Receipt Fields for details on interpreting the receipt JSON. It's fairly straight forward for iOS 7+, but auto-renewing subscription receipts for iOS 6 and earlier are tedious.

Resources