Search in sources :

Example 11 with RequestOptions

use of com.stripe.net.RequestOptions in project stripe-java by stripe.

the class PagingIteratorTest method testAutoPaginationWithParams.

@Test
public void testAutoPaginationWithParams() throws IOException, StripeException {
    // set some arbitrary parameters so that we can verify that the
    // parameters passed to autoPagingIterable() override the initial
    // collection parameters
    Map<String, Object> page0Params = new HashMap<String, Object>();
    page0Params.put("foo", "bar");
    Map<String, Object> autoPagingParams = new HashMap<String, Object>();
    autoPagingParams.put("foo", "baz");
    Map<String, Object> page1Params = new HashMap<String, Object>();
    page1Params.put("foo", "baz");
    page1Params.put("starting_after", "pm_124");
    Map<String, Object> page2Params = new HashMap<String, Object>();
    page2Params.put("foo", "baz");
    page2Params.put("starting_after", "pm_126");
    RequestOptions options = (new RequestOptionsBuilder()).setApiKey("sk_paging_key").build();
    PageableModelCollection collection = PageableModel.list(page0Params, options);
    List<PageableModel> models = new ArrayList<PageableModel>();
    for (PageableModel model : collection.autoPagingIterable(autoPagingParams)) {
        models.add(model);
    }
    assertEquals(5, models.size());
    assertEquals("pm_123", models.get(0).getId());
    assertEquals("pm_124", models.get(1).getId());
    assertEquals("pm_125", models.get(2).getId());
    assertEquals("pm_126", models.get(3).getId());
    assertEquals("pm_127", models.get(4).getId());
    verifyGet(PageableModelCollection.class, "https://api.stripe.com/v1/pageablemodels", page0Params, options);
    verifyGet(PageableModelCollection.class, "https://api.stripe.com/v1/pageablemodels", page1Params, options);
    verifyGet(PageableModelCollection.class, "https://api.stripe.com/v1/pageablemodels", page2Params, options);
    verifyNoMoreInteractions(networkMock);
}
Also used : HashMap(java.util.HashMap) RequestOptions(com.stripe.net.RequestOptions) RequestOptionsBuilder(com.stripe.net.RequestOptions.RequestOptionsBuilder) ArrayList(java.util.ArrayList) BaseStripeTest(com.stripe.BaseStripeTest) Test(org.junit.Test)

Example 12 with RequestOptions

use of com.stripe.net.RequestOptions in project alf.io by alfio-event.

the class BaseStripeManager method getInfo.

Optional<PaymentInformation> getInfo(Transaction transaction, PurchaseContext purchaseContext) {
    try {
        Optional<RequestOptions> requestOptionsOptional = options(purchaseContext);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Charge charge = Charge.retrieve(transaction.getTransactionId(), options);
            String paidAmount = MonetaryUtil.formatCents(charge.getAmount(), charge.getCurrency());
            String refundedAmount = MonetaryUtil.formatCents(charge.getAmountRefunded(), charge.getCurrency());
            List<BalanceTransaction.Fee> fees = retrieveBalanceTransaction(charge.getBalanceTransaction(), options).getFeeDetails();
            return Optional.of(new PaymentInformation(paidAmount, refundedAmount, getFeeAmount(fees, "stripe_fee"), getFeeAmount(fees, "application_fee")));
        }
        return Optional.empty();
    } catch (StripeException e) {
        return Optional.empty();
    }
}
Also used : RequestOptions(com.stripe.net.RequestOptions) Charge(com.stripe.model.Charge) PaymentInformation(alfio.model.PaymentInformation)

Example 13 with RequestOptions

use of com.stripe.net.RequestOptions in project alf.io by alfio-event.

the class StripeManager method refund.

