Created
June 11, 2019 12:18
-
-
Save adamduren/fa26144e2a9706671988e7e88641d75e to your computer and use it in GitHub Desktop.
Create Token from JS with `cordova-plugin-applepay`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reverse Engineered from | |
// https://github.com/stripe/stripe-ios/blob/d4e3170fab9ab940816ea28ea8084b48a842e764/Stripe/STPAPIClient%2BApplePay.m#L22-L28 | |
class StripeToken { | |
// IPaymentResponse is the response from `makePayment()` | |
public async getTokenFromPaymentData(payment: IPaymentResponse) { | |
const payload: any = { | |
pk_token: atob(payment.paymentData), | |
...this.addressParamsFromPaymentData(payment), | |
}; | |
if (payment.paymentMethodDisplayName) { | |
payload.pk_token_instrument_name = payment.paymentMethodDisplayName; | |
} | |
if (payment.paymentMethodNetwork) { | |
payload.pk_token_payment_network = payment.paymentMethodNetwork; | |
} | |
if (payment.transactionIdentifier) { | |
payload.pk_token_transaction_id = payment.transactionIdentifier; | |
} | |
const response = await fetch('https://api.stripe.com/v1/tokens', { | |
method: 'POST', | |
headers: { | |
'Stripe-Version': '2015-10-12', | |
Authorization: `Bearer ${environment.stripePublishableKey}`, | |
}, | |
body: new URLSearchParams(payload), | |
}); | |
const data = await response.json(); | |
const token = data.id; | |
return token; | |
} | |
private addressParamsFromPaymentData(payment: IPaymentResponse) { | |
if (payment.billingNameFirst) { | |
const params: any = {}; | |
if (payment.billingNameFirst) { | |
params['card[name]'] = `${payment.billingNameFirst}${ | |
payment.billingNameLast ? ' ' + payment.billingNameLast : '' | |
}`; } | |
if (payment.billingAddressStreet) { | |
params['card[address_line1]'] = payment.billingAddressStreet; | |
params['card[address_city]'] = payment.billingAddressCity; | |
params['card[address_state]'] = payment.billingAddressState; | |
params['card[address_zip]'] = payment.billingPostalCode; | |
params['card[address_country]'] = payment.billingCountry; | |
} | |
return params; | |
} else { | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment