1.1.13 • Published 1 year ago

tamed-stripe-frontend v1.1.13

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

WHY?

This is the frontend library for the Tamed Stripe architecture. This library aims to provide the frontend functions that can be used to communicate with the tamed-stripe-backend. It supports easy to adopt methods for basic customer generation, connected account generation, subscription generation and payment functions.

SETUP

  1. Assure the database and backend applications are up and running.

  2. Install the library with peer dependencies

yarn add tamed-stripe-frontend react-native-webview@11.26.0 react-native-webview-with-web
  1. import the library
import tsf from 'tamed-stripe-frontend';
import { StripeActionPage } from 'tamed-stripe-frontend';

At this point you can use the library.

API

init

This function initializes the library with the backend url and routes.

If you are using the backend library, you can use the below exact same code.

Example

useEffect(() => {
	tsf.init({
		apiBackend: apiBackend,
		routes: {
			"generateCustomer": "/generate-customer",
			"generateSubscription": "/generate-subscription",
			"generateProduct": "/generate-product",
			"generateAccount": "/generate-account",
			"oneTimePayment": "/one-time-payment",
			"getOneTimePaymentStatus": "/get-one-time-payment-status",
			"getSubscriptionPaymentsByStripeCustomerId": "/test/get-subscription-payments-by-stripe-customer-id",
		},
		debugMode: true
	});
}, []);

StripeActionPage

Uses react-native-webview to show the Stripe action pages.

props

NameTypeDescription
urlstringThe url to be shown in the webview.
setUrlfunctionThe function to be called when the url changes. Using this function caller can be signalled to close the web view. For example by setting the url as '' and detecting zero length url from the caller.

Example

<StripeActionPage
	url={accountLinkUrl}
	setUrl={setAccountLinkUrl}
/>

For an example usage of closing webview, please refer to the example application.

generateCustomer

Generates a stripe customer and links the stripe customer and application customer using the backend generateCustomer

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
applicationCustomerIdstringThe application customer id.
descriptionstringThe description of the customer.
emailstringThe email of the customer.
metadataobjectThe metadata for the customer.
namestringThe name of the customer.
phonestringThe phone number of the customer.
addressobjectThe address of the customer.
publicDomainstringThe public domain of the application.
successRoutestringThe route to be called when the customer is successfully generated.
cancelRoutestringThe route to be called when the customer generation is cancelled.
address
NameTypeDescription
citystringCity of the customer.
countrystringCountry of the customer.
line1stringLine 1 of the address of the customer.
line2stringLine 2 of the address of the customer.
postal_codestringPostal code of the customer.
statestringState of the customer.

Returns

Returns a customer object and a checkout session. Use the checkout session to redirect the user to the checkout page to collect default payment method.

{
	result: 'OK',
	payload: {
		customer,
		checkoutSession
	},
}

Example

const [customerCheckoutSessionUrl, setCustomerCheckoutSessionUrl] = useState('');
...
const result = await tsf.generateCustomer({
	applicationCustomerId: applicationCustomerId,
	description: `Mobile App Test Customer`,
	email: email,
	metadata: { "test": "test" },
	name: `Mobile App Test Customer`,
	phone: `1234567890`,
	address: { "line1": "1234 Main St", "city": "San Francisco", "state": "CA", "postal_code": "94111" },
	publicDomain: apiBackend,
});
setCustomerCheckoutSessionUrl(result.payload.checkoutSession.url);

...
const screen = (customerCheckoutSessionUrl.length > 0)
		? <View style={{ height: '100%', width: '100%' }}>
			<StripeActionPage
				url={customerCheckoutSessionUrl}
				setUrl={setCustomerCheckoutSessionUrl}
			/>
		</View>
		: <> </>
...

getCustomer

Gets a stripe customer using the backend getCustomer

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
applicationCustomerIdstringThe application customer id.

Returns

Returns a customer object.

{
	result: 'OK',
	payload: {
		customer
	},
}

Example

const result = await tsf.getCustomer({
	applicationCustomerId: applicationCustomerId,
});

generateProduct

Generates a product to be used for subscription generation using the backend generateProduct

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
namestringThe name of the product.
descriptionstringThe description of the product.
currencystringThe currency of the product.
unitAmountDecimalstringThe unit amount of the product. In cents.
intervalstringThe interval of the product. This can be one of following values; 'day', 'week', 'month', 'year'.
taxBehaviorstringOptional. Tax behavior of the product. This can be one of following values; 'exclusive', 'inclusive', 'unspecified'.
taxCodestringOptional. Tax code of the product. Comes from the Stripe's Product Tax Categories.

Returns

Returns a product and a price object in the payload

{
	result: 'OK',
	payload: {
		product,
		price
	}
}

Example

const resultProduct = await tsf.generateProduct({
	name: subscriptionName,
	description: subscriptionName,
	currency: 'usd',
	unitAmountDecimal: `${subscriptionCharge}`,
	interval: 'month',
	taxBehavior: 'exclusive',
	taxCode: 'txcd_30060006' // Stripe tax code for hats. :-) 
});

generateSubscription

Generates a subscription using the backend generateSubscription.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
applicationCustomerIdstringThe application's customer id.
recurringPriceIdstringThe stripe price id of the recurring price. Comes from generateProduct.
descriptionstringThe description of the subscription.
automaticTaxobjectOptional. Automatic tax settings of the subscription. If to be used following object should be passed: { enabled: true }
unlinkIfSubscriptionFailsbooleanOptional. If set to true, the customer will be unlinked from the application if the subscription fails.

Returns

Returns a subscription object.

{
	result: 'OK',
	payload: subscription,
}

Example

// first generate a product
const resultProduct = await tsf.generateProduct({
	name: subscriptionName,
	description: subscriptionName,
	currency: 'usd',
	unitAmountDecimal: `${subscriptionCharge}`,
	interval: 'month',
	taxBehavior: 'exclusive',
	taxCode: 'txcd_30060006' // Stripe tax code for hats. :-)
});
// then generate a subscription using the product
const resultSubscription = await tsf.generateSubscription({
	applicationCustomerId: props.applicationCustomerId,
	recurringPriceId: resultProduct.payload.price.id,
	description: `${subscriptionName} Subscription`,
	automaticTax: { enabled: true },
	unlinkIfSubscriptionFails: true,
});

getSubscriptionPaymentsByStripeCustomerId

Gets the DB rows indicating all subscription payments history for a certain stripe customer id. For a particular product's subscription, the returned rows should be filtered by the stripe_product_id field at the application side.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
customerIdstringThe stripe customer id that the payments are to be retrieved for.

Returns

Returns the DB rows indicating all subscription payments history for a certain stripe customer id.

{
	result: 'OK',
	payload: rows,
}

Example

const payments = await tsf.exportedForTesting.getSubscriptionPaymentsByStripeCustomerId({
	customerId: customerId
});

generateAccount

Generates a connected account that is to be used as a payee, using the backend generateAccount. The returned account URL should be used to initiate the account creation process. Similarly, for a process started earlier but not concluded, same method can be called to continue the registration process on Stripe.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
applicationCustomerIdstringThe application customer id, used to link the application customer to the Stripe connected account.
emailstringThe email of the connected account.
publicDomainstringThe public domain of the application.
countrystringThe country of the connected account, defaults to 'US'.
refreshUrlRoutestringRoute for the refresh URL. Defaults to /generate-account-cancel-route for which the route can be handled by this library.
returnUrlRoutestringRoute for the return URL. Defaults to /generate-account-success-route for which the route can be handled by this library.

Returns

You should expect 3 different responses from this function.

  • If there is a successfully generated account for the given applicationCustomerId, then the response will be as below, and the payload.id can be used as Stripe side payee (connected_account) id.
{
	result: 'OK',
	payload: {
		id: result.rows[0].stripe_account_id,
		accountLinkURL: ''
	}
}
  • If previously account generation process started but the end user did not complete the process, then the response will be as below, and the payload.accountLinkURL can be used to redirect the end user to the Stripe's website to complete the account generation process. Use the accountLinkURL field to redirect the end user to the Stripe's website to complete the account generation process.
{
	result: 'OK',
	payload: {
		id: result.rows[0].stripe_account_id,
		accountLinkURL: accountLinkForW.url,
		urlRegenerated: true
	}
}
  • If there is no account for the given applicationCustomerId, then the response will be as below, and the payload.accountLinkURL can be used to redirect the end user to the Stripe's website to start the account generation process.
{
	result: 'OK',
	payload: {
		result: 'OK',
		payload: account,
	}
}

Example

const [accountLinkUrl, setAccountLinkUrl] = useState('');
...
const generateAccount = async () => {
	const now = new Date().getTime();
	const account = await tsf.generateAccount({
		applicationCustomerId,
		email,
		publicDomain: apiBackend,
		country: country.toUpperCase(),
	});
	setAccountLinkUrl(account.payload.accountLinkURL);
};
...
const screen = (accountLinkUrl.length > 0)
	? <View style={{ height: '100%', width: '100%' }}>
		<StripeActionPage
			url={accountLinkUrl}
			setUrl={setAccountLinkUrl}
		/>
	</View>
	: <> </>
...

getAccount

Gets the connected account that is to be used as a payee, using the backend getAccount.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
applicationCustomerIdstringThe application customer id, used to link the application customer to the Stripe connected account.

Returns

Returns the connected account that is to be used as a payee.

{
	result: 'OK',
	payload: account,
}

Example

const account = await tsf.getAccount({
	applicationCustomerId: applicationCustomerId,
});

oneTimePayment

Generates a checkout session that is to be used to charge a customer and optionally transfer a portion to a payee, using the backend oneTimePayment.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
applicationCustomerIdstringThe application customer id, used to link the application customer to the payment.
currencystringThe currency of the payment. Defaults to 'usd'
itemsArrayThe items to be charged.
payoutDataObjectThe payout data.
publicDomainPublic domain of the server, to use the return URLs.
automaticTaxObject(Optional) Automatic tax data for the payment. If sent, should be the object: { enabled: true }
newCustomerParamsObject(Optional) This is only for oneTimePayment scenarios where no persistent customer exists, like the subscription or saved payment method scenarios. If sent, a new customer will be generated with the given parameters if there is no existing customer with the applicationCustomerId parameter.
items

Array of objects, each object should have the following fields:

NameTypeDescription
namestringThe name of the item.
amountnumberThe amount of the item, in cents.
tax_codestringTax code of the item. Comes from the Stripe's Product Tax Categories.
payoutData
NameTypeDescription
payoutAccountIdstringStripe account id of the payee.
payoutAmountstringAmount to be paid to the payee, in cents.
newCustomerParams
KeyTypeValue
emailstringEmail of the customer.
descriptionstringDescription of the customer.
metadataObjectMetadata for the customer, you can embed andy data within this object, it is kept in Stripe servers also.
namestringName of the customer.
phonestringPhone number of the customer.
addressObjectAddress of the customer.

Returns

Returns the checkoutSession object created by Stripe. The url field of the returned payload can be used to redirect the end user to the Stripe's website to complete the payment process.

{
	result: 'OK',
	payload: checkoutSession,
}

Example

const [oneTimePaymentUrl, setOneTimePaymentUrl] = useState('');
const tax_code = 'txcd_30060006';
...
const oneTimePayment = async () => {
	const payoutData = {
		payoutAmount,
		payoutAccountId,
	}
	const items = [
		{ name: oneTimeChargeItem1, unitAmountDecimal: `${oneTimeCharge1}`, tax_code, },
		{ name: oneTimeChargeItem2, unitAmountDecimal: `${oneTimeCharge2}`, tax_code, },
	];
	const body = {
		applicationCustomerId,
		currency: 'usd',
		items,
		payoutData,
		publicDomain: apiBackend,
		automaticTax: { enabled: true },
	};

	const result = await tsf.oneTimePayment(body);
	// wait 10 seconds for the webhook to fire
	await new Promise(resolve => setTimeout(resolve, 10000));

	setOneTimePaymentUrl(result.payload.url);
};

