В этой короткой серии мы рассмотрим, как создать плату для Stripe на ряде их официально поддерживаемых языков!
В этой статье мы рассмотрим, как это сделать с помощью Java и Spring.
Ожидается, что у вас установлена Java и ваши ключи API Stripe настроены и готовы к работе, и что у вас есть общее представление о том, как работает Gradle.
Следующее частично взято с моего веб-сайта документации .
Установка
mkdir hello-spring-stripe && cd hello-spring-stripe mkdir -p src/main/java/stripe touch build.gradle src/main/java/stripe/StripeCharge.java src/main/java/stripe/StripeChageController.java src/main/java/stripe/Application.java .env # init gradle gradle wrapper
Настройка сборки.градация
Добавьте следующее для полосы + Весна:
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.2.1.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' bootJar { baseName = 'hello-spring-jar' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("com.stripe:stripe-java:16.5.1") compile("org.springframework.boot:spring-boot-starter-web") compile("io.github.cdimascio:java-dotenv:5.1.3") testCompile('org.springframework.boot:spring-boot-starter-test') }
Настройка файла dotenv
Мы используем локальный файл dotenv для этого “Привет, мир!” пример уровня.
# required SK_TEST_KEY=sk_... # not required PK_TEST_KEY=pk_...
Настройка основного приложения
В приложении src/main/java/stripe/.java
, добавьте следующее:
package stripecharge; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Настройка модели
В src/main/java/stripe/StripeCharge.java
:
package stripecharge; import java.util.HashMap; import java.util.Map; public class StripeCharge { private final long amount; private final String receiptEmail; private final String source; private final String currency; public StripeCharge(long amount, String receiptEmail) { this.amount = amount; this.source = "tok_visa"; this.currency = "aud"; this.receiptEmail = receiptEmail; } public MapgetCharge() { Map params = new HashMap (); params.put("amount", this.amount); params.put("currency", this.currency); // source should obtained with Stripe.js params.put("source", this.source); params.put( "description", "My First Test Charge (created for API docs)" ); params.put("receipt_email",this.receiptEmail); return params; } }
Настройка контроллера
В src/main/java/stripe/StripeChargeController.java
:
package stripecharge; // NOTE: RequestMapping + RequestParam not required for this demo // but kept in for reference purposes if wanted to play around later import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.http.ResponseEntity; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RestController; import io.github.cdimascio.dotenv.Dotenv; import com.stripe.Stripe; import com.stripe.exception.StripeException; import com.stripe.model.Charge; import com.stripe.net.RequestOptions; @RestController @RequestMapping("/api") public class StripeChargeController { @PostMapping("/charge") public ResponseEntitycreateCharge(@RequestBody StripeCharge stripeCharge) { try { // for demonstrations sake, using .env file Dotenv dotenv = Dotenv.load(); // creating the charge Stripe.apiKey = dotenv.get("SK_TEST_KEY"); Charge charge = Charge.create(stripeCharge.getCharge()); System.out.println(charge); return new ResponseEntity ("Success", HttpStatus.CREATED); } catch (StripeException e) { e.printStackTrace(); return new ResponseEntity ("Failure", HttpStatus.INTERNAL_SERVER_ERROR); } } }
Сборка, запуск и пинг
Запустите ./gradlew build
для сборки в проект или ./gradlew загрузочный запуск
для сборки и запуска.
Как только проект будет запущен, мы сможем отправить сообщение http http://localhost:8080/api/charge@example.com
(используя HTTPie), и мы получаем ответ, подобный следующему:
HTTP/1.1 201 Content-Length: 7 Content-Type: application/json;charset=UTF-8 Date: Sun, 12 Jan 2020 03:33:10 GMT Success
Я решил использовать HTTPie, потому что чувствую, что это забавный инструмент, о котором нужно знать больше! В качестве альтернативы вы могли бы сделать вышеописанное с помощью curl
(или чего-либо, что может сделать запрос POST на самом деле).
curl --header "Content-Type: application/json" \ --request POST \ --data '{"amount":1700,"receipt_email":"hello_spring@example.com"}' \ http://localhost:8080/api/charge
Если вы сейчас зайдете и проверите свою панель управления Stripe, вы сможете увидеть плату.
Ресурсы и дальнейшее чтение
- Вступительные документы для выпускников
- Весенний путеводитель по услугам отдыха
- API полосы пропускания
- Полоса с пружиной
- Использование Java Stripe на Github
- Способность к весеннему отклику
- Пункт руководства: Сервисные компоненты
- Базовый файл Gitignore для весенней загрузки
Кредит на изображение: Джио Бартлетт
Первоначально опубликовано на моем блог . Следите за мной в Твиттере, чтобы узнать больше скрытых драгоценных камней @dennisokeeffe92 деннисокэффе92 .
Оригинал: “https://dev.to/okeeffed/your-first-stripe-charge-with-java-spring-in-5-minutes-1oaj”