Stripe integration in android and create token

后端 未结 4 502
暗喜
暗喜 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<String, Object> chargeParams = new     HashMap<String, Object>();
                            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<Void, Void, Void>() {
    
                                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<String, Object> chargeParams1 = new HashMap<String, Object>();
                            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<String, Object> customerParams = new HashMap<String, Object>();
                            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<String, Object> chargeParams2 = new HashMap<String, Object>();
                            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.

    0 讨论(0)
  • 2021-01-03 15:46

    Sorry for late answer but it will help someone in future.

    You can also add following dependencies to build.gradle file.

    compile "com.stripe:stripe-java:5.7.1"
    

    You can see all its classes here

    0 讨论(0)
  • 2021-01-03 15:53

    Charge Class is not included in the old stripe sdk I solved it my by just downloaded the latest stripe and gson jars file from Download gson-2.2.2.jar : gson « g « Jar File Download and put it under lib folder in my project directry and add compile fileTree(dir: 'libs', include: ['*.jar']) to build.gradle and remove the old stripe module from my projcet and now it work fine My gradle file is

    dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
      compile 'com.android.support:appcompat-v7:25.1.0'
      compile 'com.android.support:design:25.1.0'
      testCompile 'junit:junit:4.12'
      compile 'com.stripe:stripe-android:2.0.2'
      compile 'com.google.android.gms:play-services-appindexing:8.4.0'
    }
    

    now you can use charge class of the stripe

    0 讨论(0)
  • 2021-01-03 15:59

    You should not make a charge inside the Android app. The client (here your App), should only get a Stripe token, then send this token to your backend (your server), and then use this token to create a charge with stripe.

    You must not create a charge client side as it is not secure : your secret key should not be inside the app, as it won't be secret anymore.

    This is the reason why the lib stripe-android does not have the charge class : it is not meant for that. The stripe-java lib is meant to be used on a java server.

    0 讨论(0)
提交回复
热议问题