...
const screen = (oneTimePaymentUrl.length > 0)
		? <View style={{ height: '100%', width: '100%' }}>
			<StripeActionPage
				url={oneTimePaymentUrl}
				setUrl={setOneTimePaymentUrl}
			/>
		</View>
		: <> </>
...

getOneTimePaymentStatus

Used to get the current status of a checkout session using the backend getOneTimePaymentStatus.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
checkoutSessionIdstringThe checkout session id.

Returns

The payload holds the database state of the requested payment.

{
	result: 'OK',
	payload: rows,
}

The payload.rows[0] is a database row in the following form:

 id |              application_customer_id               | stripe_customer_id |                        checkout_session_id                         |        update_time         | total_amount_decimal | currency | state |         invoice_id          |                                                                      hosted_invoice_url                                                                       | payout_amount |   payout_account_id   | payout_state 
----+----------------------------------------------------+--------------------+--------------------------------------------------------------------+----------------------------+----------------------+----------+-------+-----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------+-----------------------+--------------
  2 | Application Customer-1679582193973                 | cus_... | cs_xxxx... | 2023-03-24 14:34:57.000013 |               450000 | eur      | P     | in_... | https://invoice.stripe.com/i/acct_.../test_...?s=ap |        225000 | acct_... | W

Here the state = 'P' means the payment is completed. And you can ues the url in the hosted_invoice_url field to show the invoice to the customer.

Example

const result = await tsf.getOneTimePaymentStatus({checkoutSessionId});
console.log(`One Time Payment Status : ${JSON.stringify(result.payload.rows[0], null, 2)}`);

refundOneTimePayment

Used to refund a one time payment using the backend refundOneTimePayment.

NameTypeDescription
propsobjectThe props object.

props

NameTypeDescription
checkoutSessionIdstringThe checkout session id.

Returns

Returns the refund object created by Stripe.

{
	result: 'OK',
	payload: refund,
}

Example

const result = await tsf.refundOneTimePayment({checkoutSessionId});
console.log(`One Time Payment Refund : ${JSON.stringify(result.payload, null, 2)}`);

More Examples

The example application (made with react-native and Expo) can be found here. Also the jest test cases can be used as examples, which can be found here.

License

The license is MIT and full text here.

Used Modules

Please refer to the main github page for the list of used modules.

1.1.13

1 year ago

1.1.12

2 years ago

1.1.9

2 years ago

1.1.8

2 years ago

1.1.11

2 years ago

1.1.7

2 years ago

1.1.6

2 years ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.2

2 years ago

1.1.1

2 years ago

1.0.113

2 years ago

1.0.112

2 years ago

1.0.111

2 years ago

1.0.110

2 years ago

1.0.109

2 years ago

1.0.108

2 years ago

1.0.107

2 years ago

1.0.106

2 years ago

1.0.105

2 years ago

1.0.104

2 years ago

1.0.103

2 years ago

1.0.102

2 years ago

1.0.101

2 years ago

1.0.100

2 years ago

1.0.99

2 years ago

1.0.98

2 years ago

1.0.97

2 years ago

1.0.96

2 years ago

1.0.95

2 years ago

1.0.94

2 years ago

1.0.93

2 years ago

1.0.92

2 years ago

1.0.91

2 years ago

1.0.90

2 years ago

1.0.89

2 years ago

1.0.88

2 years ago

1.0.87

2 years ago

1.0.86

2 years ago

1.0.85

2 years ago

1.0.84

2 years ago

1.0.83

2 years ago

1.0.82

2 years ago

1.0.81

2 years ago

1.0.80

2 years ago

1.0.79

2 years ago

1.0.78

2 years ago

1.0.77

2 years ago

1.0.76

2 years ago

1.0.75

2 years ago

1.0.74

2 years ago

1.0.73

2 years ago

1.0.72

2 years ago

1.0.71

2 years ago

1.0.70

2 years ago

1.0.67

2 years ago

1.0.66

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago