Implementacion de apple-pay, Google Pay

sera posible usar como pasarela de pago Google Pay, y apple pay ???

Google Pay

Learn how to accept payments using Google Pay.

GOOGLE PAY TERMS

By integrating Google Pay, you agree to Google’s terms of service.

Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including ones from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer’s Google account.

Google Pay is fully compatible with Stripe’s products and features (e.g., subscriptions), allowing you to use it in place of a traditional payment form whenever possible. Use it to accept payments for physical or digital goods, donations, subscriptions, and more.

Accepting Google Pay in your Android app

Use the Stripe Android SDK to start accepting Google Pay in your Android apps.

Step 1: Set up your integration

To use Google Pay, first enable the Google Pay API by adding the following to the <application> tag of your AndroidManifest.xml :

AndroidManifest.xml

<application
  ...
  <meta-data
    android:name="com.google.android.gms.wallet.api.enabled"
    android:value="true" />
</application>

This guide assumes you are using Google Play services 18.0.0 or greater and Stripe Android SDK v14.1.1 or greater.

build.gradle

dependencies {
  implementation 'com.google.android.gms:play-services-wallet:18.0.0'
  implementation 'androidx.appcompat:appcompat:1.1.0'
  implementation 'com.stripe:stripe-android:14.4.1'
}

For more details, see Google Pay’s Set up Google Pay API for Android.

Step 2: Instantiate PaymentsClient

Next, create an instance of PaymentsClient in your Activity . This allows you to access the Payments APIs. Do this before you start the payment flow, such as in Activity#onCreate() .

Java kotlin

final PaymentsClient paymentsClient = Wallet.getPaymentsClient(this,
    new Wallet.WalletOptions.Builder()
        .setEnvironment(WalletConstants.ENVIRONMENT_TEST)
        .build());

After creating PaymentsClient, create an instance of IsReadyToPayRequest and fire it to determine if Google Pay is available.

Java kotlin

private void isReadyToPay() {
    final IsReadyToPayRequest request = createIsReadyToPayRequest();
    paymentsClient.isReadyToPay(request)
        .addOnCompleteListener(
            new OnCompleteListener<Boolean>() {
                public void onComplete(Task<Boolean> task) {
                    try {
                        if (task.isSuccessful()) {
                            // show Google Pay as payment option
                        } else {
                            // hide Google Pay as payment option
                        }
                    } catch (ApiException exception) { }
                }
            }
        );
}

@NonNull
private IsReadyToPayRequest createIsReadyToPayRequest() throws JSONException {
    final JSONArray allowedAuthMethods = new JSONArray();
    allowedAuthMethods.put("PAN_ONLY");
    allowedAuthMethods.put("CRYPTOGRAM_3DS");

    final JSONArray allowedCardNetworks = new JSONArray();
    allowedCardNetworks.put("AMEX");
    allowedCardNetworks.put("DISCOVER");
    allowedCardNetworks.put("JCB");
    allowedCardNetworks.put("MASTERCARD");
    allowedCardNetworks.put("VISA");

    final JSONObject isReadyToPayRequestJson = new JSONObject();
    isReadyToPayRequestJson.put("allowedAuthMethods", allowedAuthMethods);
    isReadyToPayRequestJson.put("allowedCardNetworks", allowedCardNetworks);

    return IsReadyToPayRequest.fromJson(isReadyToPayRequestJson.toString());
}

Step 3: Create a payment request

When the user is ready to pay, create a PaymentDataRequest JSON object. The PaymentDataRequest object is a JSONObject representing a request for method of payment (such as a credit card) and other details. It provides the necessary information to support a payment, including transaction information such as total cost and currency.

To create a PaymentDataRequest JSONObject with Stripe configured as your gateway, set the PaymentMethod’s TokenizationSpecification using GooglePayConfig#getTokenizationSpecification().

Configure CardParameters.billingAddressRequired, BillingAddressParameters, and PaymentDataRequest.emailRequired according to your needs, as shown below.

Once you have your tokenization parameters, create the PaymentDataRequest object with the information relevant to the purchase.

Java kotlin

@NonNull
private JSONObject createPaymentDataRequest() {
    final JSONObject tokenizationSpec =
        new GooglePayConfig().getTokenizationSpecification();
    final JSONObject cardPaymentMethod = new JSONObject()
        .put("type", "CARD")
        .put(
            "parameters",
            new JSONObject()
                .put("allowedAuthMethods", new JSONArray()
                    .put("PAN_ONLY")
                    .put("CRYPTOGRAM_3DS"))
                .put("allowedCardNetworks",
                    new JSONArray()
                        .put("AMEX")
                        .put("DISCOVER")
                        .put("JCB")
                        .put("MASTERCARD")
                        .put("VISA"))

                // require billing address
                .put("billingAddressRequired", true)
                .put(
                    "billingAddressParameters",
                    new JSONObject()
                        // require full billing address
                        .put("format", "FULL")

                        // require phone number
                        .put("phoneNumberRequired", true)
                )
        )
        .put("tokenizationSpecification", tokenizationSpec);

    // create PaymentDataRequest
    final JSONObject paymentDataRequest = new JSONObject()
        .put("apiVersion", 2)
        .put("apiVersionMinor", 0)
        .put("allowedPaymentMethods",
            new JSONArray().put(cardPaymentMethod))
        .put("transactionInfo", JSONObject()
            .put("totalPrice", "10.00")
            .put("totalPriceStatus", "FINAL")
            .put("currencyCode", "USD")
        )
        .put("merchantInfo", new JSONObject()
            .put("merchantName", "Example Merchant"))

        // require email address
        .put("emailRequired", true)
        .toString();

    return PaymentDataRequest.fromJson(paymentDataRequest);
}

Step 4: Submit the payment

Now that you’ve established a way to create the payment data request, hook up that method to your “Buy” button’s click handler.

Java kotlin

public class PayWithGoogleActivity extends AppCompatActivity {
    private static final int LOAD_PAYMENT_DATA_REQUEST_CODE = 53;

    private void payWithGoogle() {
        AutoResolveHelper.resolveTask(
            paymentsClient.loadPaymentData(createPaymentDataRequest()),
            this,
            LOAD_PAYMENT_DATA_REQUEST_CODE
        );
    }
}

Invoking AutoResolveHelper#resolveTask() with a PaymentDataRequest will launch Google Pay. Receive the result in Activity#onActivityResult() . Use PaymentMethodCreateParams#createFromGooglePay(JSONObject) to create a PaymentMethodCreateParams object from the JSON representation of the PaymentData , as shown below.

Charges API Payment Intents API

Java kotlin

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case LOAD_PAYMENT_DATA_REQUEST_CODE: {
            switch (resultCode) {
                case Activity.RESULT_OK: {
                    PaymentData paymentData = PaymentData.getFromIntent(data);
                    // You can get some data on the user's card, such as the
                    // brand and last 4 digits
                    CardInfo info = paymentData.getCardInfo();
                    // You can also pull the user address from the
                    // PaymentData object.
                    UserAddress address = paymentData.getShippingAddress();
                    // This is the raw JSON string version of your Stripe token.
                    String rawToken = paymentData.getPaymentMethodToken()
                        .getToken();

                    // Now that you have a Stripe token object,
                    // charge that by using the id
                    Token stripeToken = Token.fromString(rawToken);
                    if (stripeToken != null) {
                        // This chargeToken function is a call to your own
                        // server, which should then connect to Stripe's
                        // API to finish the charge.
                        chargeToken(stripeToken.getId());
                    }
                    break;
                }
                case Activity.RESULT_CANCELED: {
                    break;
                }
                case AutoResolveHelper.RESULT_ERROR: {
                    // Log the status for debugging
                    // Generally there is no need to show an error to
                    // the user as the Google Payment API will do that
                    final Status status =
                        AutoResolveHelper.getStatusFromIntent(data);
                    break;
                }
                default: {
                    // Do nothing.
                }
            }
            break;
        }
        default: {
            // Handle any other startActivityForResult calls you may have made.
        }
    }
}

Going live with Google Pay

  1. Build your app in ENVIRONMENT_TEST with your Stripe test publishable key.
  2. Reach out to Google support.
  3. Send the APK pointing to ENVIRONMENT_TEST to Google support when requested.
  4. Google assesses the app against their integration checklist and provides feedback if needed.
  5. Google provides instructions on how to agree to their Terms of Service and ensure production access is granted.
  6. Send your final production APK pointing to ENVIRONMENT_PRODUCTION to Google for a real-world test which includes a few transactions.
  7. If all tests pass, Google clears you to publish the APK.
  8. Notify Google support when your APK is 100% visible to users.

Apple Pay

Allow customers to securely make payments using Apple Pay on their iPhone, iPad, and Apple Watch.

