Search in sources :

Example 26 with Charge

use of com.stripe.model.Charge 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)

Example 27 with Charge

use of com.stripe.model.Charge in project cryptonomica by Cryptonomica.

the class StripeTestServlet method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /* --- request*/
    String requestDataStr = ServletUtils.getAllRequestData(request);
    String responseStr = "{\"paymentData\":" + requestDataStr + ",";
    // Get the credit card details submitted by the form
    String token = request.getParameter("stripeToken");
    @SuppressWarnings("unused") String cardHolderName = request.getParameter("cardHolderName");
    /* -- see example on: https://github.com/stripe/stripe-java#usage */
    // 
    RequestOptions requestOptions = (new RequestOptions.RequestOptionsBuilder()).setApiKey(STRIPE_SECRET_KEY).build();
    // 
    // -- Card options:
    // ------------ // Map<String, Object> cardMap = new HashMap<>();
    // cardMap.put("name", cardHolderName);// - "Received both card and source parameters. Please pass in only one."
    /*
        cardMap.put("number", "4242424242424242");
        cardMap.put("exp_month", 12);
        cardMap.put("exp_year", 2020);
        */
    // -- Charge options:
    Map<String, Object> chargeMap = new HashMap<>();
    // -- this is ONE dollar
    chargeMap.put("amount", 100);
    chargeMap.put("currency", "usd");
    // see: https://stripe.com/docs/charges (Java)
    // chargeParams.put("source", token);
    // chargeParams.put("description", "Example charge");
    chargeMap.put("source", token);
    chargeMap.put("description", "Example charge: " + token);
    // 
    // ------------ // chargeMap.put("card", cardMap);
    // -- make charge:
    responseStr += "\"charge\":";
    try {
        Charge charge = Charge.create(chargeMap, requestOptions);
        // System.out.println(charge);
        responseStr += GSON.toJson(charge);
        LOG.warning(GSON.toJson(charge));
        ExternalAccount source = charge.getSource();
        LOG.warning("source: " + GSON.toJson(source));
        // -- "succeeded"
        charge.getStatus();
        // - boolean: true or false
        charge.getPaid();
    // 
    // String customerStr = source.getCustomer();
    // LOG.warning("customerStr: " + customerStr); //
    // responseStr += "," + "\"customerStr\":" + GSON.toJson(charge); // - same as source
    } catch (StripeException e) {
        String errorMessage = e.getMessage();
        responseStr += "\"";
        responseStr += errorMessage;
        responseStr += "\"";
        LOG.warning(errorMessage);
    }
    responseStr += "}";
    ServletUtils.sendJsonResponse(response, responseStr);
}
Also used : StripeException(com.stripe.exception.StripeException) RequestOptions(com.stripe.net.RequestOptions) HashMap(java.util.HashMap) Charge(com.stripe.model.Charge) ExternalAccount(com.stripe.model.ExternalAccount)

Example 28 with Charge

use of com.stripe.model.Charge in project alf.io by alfio-event.

the class BaseStripeManager method charge.

protected Optional<Charge> charge(PaymentSpecification spec, Map<String, Object> chargeParams) throws StripeException {
    Optional<RequestOptions> opt = options(spec.getPurchaseContext(), builder -> builder.setIdempotencyKey(spec.getReservationId()));
    if (opt.isEmpty()) {
        return Optional.empty();
    }
    RequestOptions options = opt.get();
    Charge charge = Charge.create(chargeParams, options);
    if (charge.getBalanceTransactionObject() == null) {
        try {
            charge.setBalanceTransactionObject(retrieveBalanceTransaction(charge.getBalanceTransaction(), options));
        } catch (Exception e) {
            log.warn("can't retrieve balance transaction", e);
        }
    }
    return Optional.of(charge);
}
Also used : RequestOptions(com.stripe.net.RequestOptions) Charge(com.stripe.model.Charge)

Example 29 with Charge

use of com.stripe.model.Charge in project alf.io by alfio-event.

the class BaseStripeManager method refund.