// https://stripe.com/docs/api#create_refund
public boolean refund(Transaction transaction, Event event, Optional<Integer> amount) {
    String chargeId = transaction.getTransactionId();
    try {
        String amountOrFull = amount.map(MonetaryUtil::formatCents).orElse("full");
        log.info("Stripe: trying to do a refund for payment {} with amount: {}", chargeId, amountOrFull);
        Map<String, Object> params = new HashMap<>();
        params.put("charge", chargeId);
        amount.ifPresent(a -> params.put("amount", a));
        if (isConnectEnabled(event)) {
            params.put("refund_application_fee", true);
        }
        Optional<RequestOptions> requestOptionsOptional = options(event);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Refund r = Refund.create(params, options);
            if ("succeeded".equals(r.getStatus())) {
                log.info("Stripe: refund for payment {} executed with success for amount: {}", chargeId, amountOrFull);
                return true;
            } else {
                log.warn("Stripe: was not able to refund payment with id {}, returned status is not 'succeded' but {}", chargeId, r.getStatus());
                return false;
            }
        }
        return false;
    } catch (StripeException e) {
        log.warn("Stripe: was not able to refund payment with id " + chargeId, e);
        return false;
    }
}
Also used : Refund(com.stripe.model.Refund) RequestOptions(com.stripe.net.RequestOptions)

Example 14 with RequestOptions

use of com.stripe.net.RequestOptions in project alf.io by alfio-event.

the class StripeManager method getInfo.

Optional<PaymentInformation> getInfo(Transaction transaction, Event event) {
    try {
        Optional<RequestOptions> requestOptionsOptional = options(event);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Charge charge = Charge.retrieve(transaction.getTransactionId(), options);
            String paidAmount = MonetaryUtil.formatCents(charge.getAmount());
            String refundedAmount = MonetaryUtil.formatCents(charge.getAmountRefunded());
            List<Fee> fees = retrieveBalanceTransaction(charge.getBalanceTransaction(), options).getFeeDetails();
            return Optional.of(new PaymentInformation(paidAmount, refundedAmount, getFeeAmount(fees, "stripe_fee"), getFeeAmount(fees, "application_fee")));
        }
        return Optional.empty();
    } catch (StripeException e) {
        return Optional.empty();
    }
}
Also used : RequestOptions(com.stripe.net.RequestOptions) Fee(com.stripe.model.Fee) Charge(com.stripe.model.Charge) PaymentInformation(alfio.model.PaymentInformation)

Example 15 with RequestOptions

use of com.stripe.net.RequestOptions in project cryptonomica by Cryptonomica.

the class StripePaymentsAPI method processStripePayment.

