Stripe integration in android and create token

后端 未结 4 530
暗喜
暗喜 2021-01-03 15:19

I want to integrate stripe in android and test the code with publishable key. I want to create token after successful transaction with the card params any suggested code.

4条回答
  •  天涯浪人
    2021-01-03 15:44

    follow this code and also import stripe library.

    public class StripePaymentActivity extends FragmentActivity {
    
    /*
     * Change this to your publishable key.
     * 
     * You can get your key here: https://manage.stripe.com/account/apikeys
     */
    // public static final String PUBLISHABLE_KEY =
    // "pk_test_Tw0HyQcWAVM9R5dBdiiS90X9"; Client Key
    
    public static final String PUBLISHABLE_KEY = "your key";
    private ProgressDialogFragment progressFragment;
    String[] id, memberId, userEmail, endDate;
    Dialog dialog;
    
    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.payment_activity);
    dialog = new Dialog(StripePaymentActivity.this);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    progressFragment = ProgressDialogFragment
            .newInstance(R.string.progressMessage);
    }
    
    public void saveCreditCard(PaymentForm form) {
    
    Card card = new Card(form.getCardNumber(), form.getExpMonth(),
            form.getExpYear(), form.getCvc());
    Log.e("card ", "27th March ::- " + card);
    boolean validation = card.validateCard();
    Log.e("Validation", "27th March::-" + validation);
    if (validation) {
        startProgress();
        new Stripe().createToken(card, PUBLISHABLE_KEY,
                new TokenCallback() {
                    public void onSuccess(Token token) {
                        try {
                            // getTokenList().addToList(token);
                            Log.e("Token Json", "27th March::-" + token);
                            final Map chargeParams = new     HashMap();
                            chargeParams.put("amount", 999);
                            chargeParams.put("currency", "usd");
                            chargeParams.put("card", token.getId());
                            // chargeParams.put("captured", false);
                            com.stripe.Stripe.apiKey = "sk.. your key";
                            // Charge charge = Charge.create(chargeParams);
                            // Charge ch = Charge.retrieve(charge.getId());
                            // // Used it here for demonstration
                            // ch.capture();
                            // Charge.create(chargeParams);
                            new AsyncTask() {
    
                                Charge charge;
    
                                @Override
                                protected Void doInBackground(
                                        Void... params) {
                                    try {
                                        com.stripe.Stripe.apiKey = "sk_your key";
                                        charge = Charge
                                                .create(chargeParams);
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                        // showAlert("Exception while charging the card!",
                                        // e.getLocalizedMessage());
                                    }
                                    return null;
                                }
    
                                protected void onPostExecute(Void result) {
                                    Toast.makeText(
                                            StripePaymentActivity.this,
                                            "Card Charged : "
                                                    + charge.getCreated()
                                                    + "\nPaid : "
                                                    + charge.getPaid(),
                                            Toast.LENGTH_LONG).show();
                                };
    
                            }.execute();
                            final Map chargeParams1 = new HashMap();
                            chargeParams1.put("amount", 999);
                            chargeParams1.put("currency", "usd");
                            chargeParams1.put("card", token.getId());
                            chargeParams1.put("captured", false);
                            com.stripe.Stripe.apiKey = "sk_your key";
                            Charge charge1 = Charge.create(chargeParams1);
                            com.stripe.Stripe.apiKey = "sk_your key";
                            Charge ch2 = Charge.retrieve(charge1.getId()); //    Use
                                                                            // saved
                                                                            // charged
                                                                            // Id
                                                                            // instead
                                                                            // of
                                                                            // charge.getId()
                                                                            // Used
                                                                            // it
                                                                            // here
                                                                            // for
                                                                            // demonstration
                            ch2.capture();
                            com.stripe.Stripe.apiKey = "sk_your key";
    
                            // Customer Parameters HashMap
                            Map customerParams = new HashMap();
                            customerParams
                                    .put("description",
                                            com.essexpass.Global
                                                    .getPreferenceString(
                                                            getApplicationContext(),
                                                            "email", ""));
                            customerParams.put("card", token.getId()); // Obtained
                                                                        // in
                                                                        // onSuccess()
                                                                        // method
                                                                        // of
                                                                        // TokenCallback
                                                                        // while
                                                                        // creating
                                                                        // token
                                                                        // above
    
                            // Create a Customer
                            Customer cust = Customer.create(customerParams);
                            com.stripe.Stripe.apiKey = "sk_your key";
    
                            // Retrieve saved customer ID from database
                            // String cust_id = getSavedCustomerId();
                            // //getSavedCustomerId() method should retrieve
                            // saved customer Id from db
    
                            // Charge Parameters HashMap
                            final Map chargeParams2 = new HashMap();
                            chargeParams2.put("amount", 999);
                            chargeParams2.put("currency", "usd");
                            chargeParams2.put(
                                    "customer",
                                    com.essexpass.Global
                                            .getPreferenceString(
                                                    getApplicationContext(),
                                                    "email", "")); // Use
                                                                    // customer
                                                                    // instead
                                                                    // of
                                                                    // card
    
                            Charge.create(chargeParams2);
                        } catch (AuthenticationException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InvalidRequestException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (APIConnectionException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (CardException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (APIException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        finishProgress();
                        // Now Call The Services for the and generate New
                        // Member Id
                        GetUserPassDeal();
                    }
    
                    public void onError(Exception error) {
                        handleError(error.getLocalizedMessage());
                        finishProgress();
                    }
                });
    } else if (!card.validateNumber()) {
        handleError("The card number that you entered is invalid");
    } else if (!card.validateExpiryDate()) {
        handleError("The expiration date that you entered is invalid");
    } else if (!card.validateCVC()) {
        handleError("The CVC code that you entered is invalid");
    } else {
        handleError("The card details that you entered are invalid");
    }
    }
    
    private void startProgress() {
    progressFragment.show(getSupportFragmentManager(), "progress");
    }
    
    private void finishProgress() {
    progressFragment.dismiss();
    
    }
    
    private void handleError(String error) {
    ErrorDialogFragment fragment = ErrorDialogFragment.newInstance(
            R.string.validationErrors, error);
    fragment.show(getFragmentManager(), "error");
    }
    

    i have use this code in my application. Thanks.

提交回复
热议问题