// https://stripe.com/docs/api#create_refund
boolean refund(Transaction transaction, PurchaseContext purchaseContext, Integer amountToRefund) {
    Optional<Integer> amount = Optional.ofNullable(amountToRefund);
    String chargeId = transaction.getTransactionId();
    try {
        String amountOrFull = amount.map(p -> MonetaryUtil.formatCents(p, transaction.getCurrency())).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 (transaction.getPlatformFee() > 0 && isConnectEnabled(new PaymentContext(purchaseContext))) {
            params.put("refund_application_fee", true);
        }
        Optional<RequestOptions> requestOptionsOptional = options(purchaseContext);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Refund r = Refund.create(params, options);
            boolean pending = PENDING.equals(r.getStatus());
            if (SUCCEEDED.equals(r.getStatus()) || pending) {
                log.info("Stripe: refund for payment {} {} for amount: {}", chargeId, pending ? "registered" : "executed with success", 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 : Transaction(alfio.model.transaction.Transaction) RequestOptions(com.stripe.net.RequestOptions) java.util(java.util) PaymentProxy(alfio.model.transaction.PaymentProxy) PaymentResult(alfio.manager.support.PaymentResult) PurchaseContext(alfio.model.PurchaseContext) PurchaseContextType(alfio.model.PurchaseContext.PurchaseContextType) UnaryOperator(java.util.function.UnaryOperator) ConfigurationManager(alfio.manager.system.ConfigurationManager) PaymentInformation(alfio.model.PaymentInformation) Charge(com.stripe.model.Charge) Profiles(org.springframework.core.env.Profiles) Configurable(alfio.model.Configurable) Refund(com.stripe.model.Refund) TicketRepository(alfio.repository.TicketRepository) Predicate(java.util.function.Predicate) FeeCalculator(alfio.manager.support.FeeCalculator) PaymentMethod(alfio.model.transaction.PaymentMethod) Stripe(com.stripe.Stripe) ErrorsCode(alfio.util.ErrorsCode) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) PaymentContext(alfio.model.transaction.PaymentContext) MonetaryUtil(alfio.util.MonetaryUtil) Environment(org.springframework.core.env.Environment) UserManager(alfio.manager.user.UserManager) Log4j2(lombok.extern.log4j.Log4j2) ConfigurationPathLevel(alfio.model.system.ConfigurationPathLevel) com.stripe.exception(com.stripe.exception) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) BalanceTransaction(com.stripe.model.BalanceTransaction) Webhook(com.stripe.net.Webhook) RequestOptions(com.stripe.net.RequestOptions) PaymentContext(alfio.model.transaction.PaymentContext) Refund(com.stripe.model.Refund)

Example 30 with Charge

use of com.stripe.model.Charge in project alf.io by alfio-event.

the class StripeWebhookPaymentManager method parseTransactionPayload.

@Override
public Optional<TransactionWebhookPayload> parseTransactionPayload(String body, String signature, Map<String, String> additionalInfo, PaymentContext paymentContext) {
    try {
        var stripeEvent = Webhook.constructEvent(body, signature, getWebhookSignatureKey(paymentContext.getConfigurationLevel()));
        String eventType = stripeEvent.getType();
        if (eventType.startsWith("charge.")) {
            return deserializeObject(stripeEvent).map(obj -> new StripeChargeTransactionWebhookPayload(eventType, (Charge) obj));
        } else if (eventType.startsWith("payment_intent.")) {
            return deserializeObject(stripeEvent).map(obj -> new StripePaymentIntentWebhookPayload(eventType, (PaymentIntent) obj));
        }
        return Optional.empty();
    } catch (Exception e) {
        log.error("got exception while handling stripe webhook", e);
        return Optional.empty();
    }
}
Also used : alfio.repository(alfio.repository) java.util(java.util) ConfigurationLevel(alfio.manager.system.ConfigurationLevel) ZonedDateTime(java.time.ZonedDateTime) PaymentResult(alfio.manager.support.PaymentResult) PurchaseContext(alfio.model.PurchaseContext) ConfigurationManager(alfio.manager.system.ConfigurationManager) JsonParser(com.google.gson.JsonParser) PaymentInformation(alfio.model.PaymentInformation) Charge(com.stripe.model.Charge) alfio.model.transaction.capabilities(alfio.model.transaction.capabilities) PaymentIntent(com.stripe.model.PaymentIntent) alfio.model.transaction(alfio.model.transaction) StripeChargeTransactionWebhookPayload(alfio.model.transaction.webhook.StripeChargeTransactionWebhookPayload) StripePaymentIntentWebhookPayload(alfio.model.transaction.webhook.StripePaymentIntentWebhookPayload) StripeException(com.stripe.exception.StripeException) Stripe(com.stripe.Stripe) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) Audit(alfio.model.Audit) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) StringReader(java.io.StringReader) StripeSCACreditCardToken(alfio.model.transaction.token.StripeSCACreditCardToken) Environment(org.springframework.core.env.Environment) STRIPE_MANAGER_TYPE_KEY(alfio.manager.payment.BaseStripeManager.STRIPE_MANAGER_TYPE_KEY) TicketReservation(alfio.model.TicketReservation) Log4j2(lombok.extern.log4j.Log4j2) PaymentWebhookResult(alfio.manager.support.PaymentWebhookResult) StripeObject(com.stripe.model.StripeObject) ClockProvider(alfio.util.ClockProvider) EXTERNAL_PROCESSING_PAYMENT(alfio.model.TicketReservation.TicketReservationStatus.EXTERNAL_PROCESSING_PAYMENT) ConfigurationKeys(alfio.model.system.ConfigurationKeys) WAITING_EXTERNAL_CONFIRMATION(alfio.model.TicketReservation.TicketReservationStatus.WAITING_EXTERNAL_CONFIRMATION) BalanceTransaction(com.stripe.model.BalanceTransaction) Webhook(com.stripe.net.Webhook) Transactional(org.springframework.transaction.annotation.Transactional) StripeChargeTransactionWebhookPayload(alfio.model.transaction.webhook.StripeChargeTransactionWebhookPayload) StripePaymentIntentWebhookPayload(alfio.model.transaction.webhook.StripePaymentIntentWebhookPayload) Charge(com.stripe.model.Charge) StripeException(com.stripe.exception.StripeException)

Aggregations

Charge (com.stripe.model.Charge)49 BaseStripeFunctionalTest (com.stripe.BaseStripeFunctionalTest)36 Test (org.junit.Test)36 HashMap (java.util.HashMap)19 RequestOptions (com.stripe.net.RequestOptions)12 Refund (com.stripe.model.Refund)8 Dispute (com.stripe.model.Dispute)7 Card (com.stripe.model.Card)5 EvidenceSubObject (com.stripe.model.EvidenceSubObject)5 Environment (org.springframework.core.env.Environment)5 PaymentResult (alfio.manager.support.PaymentResult)4 PaymentInformation (alfio.model.PaymentInformation)4 StripeException (com.stripe.exception.StripeException)3 BalanceTransaction (com.stripe.model.BalanceTransaction)3 ConfigurationManager (alfio.manager.system.ConfigurationManager)2 PurchaseContext (alfio.model.PurchaseContext)2 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 StripeCreditCardToken (alfio.model.transaction.token.StripeCreditCardToken)2 ConfigurationRepository (alfio.repository.system.ConfigurationRepository)2 Stripe (com.stripe.Stripe)2