插件
Google Pay
@nativescript/google-pay
一个允许您在 Android 应用中提供 Google Pay 的插件。
内容
安装
cli
ns plugin add @nativescript/google-pay
先决条件
在开始之前,请查看以下先决条件
- 安装 Google Play 服务 18.1.2 或更高版本(大多数 Android 设备默认情况下都已安装)。
- 安装 Google Pay 应用并添加付款方式。
- 向 Google 添加付款方式.
- 遵守 Google Pay API 可接受使用政策 和 Google Play 开发者政策。
关于支付令牌的重要说明
如果您正在使用支付服务提供商,则需要在生产模式下为您的应用提供有效的支付令牌。您可以在 Google 文档中查看许多 提供商的配置。
在开发过程中,您可以在创建支付请求时使用以下示例进行网关令牌配置。
ts
parameters: {
gateway: 'example', // in production replace with your gateway provider
gatewayMerchantId: 'exampleGatewayMerchantId' // in production replace with your gateway provider merchant ID
}
使用 @nativescript/google-pay
要在您的应用中实现 Google Pay,请按照以下步骤操作
- 在您的应用中注册 GooglePayBtn 视图并将其添加到标记中。
xml
<android>
<GooglePayBtn
cardNetworks="VISA, AMEX, DISCOVER"
authMethods="PAN_ONLY, CRYPTOGRAM_3DS"
tap="onGooglePayTap"
width="100%"
height="40"
buttonType="PAY_BLACK"
></GooglePayBtn>
</android>
- 侦听 GooglePayBtn 的点击事件
点击 GooglePayBtn 将使用 Google Pay 启动支付。在 tap
事件处理程序(onGooglePayTap
函数)中,使用 Google Pay 管理支付,如下所示
- 侦听按钮实例上的
GooglePayEvents.PaymentSuccess
事件。
- 当用户批准您的应用使用其 Google Pay 支付数据进行支付时,将发出此事件。
GooglePayEvents.PaymentSuccess
事件的回调函数将从 Google Pay 中接收令牌和其他数据,即 PaymentSuccessEventData。您将其发送到您的支付服务提供商以进行支付处理。
ts
googlePayBtn.once(
GooglePayEvents.PaymentSuccess,
async (args: PaymentSuccessEventData) => {
const payloadToBackend = {
amount: 25.2,
method: '3DS',
'3DS': {
signature: args.data.paymentMethodData.tokenizationData.token.signature,
type: 'G', // for Google
version:
args.data.paymentMethodData.tokenizationData.token.protocolVersion,
data: args.data.paymentMethodData.tokenizationData.token.signedMessage,
},
}
// send the user payments data to your payments services provider here
const result = await someHttpCallToPaymentServiceProvider(payloadToBackend)
}
)
2. Present the user with the payment sheet.
To present the user with the payment sheet to complete the transaction, call the
`createPaymentRequest()` passing it a [GooglePayRequest](#googlepayrequest) object.
```ts
const options = {
environment: 'development', // change this to production when in prod mode
theme: 'light',
merchantInfo: {
merchantName: 'YOUR_MERCHANT_NAME'
},
allowedPaymentMethods: {
type: AllowedPaymentMethodsType.CARD,
parameters: {
allowPrepaidCards: true,
allowCreditCards: true,
billingAddressRequired: true,
billingAddressParameters: {
format: BillingAddressParametersFormat.MIN, // FULL
phoneNumberRequired: true
}
},
tokenizationSpecification: {
type: TokenizationSpecificationType.PAYMENT_GATEWAY,
parameters: {
gateway: 'example', // in production replace with your gateway provider
gatewayMerchantId: 'exampleGatewayMerchantId' // in production replace with your gateway provider merchant ID
}
}
},
transactionInfo: {
currencyCode: 'USD',
countryCode: 'US',
// transactionId: '283999292929929', // A unique ID that identifies a transaction attempt. Merchants can use an existing ID or generate a specific one for Google Pay transaction attempts. This field is required when you send callbacks to the Google Transaction Events API.
totalPriceStatus: TotalPriceStatusValue.FINAL,
totalPrice: 25.20,
totalPriceLabel: 'Total',
checkoutOption: CheckoutOptionValue.DEFAULT
},
emailRequired: true,
shippingAddressRequired: true,
shippingAddressParameters: {
allowedCountryCodes: ['US'],
phoneNumberRequired: true
}
} as GooglePayRequest;
googlePayBtn.createPaymentRequest(options).catch(err => {
console.log('error with create payment request', err);
});
```
您可以在此处找到上述步骤的完整代码示例 此处
API
GooglePayBtn 类
一个用于启动和管理 Google Pay 支付的类。
方法 | 返回值 | 描述 |
---|---|---|
createPaymentRequest(args: GooglePayRequest) | Promise<unknown> | 创建 Google Pay 支付请求并向用户显示支付表单。 |
枚举
GooglePayAuthMethods
键 | 描述 |
---|---|
PAN_ONLY | 此身份验证方法与存储在用户 Google 帐户中的付款卡相关联。返回的支付数据包括个人账户号码 (PAN) 以及到期月份和到期年份。 |
CRYPTOGRAM_3DS | 此身份验证方法与存储为 Android 设备令牌的卡相关联。返回的支付数据包括在设备上生成的 3-D Secure (3DS) 密码。 |
GooglePayCardNetworks
键 | 值 |
---|---|
AMEX | 'AMEX' |
DISCOVER | 'DISCOVER' |
INTERAC | 'INTERAC' |
JCB | 'JCB' |
MASTERCARD | 'MASTERCARD' |
VISA | 'VISA' |
GooglePayEvents
键 | 值 |
---|---|
PaymentCancelled | 'PaymentCancelled' |
PaymentError | 'PaymentError' |
PaymentSuccess | 'PaymentSuccess' |
TokenizationSpecificationType
枚举 | 描述 |
---|---|
PAYMENT_GATEWAY | 要从 Google Pay API 支持的支付网关检索支付和客户信息,请将 type 设置为 PAYMENT_GATEWAY |
DIRECT | 直接集成允许商家在其服务器上解密 Google Pay 响应。要获得资格,您必须符合支付卡行业 (PCI) 数据安全标准 (DSS) 1 级。您的服务器还需要具备安全处理用户支付凭据所需的必要基础设施。 |
BillingAddressParametersFormat
键 | 描述 |
---|---|
MIN | 姓名、国家/地区代码和邮政编码(默认值)。 |
FULL | 姓名、街道地址、地区、省/自治区、国家/地区代码和邮政编码。 |
AllowedPaymentMethodsType
键 | 值 |
---|---|
CARD | 'CARD' |
TotalPriceStatusValue
键 | 描述 |
---|---|
NOT_CURRENTLY_KNOWN | 用于功能检查。如果交易在欧洲经济区国家/地区处理,请勿使用此属性。 |
ESTIMATED | 总价可能会根据响应的详细信息进行调整,例如根据账单地址收取的销售税。 |
FINAL | 总价不会从显示给购物者的金额中更改。 |
CheckoutOptionValue
键 | 描述 |
---|---|
DEFAULT | 标准文本适用于给定的 totalPriceStatus(默认值)。 |
COMPLETE_IMMEDITATE_PURCHASE | 付款人在确认其选择后,立即对所选付款方式进行收费。此选项仅在 totalPriceStatus 设置为 FINAL 时可用。 |
GooglePayButtonType
键 | 值 |
---|---|
PAY_WHITE | 'PAY_WHITE' |
PAY_WHITE_NO_SHADOW | 'PAY_WHITE_NO_SHADOW' |
BUY_WHITE | 'BUY_WHITE' |
BUY_WHITE_NO_SHADOW | 'BUY_WHITE_NO_SHADOW' |
PAY_BLACK | 'PAY_BLACK' |
BUY_BLACK | 'BUY_BLACK' |
DONATE_BLACK | 'DONATE_BLACK' |
接口
GooglePayRequest
ts
interface GooglePayRequest {
/**
* Sets the ENVIRONMENT for testing Google Pay
*/
environment: 'development' | 'production'
/**
* Sets the theme for the payment sheet UI.
*/
theme: 'dark' | 'light'
/**
* Major API version. The value is 2 for this specification.
*/
apiVersion: number
/**
* Minor API version. The value is 0 for this specification.
*/
apiVersionMinor: number
merchantInfo: {
/**
* Merchant name encoded as UTF-8. Merchant name is rendered in the payment sheet. In TEST environment, or if a merchant isn't recognized, a “Pay Unverified Merchant” message is displayed in the payment sheet.
*/
merchantName: string
}
allowedPaymentMethods: {
/**
* A short identifier for the supported payment method.
* Only CARD and PAYPAL currently are supported entries
*/
type: string
parameters: {
/**
* Fields supported to authenticate a card transaction.
* PAN_ONLY: This authentication method is associated with payment cards stored on file with the user's Google Account. Returned payment data includes personal account number (PAN) with the expiration month and the expiration year.
* CRYPTOGRAM_3DS: This authentication method is associated with cards stored as Android device tokens. Returned payment data includes a 3-D Secure (3DS) cryptogram generated on the device.
*/
allowedAuthMethods: Array<string>
/**
* One or more card networks that you support, also supported by the Google Pay API.
* AMEX
* DISCOVER
* INTERAC
* JCB
* MASTERCARD
* VISA
*/
allowedCardNetworks: string
/**
* Set to false if you don't support prepaid cards. Default: The prepaid card class is supported for the card networks specified.
*/
allowPrepaidCards?: boolean
/**
* Set to false if you don't support credit cards. Default: The credit card class is supported for the card networks specified.
*/
allowCreditCards?: boolean
/**
* Set to true to request assuranceDetails. This object provides information about the validation performed on the returned payment data.
*/
assuranceDetailsRequired?: boolean
/**
* Set to true if you require a billing address. A billing address should only be requested if it's required to process the transaction. Additional data requests can increase friction in the checkout process and lead to a lower conversion rate.
*/
billingAddressRequired?: boolean
/**
* The expected fields returned if billingAddressRequired is set to true.
*/
billingAddressParameters?: {
/**
* Billing address format required to complete the transaction.
* MIN: Name, country code, and postal code (default).
* FULL: Name, street address, locality, region, country code, and postal code.
*/
format?: string
/**
* Set to true if a phone number is required to process the transaction.
*/
phoneNumberRequired?: boolean
}
}
/**
* Configure an account or decryption provider to receive payment information.
* This property is required for the CARD payment method.
*/
tokenizationSpecification?: {
/**
* A payment method tokenization type is supported for the given PaymentMethod.
* For CARD payment method, use PAYMENT_GATEWAY or DIRECT.
* For PAYPAL PaymentMethod, use DIRECT with no parameter.
*/
type: TokenizationSpecificationType
/**
* Parameters specific to the selected payment method tokenization type.
*/
parameters: {
gateway: string
gatewayMerchantId: string
}
}
}
/**
* Details about the authorization of the transaction based upon whether the user agrees to the transaction or not. Includes total price and price status.
* https://developers.google.com/pay/api/android/reference/request-objects#TransactionInfo
*/
transactionInfo: {
/**
* Array containing the transaction items for the transaction (item, shipping, tax, etc.)
*/
displayItems: Array<GoogelPayDisplayItems>
/**
* ISO 4217 alphabetic currency code.
*/
currencyCode: string
/**
* ISO 3166-1 alpha-2 country code where the transaction is processed. This is required for merchants based in European Economic Area (EEA) countries.
*/
countryCode?: string
/**
* A unique ID that identifies a transaction attempt. Merchants may use an existing ID or generate a specific one for Google Pay transaction attempts. This field is required when you send callbacks to the Google Transaction Events API.
*/
transactionId?: string
/**
* The status of the total price used.
*/
totalPriceStatus: TotalPriceStatusValue
/**
* Total monetary value of the transaction with an optional decimal precision of two decimal places. This field is required unless totalPriceStatus is set to NOT_CURRENTLY_KNOWN.
* The format of the string should follow the regex format: ^[0-9]+(\.[0-9][0-9])?$
*/
totalPrice?: string
/**
* Custom label for the total price within the display items.
*/
totalPriceLabel?: string
/**
* Affects the submit button text displayed in the Google Pay payment sheet.
*/
checkoutOption?: CheckoutOptionValue
}
/**
* Set to true to request an email address.
*/
emailRequired?: boolean
/**
* Set to true to request a full shipping address.
*/
shippingAddressRequired?: boolean
/**
* If shippingAddressParameters is set to true, specify shipping address restrictions.
*/
shippingAddressParameters?: {
/**
* ISO 3166-1 alpha-2 country code values of the countries where shipping is allowed. If this object isn't specified, all shipping address countries are allowed.
*/
allowedCountryCodes?: Array<string>
/**
* Set to true if a phone number is required for the provided shipping address.
*/
phoneNumberRequired?: boolean
}
}
PaymentCancelledEventData
ts
interface PaymentCancelledEventData extends EventData {
eventName: string
object: any
}
PaymentErrorEventData
ts
interface PaymentErrorEventData extends EventData {
eventName: string
object: any
data: {
statusCode: number
}
}
PaymentSuccessEventData
ts
interface PaymentSuccessEventData extends EventData {
eventName: string
object: any
data: {
/**
* Data about the selected payment method.
*/
paymentMethodData: {
/**
* PaymentMethod type selected in the Google Pay payment sheet.
*/
type: string
/**
* User-facing message to describe the payment method that funds this transaction.
*/
description: string
/**
* The value of this property depends on the payment method type returned. For CARD, see CardInfo.
*/
info: {
/**
* The details about the card. This value is commonly the last four digits of the selected payment account number.
*/
cardDetails: string
/**
* This object provides information about the validation performed on the returned payment data if assuranceDetailsRequired is set to true in the CardParameters.
*/
assuranceDetails: {
/**
* If true, indicates that Cardholder possession validation has been performed on returned payment credential.
*/
accountVerified: boolean
/**
* If true, indicates that identification and verifications (ID&V) was performed on the returned payment credential.
* If false, the same risk-based authentication can be performed as you would for card transactions. This risk-based authentication can include, but not limited to, step-up with 3D Secure protocol if applicable.
*/
cardHolderAuthenticated: boolean
}
/**
* The payment card network of the selected payment. Returned values match the format of allowedCardNetworks in CardParameters.
* This card network value should not be displayed to the buyer. It's used when the details of a buyer's card are needed. For example, if customer support needs this value to identify the card a buyer used for their transaction. For a user-visible description, use the description property of PaymentMethodData instead.
*/
cardNetwork: string
/**
* The billing address associated with the provided payment method, if billingAddressRequired is set to true in CardParameters.
*/
billingAddress?: Address
}
/**
* Payment tokenization data for the selected payment method.
*/
tokenizationData: {
/**
* The type of tokenization to be applied to the selected payment method. This value matches the type set in PaymentMethodTokenizationSpecification.
*/
type: string
/**
* The generated payment method token.
* PAYMENT_GATEWAY: JSON object string that contains a chargeable token issued by your gateway.
* DIRECT: protocolVersion, signature, and a signedMessage for decryption. See Payment method token structure for more information.
*/
token: {
/**
* Identifies the encryption or signing scheme under which the message is created. It allows the protocol to evolve over time, if needed.
*/
protocolVersion: string
/**
* Verifies that the message came from Google. It's base64-encoded, and created with ECDSA by the intermediate signing key.
*/
signature: string
/**
* A JSON object serialized as a string that contains the encryptedMessage, ephemeralPublicKey, and tag. It's serialized to simplify the signature verification process.
*/
signedMessage: string
/**
* JSON object string that contains a chargeable token issued by your gateway
*/
rawToken: string
}
}
}
/**
* Email address, if emailRequired is set to true in the PaymentDataRequest. If another request has the property set to true there's no effect.
*/
email: string
/**
* Shipping address, if shippingAddressRequired is set to true in the PaymentDataRequest.
*/
shippingAddress: Address
}
}
地址
ts
Address {
/**
* The full name of the addressee.
*/
name;
/**
* The postal or ZIP code.
*/
postalCode;
/**
* ISO 3166-1 alpha-2 country code.
*/
countryCode;
/**
* A telephone number, if phoneNumberRequired is set to true in the PaymentDataRequest.
*/
phoneNumber;
/**
* The first line of the address.
*/
address1;
/**
* The second line of the address.
*/
address2;
/**
* The third line of the address.
*/
address3;
/**
* City, town, neighborhood, or suburb.
*/
locality;
/**
* A country subdivision, such as a state or province.
*/
administrativeArea;
/**
* The sorting code.
*/
sortingCode;
}
GooglePayDisplayItems
ts
interface GoogelPayDisplayItems {
label: string
type: string
price: string
}
许可证
Apache 许可证 2.0 版
- 上一个
- Apple Pay
- 下一个
- 支付:应用内购买和订阅