SUPPORTED DEVICES

Refer to Apple’s compatibility documentation to learn which devices support Apple Pay.

Stripe users can accept Apple Pay in iOS applications in iOS 9 and above, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the pricing is the same as other card transactions.

Apple Pay is compatible with most Stripe products and features (e.g., subscriptions), allowing you to use it in place of a traditional payment form whenever possible. Use it to accept payments for physical or digital goods, donations, subscriptions, and more (note that Apple Pay cannot be used instead of in-app purchases).

Apple Pay is available to cardholders at participating banks in supported countries. Refer to Apple’s participating banks documentation to learn which banks and countries are supported.

Using Stripe and Apple Pay vs. in-app purchases

Apple Pay doesn’t replace Apple’s In-App Purchase API. You can use any of Stripe’s supported payment methods and Apple Pay in your iOS app to sell physical goods (e.g., groceries and clothing) or for services your business provides (e.g., club memberships and hotel reservations). These payments are processed through Stripe and you only need to pay Stripe’s processing fee.

Apple’s developer terms require their In-App Purchase API be used for digital “content, functionality, or services,” such as premium content for your app or subscriptions for digital content. Payments made using the In-App Purchase API are processed by Apple and subject to their transaction fees.

Accept Apple Pay in your iOS app

Stripe’s iOS SDK makes it easy to accept both Apple Pay and regular credit card payments. Before you start, you’ll need to be enrolled in the Apple Developer Program and set up Stripe on your server and in your app. Next, follow these steps:

  1. Register for an Apple Merchant ID
  2. Create a new Apple Pay certificate
  3. Integrate with Xcode
  4. Check if Apple Pay is supported
  5. Create the payment request
  6. Present the payment sheet
  7. Submit the payment to Stripe

Step 1: Register for an Apple Merchant ID

First, you’ll need to obtain an Apple Merchant ID. Register a new identifier on the Apple Developer website.

Fill out the form with a description and identifier. Your description is for your own records and can be modified in the future (we recommend just using the name of your app). We recommend using merchant.com.{{your_app_name}} as the identifier.

Step 2: Create a new Apple Pay certificate

Next, create a certificate for your app to encrypt payment data.

Head to the Apple Pay Settings page in the Dashboard. Choose Add new application and follow the guide there.

Step 3: Integrate with Xcode

Finally, add the Apple Pay capability to your app. In Xcode, open your project settings, choose the Signing & Capabilities tab, and add the Apple Pay capability. You may be prompted to log in to your developer account at this point. Enable the checkbox next to the merchant ID you created earlier, and your app is ready to accept Apple Pay!

Xcode capabilities pane

Enable the Apple Pay capability in Xcode

Step 4: Check if Apple Pay is supported

If you’re using STPPaymentContext , that class handles the rest for you. Follow this guide instead.

Before displaying Apple Pay as a payment option in your app, determine if the user’s device supports Apple Pay and they have a card added to their wallet.

Swift Objective-C

CheckoutViewController.swift

import Stripe
import PassKit

class CheckoutViewController: UIViewController, STPApplePayContextDelegate {
    let applePayButton: PKPaymentButton = PKPaymentButton(paymentButtonType: .plain, paymentButtonStyle: .black)

