diff --git a/types/stripejs/customer.d.ts b/types/stripejs/customer.d.ts new file mode 100644 index 0000000000..fcde40a32a --- /dev/null +++ b/types/stripejs/customer.d.ts @@ -0,0 +1,299 @@ +export interface Customer { + /** + * The Address of the customer + */ + address: Address; + + /** + * The email address of the customer + */ + email: string; + + /** + * The full name of the owner + */ + name: string; + + /** + * The phone number of the customer + * NOTE: This includes the extension + */ + phone: string; + + /** + * Verified customer’s address + */ + readonly verified_address: Address; + + /** + * Verified customer’s email address + */ + readonly verified_email: string; + + /** + * Verified customer’s full name + */ + readonly verified_name: string; + + /** + * Verified customer’s phone number + */ + readonly verified_phone: string; +} + +// --- CUSTOMER ADDRESS --- // +export interface Address { + /** + * City/District/Suburb/Town/Village. + */ + city: string; + + /** + * Two-letter country code, capitalized + * NOTE: The codes are specified by the ISO3166 alpha-2 + */ + country: string; + + /** + * Address line 1 (Street address/PO Box/Company name). + */ + line1: string; + + /** + * Address line 2 (Apartment/Suite/Unit/Building). + */ + line2: string; + + /** + * ZIP or postal code + */ + postal_code: string; + + /** + * State/County/Province/Region. + */ + state: string; +} + +// --- CARD PAYMENT OPTION --- // +/** + * @see https://stripe.com/docs/api#card_object + */ +export interface Card { + /** + * The unique identifier of the bank account + */ + id: string; + + /** + * The account this card belongs to. + * NOTE: This attribute will not be in the card object if the card belongs to a customer or recipient instead. + */ + object: 'card'; + + account?: string; + + /** + * City/District/Suburb/Town/Village + */ + address_city: string; + + /** + * The country in which the address is located + */ + address_country: string; + + /** + * Address line 1 (Street address/PO Box/Company name) + */ + address_line1: string; + + /** + * The results of address_line1 if it was provided + */ + address_line1_check: checkStatus; + + /** + * Address line 2 (Apartment/Suite/Unit/Building) + */ + address_line2: string; + + /** + * State/County/Province/Region. + */ + address_state: string; + + /** + * ZIP or postal code + */ + address_zip: string; + + /** + * The results of address_zip if it was provided + */ + address_zip_check: checkStatus; + + /** + * A set of available payout methods for this card + * NOTE: Only values from this set should be passed as the method when creating a transfer + */ + available_payout_methods: ['standard'] | ['standard', 'instant']; + + /** + * The brand of the card + */ + brand: 'American Express' | 'Diners Club' | 'Discover' | 'JCB' | 'MasterCard' | 'UnionPay' | 'Visa' | 'Unknown'; + + /** + * Two-letter ISO code representing the country of the card + * You could use this attribute to get a sense of the international breakdown of cards you’ve collected + */ + country: string; + + /** + * Three-letter ISO code for currency + * Only applicable on accounts (not customers or recipients). + * The card can be used as a transfer destination for funds in this currency + */ + currency?: string; + + /** + * The customer that this card belongs to + * NOTE: This attribute will not be in the card object if the card belongs to an account or recipient instead + */ + customer?: any; + + /** + * If a CVC was provided, results of the check + */ + cvc_check: checkStatus; + + /** + * Only applicable on accounts (not customers or recipients) + * This indicates whether this card is the default external account for its currency + */ + default_for_currency?: boolean; + + /** + * The last four digits of the device account number. + * NOTE: For tokenized numbers only + */ + dynamic_last4: string; + + /** + * Two-digit number representing the card’s expiration month + */ + exp_month: number; + + /** + * Four-digit number representing the card’s expiration year + */ + exp_year: number; + + /** + * Uniquely identifies this particular card number + */ + fingerprint: string; + + /** + * Card funding type + */ + funding: 'credit' | 'debit' | 'prepaid' | 'unknown'; + + /** + * The last four digits of the card + */ + last4: string; + + /** + * The name of the cardholder + */ + name: string; + + /** + * The recipient that this card belongs to. + * NOTE: This attribute will not be in the card object if the card belongs to a customer or account instead + */ + recipient?: string; + + /** + * If the card number is tokenized, this is the method that was used + */ + tokenization_method: 'apple_pay' | 'android_pay'; + + /** + * Your own saved information with this card + */ + metadata: { [key: string]: string }; +} + +export type checkStatus = 'pass' | 'fail' | 'unavailable' | 'unchecked'; + +// --- BANK ACCOUNT PAYMENT OPTION --- // +/** + * @see https://stripe.com/docs/api#customer_bank_account_object + */ +export interface BankAccount { + /** + * The unique identifier of the bank account + */ + id: string; + + object: 'bank_account'; + + /** + * The name of the person or business that owns the bank account. + */ + account_holder_name: string; + + /** + * The type of entity that holds the account. + */ + account_holder_type: 'individual' | 'company'; + + /** + * Name of the bank associated with the routing number + * @example 'STRIPE TEST BANK' + */ + bank_name: string; + + /** + * The routing transit number for the bank account + */ + routing_number: string; + + /** + * Two-letter ISO code representing the country the bank account is located in + * @example 'US' + */ + country: string; + /** + * Three-letter ISO code for the currency paid out to the bank account + * @example 'usd' + */ + currency: string; + + customer: string; + + /** + * Uniquely identifies this particular bank account. + * NOTE: You can use this attribute to check whether two bank accounts are the same + */ + fingerprint: string; + + /** + * The last 4 digits of the bank number + */ + last4: string; + + /** + * Your own saved information with this bank account + */ + metadata: { [key: string]: string }; + + /** + * The status of the bank account + * @see https://stripe.com/docs/api#customer_bank_account_object-status + */ + status: 'new' | 'validated' | 'verified' | 'verification_failed' | 'errored'; +} diff --git a/types/stripejs/element.d.ts b/types/stripejs/element.d.ts new file mode 100644 index 0000000000..82317b9adf --- /dev/null +++ b/types/stripejs/element.d.ts @@ -0,0 +1,414 @@ +import { StripeError } from "./index"; + +export interface ElementFactory { + /** + * Creates a new StripeJS element + * @see https://stripe.com/docs/stripe-js/reference#elements-create + * @param type - The type of element that should be created + * @param options - Any options that should be used to con + * + * @example ``` + * const style = { + * base: { + * color: '#303238', + * fontSize: '16px', + * color: "#32325d", + * fontSmoothing: 'antialiased', + * '::placeholder': { + * color: '#ccc', + * }, + * }, + * invalid: { + * color: '#e5424d', + * ':focus': { + * color: '#303238', + * }, + * }, + * }; + * const cardElement = elementCreator.create('card', {style: style}) + * ``` + * + * @return The created element + */ + create( + type: ElementType, + options: CardElementOptions | IBANElementOptions | IdealBankOptions | PaymentButtonOptions + ): Element; +} + +export interface ElementCreatorOptions { + /** + * Fonts that should be used for styling the element + * @see https://stripe.com/docs/stripe-js/reference#stripe-elements + */ + fonts?: FontCSSElement[] | FontConfigElement[]; + + /** + * The translation that should be used for the element text + * `auto` defaults to the browser language + * + * NOTE: Only use the `string` option in combination with + * @see isLanguageTag + * + * @default 'auto' + */ + locale?: 'auto' | 'da' | 'de' | 'en' | 'es' | 'fi' | 'fr' | 'it' | 'ja' | 'no' | 'nl' | 'sv' | 'zh' | string; + + /** + * Whether or not the locale is written in a language code + * This can be used in combination with localization libraries so that language names won't have to be formatted + * @example `en-US` + * + * @since 0.1.0 + */ + isIETFLocaleTag?: boolean; +} + +export interface FontCSSElement { + /** + * A relative or absolute URL pointing to a CSS file with `@font-face` definitions + * @example 'https://fonts.googleapis.com/css?family=Open+Sans' + */ + cssSrc: string; +} + +export interface FontConfigElement { + /** + * The name of the font family + * @example 'Times New Roman' + */ + family?: string; + + /** + * A src value pointing to your custom font file. + * @example + * 'url(https://somewebsite.com/path/to/font.woff)' + * 'url(path/to/font.woff)' + */ + src?: string; + + /** + * The style of the text + * @default 'normal' + */ + style?: 'normal' | 'italic' | 'oblique'; + + /** + * A unicode range for the font that should be used + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range + */ + unicodeRange?: string; + + /** + * The weight of the font + * NOTE: This cannot be a number! + */ + weight?: 'initial' | 'inherit' | 'bold' | 'bolder' | 'lighter' | 'normal' | 'revert' | 'unset'; +} + +// --- ELEMENT --- // +export interface Element { + /** + * Mount the element to the DOM + * @see https://stripe.com/docs/stripe-js/reference#element-mount + * + * @param element - A HTML DOM element or a CSS selector + * + * @example ``` + * + *
+ * + * cardElement.mount('#card-element'); + * ``` + */ + mount(element: HTMLElement | string): void; + + /** + * Watch for changes on the element + * @see https://stripe.com/docs/stripe-js/reference#element-on + * + * @param event - What event to listen to + * @param handler - The handler function that is called when the event fires + */ + on(event: 'blur' | 'focus' | 'ready', handler: () => void): void; + on(event: 'click', handler: (event: { preventDefault: () => void }) => void): void; + on(event: 'change', handler: (event: OnChange) => void): void; + + /** + * Blur the element + * @see https://stripe.com/docs/stripe-js/reference#other-methods + */ + blur(): void; + + /** + * Clear the value of the element + */ + clear(): void; + + /** + * Removes the Element from the DOM and destroys it + * NOTE: a destroyed element can not be re-activated or re-mounted to the DOM + */ + destroy(): void; + + /** + * Give focus to the element + */ + focus(): void; + + /** + * Unmounts the Element from the DOM + * Call `element.mount()` to re-attach it to the DOM + * @see mount + */ + unmount(): void; + + /** + * Updates the options the Element was initialized with + * NOTE: Updates are merged into the existing configuration + * @param options - The options that should be used to update the element + */ + update(options: CardElementOptions | IBANElementOptions | IdealBankOptions | PaymentButtonOptions): void; +} + +/** + * The type of element that can be created by the ElementCreator + * @see ElementCreator + */ +export type ElementType = 'card' | 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'postalCode'; + +// --- ELEMENT EVENTS --- // +export interface OnChange { + /** + * true if the value is empty + */ + empty: boolean; + + /** + * true if the value is well-formed and potentially complete + */ + complete: boolean; + + /** + * The current validation error if any + */ + error: StripeError; + + /** + * The value of the element + * @see CardElementOptions.value for more information + * NOTE: This is only filled is the element is of a Card type + * + * ----- + * + * The selected bank. Can be one of the banks listed in the + * @see https://stripe.com/docs/sources/ideal#optional-specifying-the-customers-bank + * NOTE: This is also filled when the element is of IdealBank type + */ + value?: any; + + /** + * The type of card that was used + * @example 'visa' + * NOTE: This is only available when the element is of Card or Cardnumber type + */ + brand?: string; + + /** + * The country code of the entered IBAN + * NOTE: This is only available when the element is of IBAN type + */ + country?: string; + + /** + * The financial institution that services the account whose IBAN was entered into the Element. + * NOTE: This is only available when the element is of IBAN type + */ + bankName: string; +} + +// --- CARD ELEMENT --- // +export interface CardElementOptions extends BaseOptions { + /** + * A pre-filled value + * NOTE: Sensitive card information (card number, CVC, and expiration date) cannot be pre-filled + * @see placeholder + * + * @example {postalCode: '94110'} + */ + value?: any; + + /** + * Whether or not to hide the postal code + * NOTE: If you are already collecting a full billing address or postal code elsewhere, set this to `true` + * @default false + */ + hidePostalCode?: boolean; + + /** + * Appearance of the icon in the Element + */ + iconStyle?: 'solid' | 'default'; + + /** + * A placeholder text + * NOTE: This is only available for `cardNumber`, `cardExpiry` & `cardCvc` elements + */ + placeholder?: string; +} + +// --- IBAN ELEMENT --- // +export interface IBANElementOptions extends BaseOptions { + /** + * Specify the list of countries or country-groups whose IBANs you want to allow + */ + supportedCountries?: string[]; + + /** + * Customize the country and format of the placeholder IBAN + * @default 'DE" + */ + placeholderCountry?: string; + + /** + * Appearance of the icon in the Element + */ + iconStyle?: 'solid' | 'default'; +} + +// --- IDEAL ELEMENT --- // +export interface IdealBankOptions extends BaseOptions { + /** + * A pre-filled value for the Element. Can be one of the banks listed in the + * @see https://stripe.com/docs/sources/ideal#optional-specifying-the-customers-bank + * + * @example 'abn_amro' + */ + value?: string; +} + +// --- PAYMENT BUTTON ELEMENT --- // +export interface PaymentButtonOptions { + paymentRequest: any; + + /** + * Set custom class names on the container DOM element when the Stripe Element is in a + * particular state. + */ + classes?: { + base?: string; /** @default StripeElement */ + complete?: string; /** @default StripeElement--complete */ + focus: string; /** @default StripeElement--focus */ + invalid: string; /** @default StripeElement--invalid */ + }; + + style?: { + base?: PaymentRequestButtonStyle; + complete?: PaymentRequestButtonStyle; + empty?: PaymentRequestButtonStyle; + invalid?: PaymentRequestButtonStyle; + }; +} + +export interface PaymentRequestButtonStyle { + /** + * The type of button that should be shown + * @default 'default' + */ + type?: 'default' | 'donate' | 'buy'; + + /** + * The theme of the button that should be used + * @default 'dark' + */ + theme?: 'dark' | 'light' | 'light-outline'; + + /** + * The height of the button + * @example '25px' + */ + height?: string; +} + +// --- BASE OPTIONS FOR ELEMENTS --- // +/** + * @deprecated Do not use this interface. This is only here to minimize code duplication + */ +export interface BaseOptions { + /** + * Set custom class names on the container DOM element when the Stripe Element is in a + * particular state. + */ + classes?: { + base?: string; /** @default StripeElement */ + complete?: string; /** @default StripeElement--complete */ + empty?: string; /** @default StripeElement--empty */ + focus?: string; /** @default StripeElement--focus */ + invalid?: string; /** @default StripeElement--invalid */ + webkitAutofill?: string; /** @default StripeElement--webkit-autofill */ + }; + + /** + * Customize appearance using CSS properties + */ + style?: { + base?: StyleAttributes; + complete?: StyleAttributes; + empty?: StyleAttributes; + invalid?: StyleAttributes; + }; + + /** + * Whether or not the icon should be hidden + * @default false + */ + hideIcon?: boolean; + + /** + * Whether or not the input is disabled + * @default false + */ + disabled?: boolean; +} + +/** + * Styling settings for a Stripe Element + */ +export interface StyleAttributes { + color?: string; + fontFamily?: string; + fontSize?: string; + fontSmoothing?: string; + fontStyle?: string; + fontVariant?: any; + iconColor?: string; + lineHeight?: string; + letterSpacing?: string; + + /** + * Align text inside the element + * NOTE: Only available for the `cardNumber`, `cardExpiry`, and `cardCvc` Elements + */ + textAlign?: string; + '::-ms-clear'?: MSClearAttributes; + + /** + * Add padding to the element + * NOTE: Only available for the `idealBank` Element + */ + padding?: string; + + textDecoration?: string; + textShadow?: string; + textTransform?: string; + ':hover'?: StyleAttributes; + ':focus'?: StyleAttributes; + '::placeholder'?: StyleAttributes; + '::selection'?: StyleAttributes; + ':-webkit-autofill'?: StyleAttributes; + ':disabled'?: StyleAttributes; +} + +export interface MSClearAttributes extends StyleAttributes { + display?: string; +} diff --git a/types/stripejs/index.d.ts b/types/stripejs/index.d.ts new file mode 100644 index 0000000000..ed4f8686bf --- /dev/null +++ b/types/stripejs/index.d.ts @@ -0,0 +1,147 @@ +// Type definitions for stripe.js 3.0 +// Project: https://stripe.com/ +// Definitions by: Robin van Tienhoven +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { ElementCreatorOptions, ElementFactory } from './element'; +import { StripePaymentOptions, StripePaymentRequest } from './payment'; +import { BankTokenData, PiiTokenData, TokenData, IBANTokenData, TokenResult } from './token'; +import { SourceData, SourceResult } from './source'; + +export interface StripeJS { + /** + * The currently used key + */ + _apiKey: string; + + /** + * The mode in which the requests are currently done + * @example 'test' + */ + _keyMode: string; + + /** + * Initialization function for StripeJS + * @see https://stripe.com/docs/stripe-js/reference#including-stripejs + * + * @param key - The public key of the user + * @param [options] - Any options to configure StripeJS + * + * @return StripeJS instance + */ + (key: string, options?: StripeConfigOptions): StripeJS; + + /** + * Create an instance of elements which can be used to manage a group of StripeJS elements + * @see https://stripe.com/docs/stripe-js/reference#stripe-elements + * + * @param [options] - Configuration options for the elements object + * + * @return an instance of `Elements` to manage a group of elements + */ + elements(options?: ElementCreatorOptions): ElementFactory; + + /** + * Creates a new payment request based on the given options + * @see https://stripe.com/docs/stripe-js/reference#stripe-payment-request + * + * @param options - Options that should be used to configure the payment request + */ + paymentRequest(options: StripePaymentOptions): StripePaymentRequest; + + /** + * to convert information collected by Elements into a single-use token that you safely pass to your server + * to use in an API call + * @see https://stripe.com/docs/stripe-js/reference#stripe-create-token + * + * @param element - The element from which the data should be extracted + * @param [data] - an object containing additional payment information you might have collected + * + * @return an object containing the generated token or an error + */ + createToken(element: Element, data?: TokenData | IBANTokenData): Promise; + createToken(type: 'bank_account', data: BankTokenData): Promise; + createToken(type: 'pii', data: PiiTokenData): Promise; + + /** + * convert payment information collected by Elements into a Source object that you safely pass + * to your server to use in an API call + * @see https://stripe.com/docs/stripe-js/reference#stripe-create-source + * + * @param element - The element from which information should be extracted + * @param data - An object containing the type of Source you want to create and any additional payment source information + * NOTE: You cannot pass raw card information without an `Element`! + * + * @return an object containing the generated Source or an error + */ + createSource(element: Element, data: SourceData): Promise; + createSource(data: SourceData): Promise; + + /** + * Retrieve a Source using its unique ID and client secret + * NOTE: The parameters are always available in any source object fetched with StripeJS + * + * @param id - Unique identifier of the source + * @param client_secret - A secret available to the web client that created the Source + * + * @return an object containing the generated Source or an error + */ + retrieveSource({id, client_secret}: { id: string, client_secret: string }): Promise; +} + +export interface StripeConfigOptions { + stripeAccount: string; +} + +/** + * @see https://stripe.com/docs/api#errors + */ +export interface StripeError { + /** + * The type of error that has occurred + */ + type: errorType; + + /** + * For card errors, the ID of the failed charge + */ + charge?: string; + + /** + * For some errors that could be handled programmatically, + * a short string indicating the error code reported + */ + code?: string; + + /** + * For card errors resulting from a card issuer decline, + * a short string indicating the card issuer’s reason for the decline if they provide one + */ + decline_code?: string; + + /** + * A URL to more information about the error code reported + */ + doc_url?: string; + + /** + * A human-readable message providing more details about the error. + * NOTE: For card errors, these messages can be shown to your users + */ + message?: string; + + /** + * If the error is parameter-specific, the parameter related to the error + */ + param?: string; +} + +export type errorType = + 'api_connection_error' | + 'api_error' | + 'authentication_error' | + 'card_error' | + 'idempotency_error' | + 'invalid_request_error' | + 'rate_limit_error'; diff --git a/types/stripejs/payment.d.ts b/types/stripejs/payment.d.ts new file mode 100644 index 0000000000..bad5419ec1 --- /dev/null +++ b/types/stripejs/payment.d.ts @@ -0,0 +1,235 @@ +import { ShippingAddress, ShippingOption } from "./shipping"; + +/** + * The Payment request object that can be used to make payments + * @see https://stripe.com/docs/stripe-js/reference#the-payment-request-object + */ +export interface StripePaymentRequest { + /** + * Whether or not a payment can be made + * NOTE: When no API is available it resolves with `null` + * + * @see https://stripe.com/docs/stripe-js/reference#payment-request-can-make-payment + */ + canMakePayment(): Promise; + + /** + * Shows the browser’s payment UI + * NOTE: When using the paymentRequestButton Element, this is called for you under the hood + * NOTE: This method must be called as the result of a user interaction (for example, in a click handler) + * + * @see https://stripe.com/docs/stripe-js/reference#payment-request-show + */ + show(): void; + + /** + * Updates the payment information + * NOTE: can only be called when the browser payment UI is not showing + * + * @param options - Payment information that should be used by Stripe + * + * @see https://stripe.com/docs/stripe-js/reference#payment-request-update + */ + update(options: UpdateOptions): void; + + /** + * Register your event listener + * @see https://stripe.com/docs/stripe-js/reference#payment-request-on + */ + on(event: 'cancel', handler: () => void): void; + + on(event: 'token' | 'source', handler: (event: StripePaymentResponse) => void): void; + + on(event: 'shippingaddresschange', handler: (event: NewShippingAddress) => void): void; + + on(event: 'shippingoptionchange', handler: (event: NewShippingOptions) => void): void; +} + +export interface CanMakePaymentResult { + /** + * true if the browser payment API supports Apple Pay. + * NOTE: using the paymentRequestButton Element is automatically cross-browser. + * If you use this PaymentRequest object to create a paymentRequestButton Element, you don‘t need to check applePay yourself + */ + readonly applePay: boolean; +} + +/** + * @see https://stripe.com/docs/stripe-js/reference#payment-request-on + */ +export interface NewShippingAddress { + /** + * Calling this function with an UpdateDetails object merges your updates into the + * current PaymentRequest object. + */ + updateWith: (dataToUpdate: UpdateOptions) => void; + + /** + * The customer's selected ShippingAddress. + */ + shippingAddress: ShippingAddress; +} + +export interface NewShippingOptions { + /** + * Calling this function with an UpdateDetails object merges your updates into the + * current PaymentRequest object. + */ + updateWith: (dataToUpdate: UpdateOptions) => void; + + /** + * The selected shipping option + */ + shippingOption: ShippingOption; +} + +/** + * Payment options that can be set when updating the payment request + * @see https://stripe.com/docs/stripe-js/reference#payment-request-update + */ +export interface UpdateOptions { + /** + * The currency in which the customer should be charged + * @example 'usd' + */ + currency: string; + + /** + * The total amount the customer has to pay + * NOTE: This object is shown to the customer in the browser‘s payment UI + */ + total: PaymentItem; + + /** + * An array of payment item objects + * NOTE: The sum of the line item amounts does not need to add up to the total amount above + * @see total + * + * @default [] + */ + displayItems?: PaymentItem[]; + + /** + * An array of possible shipping options + * NOTE: This first one in the array will be listed as the default option + * + * @default [] + */ + shippingOptions?: ShippingOption[]; +} + +/** + * Configuration options for creating a payment request + * @see https://stripe.com/docs/stripe-js/reference#stripe-payment-request + */ +export interface StripePaymentOptions extends UpdateOptions { + /** + * The two letter code representing your country + * @example 'US' + */ + country: string; + + /** + * Whether or not the form should ask for the payer's name + * @default false + */ + requestPayerName?: boolean; + + /** + * Whether or not the form should ask for the payer's email address + * @default false + */ + requestPayerEmail?: boolean; + + /** + * Whether or not the form should ask for the payer's phone number + * @default false + */ + requestPayerPhone?: boolean; + + /** + * Whether or not a shipping address should be requested + * NOTE: Setting this to true requires `shippingOptions` to be set with at least one option! + * @see shippingOptions + */ + requestShipping?: boolean; +} + +export interface PaymentItem { + /** + * The amount the user has to pay in the given currency + * @see StripePaymentOptions.currency + */ + amount: number; + + /** + * A text that should be shown to the user + */ + label: string; + + /** + * Whether or not the payment should be executed immediately + * If you might change this amount later (for example, after you have calculated shipping costs), set this to `true` + */ + pending?: boolean; +} + +// --- PAYMENT RESPONSE FROM STRIPE --- // +/** + * @see https://stripe.com/docs/stripe-js/reference#payment-response-object + */ +export interface StripePaymentResponse { + /** + * NOTE: Only available when the event type 'token' was used + */ + readonly token?: any; + + /** + * NOTE: Only available when the event type 'source' was used + */ + readonly source?: any; + + /** + * A function to complete the payment and give feedback to the user + * Call this when you have processed the token data provided by the API + * + * @param status - The status that should be shown to the user + */ + complete: (status: completeStatus) => void; + + /** + * Information about the payer + * NOTE: This is only set if the corresponding field was set to `true` in the `PaymentOptions` + * + * @see PaymentOptions.requestPayerName + * @see PaymentOptions.requestPayerEmail + * @see PaymentOptions.requestPayerPhone + */ + readonly payerName?: string; + readonly payerEmail?: string; + readonly payerPhone?: string; + + /** + * The shipping address the payer selected + */ + readonly shippingAddress: ShippingAddress; + + /** + * The shipping option the payer selected + */ + readonly shippingOption: ShippingOption; + + /** + * The unique name of the payment handler the customer chose to authorize payment + * @example 'basic-card' + */ + readonly methodName: string; +} + +export type completeStatus = + 'success' | + 'fail' | + 'invalid_payer_name' | + 'invalid_payer_phone' | + 'invalid_payer_email' | + 'invalid_shipping_address'; diff --git a/types/stripejs/shipping.d.ts b/types/stripejs/shipping.d.ts new file mode 100644 index 0000000000..91d46963f8 --- /dev/null +++ b/types/stripejs/shipping.d.ts @@ -0,0 +1,90 @@ +/** + * @see https://stripe.com/docs/stripe-js/reference#shipping-address-object + */ +export interface ShippingAddress { + /** + * Two-letter country code, capitalized + * NOTE: The codes are specified by the ISO3166 alpha-2 + */ + country: string; + + /** + * An array of address line items + * @example ['185 Berry St.', 'Suite 500', 'P.O. Box 12345'] + */ + addressLine: string[]; + + /** + * The most coarse subdivision of a country + * NOTE: Depending on the country, this might correspond to a state, a province, an oblast, a prefecture, + * or something else along these lines. + */ + region: string; + + /** + * The name of a city, town, village, etc + */ + city: string; + + /** + * The postal code or ZIP code + * NOTE: This is known as the PIN code in India + */ + postalCode: string; + + /** + * The name of the recipient. + * NOTE: This might be a person, a business name, or contain “care of” (c/o) instructions + */ + recipient: string; + + /** + * The phone number of the recipient + * NOTE: This is only filled if `requestPayerPhone` was set to `true` + * + * @see PaymentOptions.requestPayerPhone + */ + phone: string; + + /** + * The sorting code as used in, for example, France + * NOTE: Not present on Apple platforms + */ + sortingCode: string; + + /** + * A logical subdivision of a city + * NOTE: Not present on Apple platforms + */ + dependentLocality: string; +} + +// --- SHIPPING OPTION --- // +/** + * Settings for a shipping location + * @see https://stripe.com/docs/stripe-js/reference#shipping-option-object + */ +export interface ShippingOption { + /** + * A unique ID you create to keep track of this shipping option. + * NOTE: You‘ll be told the ID of the selected option on changes and on completion. + */ + id: string; + + /** + * A short “title” for this shipping option. + */ + label: string; + + /** + * A longer description of this shipping option. + */ + detail: string; + + /** + * The shipping costs for this option + * NOTE: If the cost of this shipping option depends on the shipping address the customer enters, + * listen for the `shippingaddresschange` event. + */ + amount: number; +} diff --git a/types/stripejs/source.d.ts b/types/stripejs/source.d.ts new file mode 100644 index 0000000000..2a24eb7d5b --- /dev/null +++ b/types/stripejs/source.d.ts @@ -0,0 +1,316 @@ +import { StripeError } from "./index"; +import { Customer } from "./customer"; +import { Token } from "./token"; + +/** + * @see https://stripe.com/docs/api#sources + */ +export interface Source { + /** + * Unique identifier for the object + */ + id: string; + + object: 'source'; + + /** + * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, + * or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total + * amount associated with the source + */ + amount: number; + + /** + * The client secret of the source. + * Used for client-side retrieval using a publishable key. + */ + client_secret: string; + + /** + * Information related to the code verification flow + * Present if the source is authenticated by a verification code + */ + code_verification?: CodeVerification; + + /** + * Time at which the object was created. + * Measured in seconds since the Unix epoch. + * (Timestamp) + */ + created: number; + + /** + * Three-letter ISO code for the currency associated with the source + */ + currency: string; + + /** + * The authentication flow of the source + */ + flow: 'redirect' | 'receiver' | 'code_verification' | 'none'; + + /** + * LIVE MODE = true + * TEST MODE = false + */ + livemode: boolean; + + /** + * Your own saved information with this bank account + */ + metadata: { [key: string]: string }; + + /** + * Information about the owner of the payment instrument that may be used or + * required by particular source types. + */ + owner: Customer; + + /** + * Information related to the receiver flow. + * Present if the source is a receiver + */ + receiver?: Receiver; + + /** + * Information related to the redirect flow. + * Present if the source is authenticated by a redirect + */ + redirect?: Redirect; + + /** + * Extra information about a source + * NOTE: This will appear on your customer’s statement every time you charge the source + */ + statement_descriptor: string; + + /** + * The status of the source + * NOTE: Only `chargeable` sources can be used to create a charge + */ + status: 'pending' | 'canceled' | 'failed' | 'consumed' | 'chargeable'; + + /** + * The type of the source. + * NOTE: The type is a payment method + */ + type: paymentOptions; + + /** + * A matching name to the type with extra information about the payment method + * @see type + */ + [key: string]: any; + + /** + * Whether this source should be reusable or not + */ + usage: 'reusable' | 'reusable'; +} + +export type paymentOptions = + 'ach_credit_transfer' | + 'ach_debit' | + 'alipay' | + 'bancontact' | + 'card' | + 'card_present' | + 'eps' | + 'giropay' | + 'ideal' | + 'multibanco' | + 'p24' | + 'paper_check' | + 'sepa_credit_transfer' | + 'sepa_debit' | + 'sofort' | + 'three_d_secure'; + +// --- CODE VERIFICATION --- // +export interface CodeVerification { + /** + * The number of attempts remaining to authenticate the + * source object with a verification code + */ + attempts_remaining: number; + + /** + * The status of the code verification + */ + status: 'pending' | 'attempts_remaining' | 'succeeded' | 'failed' | 'attempts_remaining'; +} + +// --- REDIRECT INFORMATION --- // +export interface Redirect { + /** + * The failure reason for the redirect + * Present only if the redirect status is `'failed'` + */ + failure_reason?: 'user_abort' | 'declined' | 'processing_error'; + + /** + * The URL you provide to redirect the customer to after they authenticated their payment + */ + return_url: string; + + /** + * The status of the redirect + * - Pending: ready to be used by your customer to authenticate the transaction + * - succeeded: succesful authentication, cannot be reused + * - not_required: redirect should not be used + * - failed: failed authentication, cannot be reused + */ + status: 'pending' | 'succeeded' | 'not_required' | 'failed'; + + /** + * The URL provided to you to redirect a customer to as part of a redirect + * authentication flow + */ + url: string; +} + +// --- RECEIVER INFORMATION --- // +export interface Receiver { + /** + * The address of the receiver source + * NOTE: This is the value that should be communicated to the customer to send their funds to + */ + address: string; + + /** + * The total amount that was charged by you + * NOTE: The amount charged is expressed in the source’s currency + */ + amount_charged: number; + + /** + * The total amount received by the receiver source + */ + amount_received: number; + + /** + * The total amount that was returned to the customer + * NOTE: The amount charged is expressed in the source’s currency + */ + amount_returned: number; +} + +// --- DATA TO CREATE A SOURCE --- // +/** + * @see https://stripe.com/docs/api#create_source + */ +export interface SourceData { + /** + * The type of the source to create + */ + type: paymentOptions; + + /** + * This is the amount for which the source will be chargeable once ready + */ + amount: number; + + /** + * Three-letter ISO code for the currency associated with the source + */ + currency: string; + + /** + * The authentication flow of the source + */ + flow: 'redirect' | 'receiver' | 'code_verification' | 'none'; + + /** + * Whether this source should be reusable or not + */ + usage: 'reusable' | 'single_use'; + + /** + * Information about a mandate possiblity attached to a source object + * (generally for bank debits) as well as its acceptance status + */ + mandate?: Mandate; + + /** + * Extra data you want to add to the source object + */ + metadata?: { [key: string]: string }; + + /** + * Information about the owner of the payment instrument that may be used or + * required by particular source types. + */ + owner?: Customer; + + /** + * Can be set only if the source is a receiver + */ + receiver?: Receiver; + + /** + * Required if the source is authenticated by a redirect + */ + redirect?: Redirect; + + /** + * An arbitrary string to be displayed on your customer’s statement + * @example if your website is RunClub and the item you’re charging for is a race ticket, + * you may want to specify a statement_descriptor of RunClub 5K race ticket. + */ + statement_descriptor?: string; + + three_d_secure_2_eap?: any; + + /** + * When passed, token properties will override source parameters + */ + token?: Token; +} + +export interface Mandate { + acceptance?: Acceptance; + + /** + * The method Stripe should use to notify the customer + * - email: an email is sent directly to the customer + * - manual: a source.mandate_notification event is sent to your webhooks endpoint and you should handle the notification + * - none: the underlying debit network does not require any notification + */ + notification_method?: 'email' | 'manual' | 'none'; +} + +export interface Acceptance { + /** + * The unix timestamp the mandate was accepted or refused at by the customer. + */ + date: number; + + /** + * The unix timestamp the mandate was accepted or refused at by the customer. + */ + ip: string; + + /** + * The status of the mandate acceptance + */ + status: 'accepted' | 'refused'; + + /** + * The user agent of the browser from which the mandate was accepted or refused by the customer + * NOTE: This can be unset by updating the value to `null` and then saving + */ + user_agent: string; +} + +// --- RESPONSE FROM STRIPE WHEN CREATING OR FETCHING A SOURCE --- // +export interface SourceResult { + /** + * The identifier of the source to be retrieved + */ + source: Source; + + /** + * There was an error. This includes client-side validation errors. + */ + error?: StripeError; +} diff --git a/types/stripejs/stripejs-tests.ts b/types/stripejs/stripejs-tests.ts new file mode 100644 index 0000000000..7c705e6ec0 --- /dev/null +++ b/types/stripejs/stripejs-tests.ts @@ -0,0 +1,101 @@ +import { StripeJS } from "stripejs"; +import { CanMakePaymentResult, StripePaymentResponse } from "stripejs/payment"; +import { BankTokenData, IBANTokenData, TokenData, TokenResult } from "stripejs/token"; +import { SourceData, SourceResult } from "stripejs/source"; + +declare function describe(desc: string, fn: () => void): void; + +declare function it(desc: string, fn: () => void): void; + +describe('StripeJS', () => { + const stripe: StripeJS = {} as any; + + it('Should be able to initialize', () => { + stripe('test'); + stripe('test', {stripeAccount: 'test123'}); + }); + + it('Should be possible to get information from stripe', () => { + stripe._apiKey; + stripe._keyMode; + }); + + it('Should be possible to create and modify elements', () => { + const creator = stripe.elements(); + stripe.elements({fonts: [], locale: 'nl'}); + stripe.elements({fonts: [], locale: 'nl', isIETFLocaleTag: true}); + + const element = creator.create("cardCvc", {value: {postalCode: '94110'}}); + element.blur(); + element.focus(); + element.clear(); + element.on('focus', () => null); + element.on('click', (event: { preventDefault: () => void }) => event.preventDefault()); + element.mount('#card-element'); + element.mount(new HTMLElement()); + element.unmount(); + element.update({value: {postalCode: '123'}}); + element.destroy(); + }); + + it('Should be possible to create a payment request', () => { + const data = {country: 'NL', currency: 'eur', total: {amount: 100, label: 'hello world'}}; + const request = stripe.paymentRequest(data); + request.canMakePayment().then((result: CanMakePaymentResult | null) => null); + request.on('token', ((event: StripePaymentResponse) => { + const token: any = event.token ? event.token : null; + event.complete("fail"); + const name: string = event.payerName ? event.payerName : ''; + })); + request.show(); + request.update(data); + }); + + it('Should be possible to create a token', () => { + const element: Element = {} as any; + const data: TokenData = { + name: '', + currency: 'eur', + address_city: '', + address_country: 'NL', + address_line1: '', + address_line2: '', + address_state: '', + address_zip: '', + }; + stripe.createToken(element, data).then((result: TokenResult) => result.token); + + const iban: IBANTokenData = { + currency: 'eur', + account_holder_name: '', + account_holder_type: 'company', + }; + stripe.createToken(element, iban).then((result: TokenResult) => result.token); + + const bankData = { + country: 'NL', + account_number: '12345' + }; + const bank: BankTokenData = {...iban, ...bankData}; + stripe.createToken('bank_account', bank).then((result: TokenResult) => result.token); + + stripe.createToken('pii', {personal_id_number: ''}).then((result: TokenResult) => result.error); + }); + + it('Should be possible to create a source object', () => { + const element: Element = {} as any; + const data: SourceData = { + type: 'alipay', + flow: 'none', + amount: 1000, + currency: 'eur', + usage: 'single_use' + }; + stripe.createSource(element, data).then((result: SourceResult) => result.source); + stripe.createSource(data).then((result: SourceResult) => result.error); + }); + + it('Should be possible to fetch a source object', () => { + stripe.retrieveSource({id: '', client_secret: ''}).then((result: SourceResult) => result.source); + }); +}); diff --git a/types/stripejs/token.d.ts b/types/stripejs/token.d.ts new file mode 100644 index 0000000000..e3a3a51590 --- /dev/null +++ b/types/stripejs/token.d.ts @@ -0,0 +1,138 @@ +import { StripeError } from "./index"; +import { BankAccount, Card } from "./customer"; + +/** + * @see https://stripe.com/docs/api#token_object + */ +export interface Token { + /** + * The unique identifier for the token + */ + id: string; + + object: 'token'; + + /** + * Hash describing the bank account + */ + bank_account?: BankAccount; + + /** + * Hash describing the card used to make the charge + */ + card?: Card; + + /** + * IP address of the client that generated the token + */ + client_ip: string; + + /** + * Time at which the object was created. Measured in seconds since the Unix epoch + */ + created: string; + + /** + * LIVE MODE = `true` + * TEST MODE = `false` + */ + livemode: boolean; + + /** + * Type of the token + */ + type: 'account' | 'bank_account' | 'card' | 'pii'; + + /** + * Whether this token has already been used (tokens can be used only once) + */ + used: boolean; +} + +// --- DATA TO CREATE A TOKEN --- // +export interface TokenData { + /** + * The Cardholder name + */ + name: string; + + /** + * Fields for billing address information. + */ + address_line1: string; + address_line2: string; + address_city: string; + address_state: string; + address_zip: string; + + /** + * A two character country code identifying the country + * @example 'US' + */ + address_country: string; + + /** + * Used to add a card to an account + * NOTE: Currently, the only supported currency for debit card payouts is 'usd' + */ + currency?: string; +} + +// --- RESPONSE FROM STRIPE WHEN CREATING OR FETCHING A TOKEN --- // +export interface TokenResult { + /** + * The generated string that can be used for communication with the backend + */ + token?: Token; + + /** + * There was an error. This includes client-side validation errors. + */ + error?: StripeError; +} + +// --- DATA TO CREATE A PERSONAL TOKEN --- // +export interface PiiTokenData { + /** + * The personal ID number + */ + personal_id_number: string; +} + +// --- DATA TO CREATE A TOKEN BASED ON BANK INFORMATION --- // +export interface IBANTokenData { + /** + * Three-letter ISO code for the currency paid out to the bank account + * @example 'usd' + */ + currency: string; + + /** + * The name of the person or business that owns the bank account. + */ + account_holder_name: string; + + /** + * The type of entity that holds the account. + */ + account_holder_type: 'individual' | 'company'; +} + +export interface BankTokenData extends IBANTokenData { + /** + * The 2-digit country ISO code + * @example 'US' + */ + country: string; + + /** + * The bank account number + */ + account_number: string; + + /** + * The routing transit number for the bank account + * NOTE: This is optional if the {@link BankTokenData.currency} is 'eur' + */ + routing_number?: string; +} diff --git a/types/stripejs/tsconfig.json b/types/stripejs/tsconfig.json new file mode 100644 index 0000000000..8e844fa910 --- /dev/null +++ b/types/stripejs/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "customer.d.ts", + "element.d.ts", + "payment.d.ts", + "shipping.d.ts", + "source.d.ts", + "token.d.ts", + "stripejs-tests.ts" + ] +} + diff --git a/types/stripejs/tslint.json b/types/stripejs/tslint.json new file mode 100644 index 0000000000..1c2b5f91d1 --- /dev/null +++ b/types/stripejs/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // IBAN is written with an 'I' for example + "interface-name": false + } +}