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;
}
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);
}
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);
}
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;
}
}
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();
}
}
Aggregations