    override func viewDidLoad() {
        super.viewDidLoad()
        // Only offer Apple Pay if the customer can pay with it
        applePayButton.isHidden = Stripe.deviceSupportsApplePay()
        applePayButton.addTarget(self, action: #selector(handleApplePayButtonTapped), for: .touchUpInside)
    }

    // ...continued in next step
}

Step 5: Create the payment request

When the user taps the Apple Pay button, call Stripe paymentRequestWithMerchantIdentifier:country:currency: to create a PKPaymentRequest.

Next, configure the PKPaymentRequest to display your business name and the total. You can also collect information like billing details or shipping information.

See Apple’s documentation for full guidance on how to customize the payment request.

Swift Objective-C

CheckoutViewController.swift

func handleApplePayButtonTapped() {
    let merchantIdentifier = "merchant.com.your_app_name"
    let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD")

    // Configure the line items on the payment request
    paymentRequest.paymentSummaryItems = [
        // The final line should represent your company;
        // it'll be prepended with the word "Pay" (i.e. "Pay iHats, Inc $50")
        PKPaymentSummaryItem(label: "iHats, Inc", amount: 50.00),
    ]
    // ...continued in next step
}

Step 6: Present the payment sheet

Next, create an STPApplePayContext instance with the PKPaymentRequest and use it to present the Apple Pay sheet.

Swift Objective-C

CheckoutViewController.swift

func handleApplePayButtonTapped() {
    // ...continued from previous step

    // Initialize an STPApplePayContext instance
    if let applePayContext = STPApplePayContext(paymentRequest: paymentRequest, delegate: self) {
        // Present Apple Pay payment sheet
        applePayContext.presentApplePay(on: self)
    } else {
        // There is a problem with your Apple Pay configuration
    }
}

Step 7: Submit the payment to Stripe

Payment Intents API Payment Intents API (Server-side confirmation)

Server-side

On your server, make an endpoint that creates a PaymentIntent with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl Ruby Python PHP Java Node Go .NET

curl https://api.stripe.com/v1/payment_intents \
  -u sk_test_JvHyiNx9upl7IlABYyVfPSBF0040YC3a3v: \
  -d amount=1099 \
  -d currency=usd

Client-side

Implement applePayContext:didCreatePaymentMethod:completion: to call the completion block with the PaymentIntent client secret retrieved from the endpoint above.

After you call the completion block, STPApplePayContext completes the payment, dismisses the Apple Pay sheet, and calls applePayContext:didCompleteWithStatus:error: with the status of the payment. Implement this method to show a receipt to your customer.

Swift Objective-C

CheckoutViewController.swift

extension CheckoutViewController {
    func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: STPPaymentMethod, paymentInformation: PKPayment, completion: @escaping STPIntentClientSecretCompletionBlock) {
        let clientSecret = ... // Retrieve the PaymentIntent client secret from your backend (see Server-side step above)
        // Call the completion block with the client secret or an error
        completion(clientSecret, error);
    }

    func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPPaymentStatus, error: Error?) {
          switch status {
        case .success:
            // Payment succeeded, show a receipt view
            break
        case .error:
            // Payment failed, show the error
            break
        case .userCancellation:
            // User cancelled the payment
            break
        @unknown default:
            fatalError()
        }
    }
}

Finally, handle post-payment events to do things like sending an order confirmation email to your customer, logging the sale in a database, or starting a shipping workflow.

Troubleshooting

If you’re seeing errors from the Stripe API when attempting to create tokens, there’s likely something wrong with your Apple Pay Certificate. You’ll need to generate a new certificate and upload it to Stripe, as described above. Make sure you use a CSR obtained from your Dashboard and not one you generated yourself. Xcode often incorrectly caches old certificates, so in addition to generating a new certificate, we recommend creating a new Apple Merchant ID as well.

If you receive the error “You haven’t added your Apple merchant account to Stripe,” it’s likely your app is sending data encrypted with a previous (non-Stripe) CSR/Certificate. Make sure any certs generated by non-Stripe CSRs are revoked under your Apple Merchant ID. If this does not resolve the issue, delete the merchant ID in your Apple account and recreate it. Then, create a new certificate based on the same (Stripe-provided) CSR that was previously used. You do not need to re-upload this new certificate to Stripe. Once done, toggle the Apple Pay Credentials off and on in your app to make sure they refresh properly.

Accept Apple Pay on the web

You can start accepting Apple Pay payments on the web using Checkout or Elements. No additional configuration is required to use Apple Pay in Checkout. For Elements, refer to our Payment Request Button documentation to learn how to add Apple Pay to your site.

For existing integrations created using Stripe.js v2, you can refer to our previous Apple Pay on the Web documentation. We recommend upgrading to Checkout or Elements at your earliest convenience.

Use of Apple Pay on the Web is subject to the Apple Pay on the Web terms of service.

Recurring payments

Apple Pay tokens can be used to create one-off payments or subscriptions. For repeat purchases that are not related to a subscription, we recommend you create single-use tokens. Your customer must authenticate with the Apple Pay payment sheet each time—attempting to reuse payment information for a non-subscription payment can result in it being declined.

Testing Apple Pay

Stripe test card information cannot be saved to Wallet in iOS. Instead, Stripe recognizes when you are using your test API keys and returns a successful test card token for you to use. This allows you to make test payments using a live card without it being charged.

Next steps

Congrats! You’re now ready to implement Apple Pay. If you’d like to read more about Apple Pay and its other configuration options, we recommend the NSHipster article on Apple Pay and the Apple Pay Within Apps presentation from WWDC 2015.

Se podra implementar ???