@ApiMethod(name = "processStripePayment", path = "processStripePayment", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public StripePaymentReturn processStripePayment(final HttpServletRequest httpServletRequest, final User googleUser, final StripePaymentForm stripePaymentForm) throws Exception {
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    // final String STRIPE_SECRET_KEY = ApiKeysUtils.getApiKey("StripeTestSecretKey");
    final String STRIPE_SECRET_KEY = ApiKeysUtils.getApiKey("StripeLiveSecretKey");
    /* --- Ensure cryptonomica registered user */
    final CryptonomicaUser cryptonomicaUser = UserTools.ensureCryptonomicaRegisteredUser(googleUser);
    /* --- record user login */
    Login login = UserTools.registerLogin(httpServletRequest, googleUser);
    LOG.warning(GSON.toJson(new LoginView(login)));
    // log info:
    LOG.warning("cryptonomicaUser: " + cryptonomicaUser.getEmail().getEmail());
    LOG.warning("key fingerpint: " + stripePaymentForm.getFingerprint());
    /* --- log form: */
    /* !!!!!!!!!!!!!!!!!!! comment in production !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
    // LOG.warning(GSON.toJson(stripePaymentForm)); // <<<<<<<<<<<<<<<<<<<<<<<!!!!!!!!!!!!!!!!!!!!!!!
    // Do not save card data in DB or to logs when working with real (non-test) cards numbers !!!!!!!
    /* --- create return object */
    StripePaymentReturn stripePaymentReturn = new StripePaymentReturn();
    /* --- get OpenPGP key data */
    final String fingerprint = stripePaymentForm.getFingerprint();
    PGPPublicKeyData pgpPublicKeyData = null;
    pgpPublicKeyData = ofy().load().type(PGPPublicKeyData.class).filter("fingerprintStr", fingerprint).first().now();
    // 
    if (pgpPublicKeyData == null) {
        throw new Exception("OpenPGP public key certificate not found in our database for " + fingerprint);
    }
    if (pgpPublicKeyData.getPaid() != null && pgpPublicKeyData.getPaid()) {
        // <<<
        throw new Exception("Verification of key " + fingerprint + " already paid");
    }
    // 
    String nameOnCard;
    if (pgpPublicKeyData.getNameOnCard() != null) {
        nameOnCard = pgpPublicKeyData.getNameOnCard();
    } else if (!stripePaymentForm.getCardHolderFirstName().equalsIgnoreCase(pgpPublicKeyData.getFirstName()) || !stripePaymentForm.getCardHolderLastName().equalsIgnoreCase(pgpPublicKeyData.getLastName())) {
        throw new Exception("You have to pay with credit card with the same first and last name as in your OpenPGP key." + " If your card has different spelling of your name than passport," + " please write to support@cryptonomica.net " + "(include spelling of your name in passport and on the card," + " but do not send card number or CVC via email)");
    } else {
        nameOnCard = pgpPublicKeyData.getFirstName() + " " + pgpPublicKeyData.getLastName();
    }
    // make code for payment:
    final String chargeCode = RandomStringUtils.randomNumeric(7);
    // 
    LOG.warning("chargeCode: " + chargeCode);
    // calculate price for key verification
    Integer price = calculatePriceForKeyVerification(pgpPublicKeyData);
    /* --- process payment */
    // see example on:
    // https://github.com/stripe/stripe-java#usage
    RequestOptions requestOptions = (new RequestOptions.RequestOptionsBuilder()).setApiKey(STRIPE_SECRET_KEY).build();
    // --- cardMap
    Map<String, Object> cardMap = new HashMap<>();
    // String
    cardMap.put("number", stripePaymentForm.getCardNumber());
    // Integer
    cardMap.put("exp_month", stripePaymentForm.getCardExpMonth());
    // Integer
    cardMap.put("exp_year", stripePaymentForm.getCardExpYear());
    cardMap.put("name", nameOnCard);
    // --- chargeMap
    Map<String, Object> chargeMap = new HashMap<>();
    chargeMap.put("card", cardMap);
    // amount - a positive integer in the smallest currency unit (e.g., 100 cents to charge $1.00
    // 
    chargeMap.put("amount", price);
    // 
    chargeMap.put("currency", "usd");
    // https://stripe.com/docs/api/java#create_charge-statement_descriptor
    // An arbitrary string to be displayed on your customer's credit card statement.
    // This may be up to 22 characters. As an 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.
    // The statement description may not include <>"' characters, and will appear on your customer's statement in
    // capital letters. Non-ASCII characters are automatically stripped.
    // While most banks display this information consistently, some may display it incorrectly or not at all.
    chargeMap.put("statement_descriptor", // 13 characters
    "CRYPTONOMICA " + // 7 characters
    chargeCode);
    // https://stripe.com/docs/api/java#create_charge-description
    // An arbitrary string which you can attach to a charge object.
    // It is displayed when in the web interface alongside the charge.
    // Note that if you use Stripe to send automatic email receipts to your customers,
    // your receipt emails will include the description of the charge(s) that they are describing.
    chargeMap.put("description", "Key " + pgpPublicKeyData.getKeyID() + " verification");
    // https://stripe.com/docs/api/java#create_charge-receipt_email
    // The email address to send this charge's receipt to.
    // The receipt will not be sent until the charge is paid.
    // If this charge is for a customer, the email address specified here will override the customer's email address.
    // Receipts will not be sent for test mode charges.
    // If receipt_email is specified for a charge in live mode, a receipt will be sent regardless of your email settings.
    chargeMap.put("receipt_email", cryptonomicaUser.getEmail().getEmail());
    // -- get Charge object:
    Charge charge = Charge.create(chargeMap, requestOptions);
    // Charge obj has custom toString()
    String chargeStr = charge.toString();
    LOG.warning("chargeStr: " + chargeStr);
    String chargeJsonStr = GSON.toJson(charge);
    LOG.warning("chargeJsonStr: " + chargeJsonStr);
    if (charge.getStatus().equalsIgnoreCase("succeeded")) {
        stripePaymentReturn.setResult(true);
        stripePaymentReturn.setMessageToUser("Payment succeeded");
    } else {
        stripePaymentReturn.setResult(false);
        stripePaymentReturn.setMessageToUser("Payment not succeeded");
    }
    // create and store payment information
    StripePaymentForKeyVerification stripePaymentForKeyVerification = new StripePaymentForKeyVerification();
    stripePaymentForKeyVerification.setChargeId(charge.getId());
    stripePaymentForKeyVerification.setChargeJsonStr(chargeJsonStr);
    stripePaymentForKeyVerification.setChargeStr(chargeStr);
    stripePaymentForKeyVerification.setFingerprint(fingerprint);
    stripePaymentForKeyVerification.setCryptonomicaUserId(cryptonomicaUser.getUserId());
    stripePaymentForKeyVerification.setUserEmail(cryptonomicaUser.getEmail());
    stripePaymentForKeyVerification.setPaymentVerificationCode(chargeCode);
    Key<CryptonomicaUser> cryptonomicaUserKey = Key.create(CryptonomicaUser.class, googleUser.getUserId());
    Key<Login> loginKey = Key.create(cryptonomicaUserKey, Login.class, login.getId());
    stripePaymentForKeyVerification.setChargeLogin(loginKey);
    Key<StripePaymentForKeyVerification> entityKey = ofy().save().entity(stripePaymentForKeyVerification).now();
    LOG.warning("StripePaymentForKeyVerification saved: " + // has custom toString()
    entityKey.toString());
    // add data to OnlineVerification entity:
    OnlineVerification onlineVerification = ofy().load().key(Key.create(OnlineVerification.class, fingerprint)).now();
    if (onlineVerification == null) {
        LOG.severe("OnlineVerification record not found in data base");
    }
    try {
        // onlineVerification.setPaimentMade(Boolean.TRUE);
        onlineVerification.setPaymentMade(Boolean.TRUE);
        onlineVerification.setStripePaymentForKeyVerificationId(stripePaymentForKeyVerification.getId());
        ofy().save().entity(onlineVerification).now();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return stripePaymentReturn;
}
Also used : RequestOptions(com.stripe.net.RequestOptions) Charge(com.stripe.model.Charge) NotFoundException(com.google.api.server.spi.response.NotFoundException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Aggregations

RequestOptions (com.stripe.net.RequestOptions)29 Test (org.junit.Test)19 BaseStripeFunctionalTest (com.stripe.BaseStripeFunctionalTest)12 Charge (com.stripe.model.Charge)12 HashMap (java.util.HashMap)11 BaseStripeTest (com.stripe.BaseStripeTest)5 RequestOptionsBuilder (com.stripe.net.RequestOptions.RequestOptionsBuilder)4 PaymentInformation (alfio.model.PaymentInformation)3 DeletedProduct (com.stripe.model.DeletedProduct)2 DeletedSKU (com.stripe.model.DeletedSKU)2 Product (com.stripe.model.Product)2 Refund (com.stripe.model.Refund)2 SKU (com.stripe.model.SKU)2 FeeCalculator (alfio.manager.support.FeeCalculator)1 PaymentResult (alfio.manager.support.PaymentResult)1 ConfigurationManager (alfio.manager.system.ConfigurationManager)1 UserManager (alfio.manager.user.UserManager)1 Configurable (alfio.model.Configurable)1 PurchaseContext (alfio.model.PurchaseContext)1 PurchaseContextType (alfio.model.PurchaseContext.PurchaseContextType)1