1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-17 06:52:27 +01:00

WIP: create the formToken server-side

This commit is contained in:
Sylvain 2021-04-09 17:17:58 +02:00
parent fe5c4e6233
commit 23032c405b
11 changed files with 272 additions and 203 deletions

View File

@ -4,188 +4,7 @@
class API::PaymentsController < API::ApiController
before_action :authenticate_user!
##
# Client requests to confirm a card payment will ask this endpoint.
# It will check for the need of a strong customer authentication (SCA) to confirm the payment or confirm that the payment
# was successfully made. After the payment was made, the reservation/subscription will be created
##
def confirm_payment
render(json: { error: 'Online payment is disabled' }, status: :unauthorized) and return unless Setting.get('online_payment_module')
amount = nil # will contains the amount and the details of each invoice lines
intent = nil # stripe's payment intent
res = nil # json of the API answer
begin
amount = card_amount
if params[:payment_method_id].present?
check_coupon
check_plan
# Create the PaymentIntent
intent = Stripe::PaymentIntent.create(
{
payment_method: params[:payment_method_id],
amount: amount[:amount],
currency: Setting.get('stripe_currency'),
confirmation_method: 'manual',
confirm: true,
customer: current_user.stp_customer_id
}, { api_key: Setting.get('stripe_secret_key') }
)
elsif params[:payment_intent_id].present?
intent = Stripe::PaymentIntent.confirm(params[:payment_intent_id], api_key: Setting.get('stripe_secret_key'))
end
rescue Stripe::CardError => e
# Display error on client
res = { status: 200, json: { error: e.message } }
rescue InvalidCouponError
res = { json: { coupon_code: 'wrong coupon code or expired' }, status: :unprocessable_entity }
rescue InvalidGroupError
res = { json: { plan_id: 'this plan is not compatible with your current group' }, status: :unprocessable_entity }
end
if intent&.status == 'succeeded'
if params[:cart_items][:reservation]
res = on_reservation_success(intent, amount[:details])
elsif params[:cart_items][:subscription]
res = on_subscription_success(intent, amount[:details])
end
end
render generate_payment_response(intent, res)
end
def online_payment_status
authorize :payment
key = Setting.get('stripe_secret_key')
render json: { status: false } and return unless key&.present?
charges = Stripe::Charge.list({ limit: 1 }, { api_key: key })
render json: { status: charges.data.length.positive? }
rescue Stripe::AuthenticationError
render json: { status: false }
end
def setup_intent
user = User.find(params[:user_id])
key = Setting.get('stripe_secret_key')
@intent = Stripe::SetupIntent.create({ customer: user.stp_customer_id }, { api_key: key })
render json: { id: @intent.id, client_secret: @intent.client_secret }
end
def confirm_payment_schedule
key = Setting.get('stripe_secret_key')
intent = Stripe::SetupIntent.retrieve(params[:setup_intent_id], api_key: key)
amount = card_amount
if intent&.status == 'succeeded'
if params[:cart_items][:reservation]
res = on_reservation_success(intent, amount[:details])
elsif params[:cart_items][:subscription]
res = on_subscription_success(intent, amount[:details])
end
end
render generate_payment_response(intent, res)
rescue Stripe::InvalidRequestError => e
render json: e, status: :unprocessable_entity
end
def update_card
user = User.find(params[:user_id])
key = Setting.get('stripe_secret_key')
Stripe::Customer.update(user.stp_customer_id,
{ invoice_settings: { default_payment_method: params[:payment_method_id] } },
{ api_key: key })
render json: { updated: true }, status: :ok
rescue Stripe::StripeError => e
render json: { updated: false, error: e }, status: :unprocessable_entity
end
private
def on_reservation_success(intent, details)
@reservation = Reservation.new(reservation_params)
payment_method = params[:cart_items][:reservation][:payment_method] || 'stripe'
user_id = if current_user.admin? || current_user.manager?
params[:cart_items][:reservation][:user_id]
else
current_user.id
end
is_reserve = Reservations::Reserve.new(user_id, current_user.invoicing_profile.id)
.pay_and_save(@reservation,
payment_details: details,
intent_id: intent.id,
schedule: params[:cart_items][:reservation][:payment_schedule],
payment_method: payment_method)
if intent.class == Stripe::PaymentIntent
Stripe::PaymentIntent.update(
intent.id,
{ description: "Invoice reference: #{@reservation.invoice.reference}" },
{ api_key: Setting.get('stripe_secret_key') }
)
end
if is_reserve
SubscriptionExtensionAfterReservation.new(@reservation).extend_subscription_if_eligible
{ template: 'api/reservations/show', status: :created, location: @reservation }
else
{ json: @reservation.errors, status: :unprocessable_entity }
end
end
def on_subscription_success(intent, details)
@subscription = Subscription.new(subscription_params)
user_id = if current_user.admin? || current_user.manager?
params[:cart_items][:subscription][:user_id]
else
current_user.id
end
is_subscribe = Subscriptions::Subscribe.new(current_user.invoicing_profile.id, user_id)
.pay_and_save(@subscription,
payment_details: details,
intent_id: intent.id,
schedule: params[:cart_items][:subscription][:payment_schedule],
payment_method: 'stripe')
if intent.class == Stripe::PaymentIntent
Stripe::PaymentIntent.update(
intent.id,
{ description: "Invoice reference: #{@subscription.invoices.first.reference}" },
{ api_key: Setting.get('stripe_secret_key') }
)
end
if is_subscribe
{ template: 'api/subscriptions/show', status: :created, location: @subscription }
else
{ json: @subscription.errors, status: :unprocessable_entity }
end
end
def generate_payment_response(intent, res = nil)
return res unless res.nil?
if intent.status == 'requires_action' && intent.next_action.type == 'use_stripe_sdk'
# Tell the client to handle the action
{
status: 200,
json: {
requires_action: true,
payment_intent_client_secret: intent.client_secret
}
}
elsif intent.status == 'succeeded'
# The payment didn't need any additional actions and is completed!
# Handle post-payment fulfillment
{ status: 200, json: { success: true } }
else
# Invalid status
{ status: 500, json: { error: 'Invalid PaymentIntent status' } }
end
end
protected
def get_wallet_debit(user, total_amount)
wallet_amount = (user.wallet.amount * 100).to_i

View File

@ -1,8 +1,7 @@
# frozen_string_literal: true
# API Controller for accessing PayZen API endpoints through the front-end app
class API::PayzenController < API::ApiController
before_action :authenticate_user!
class API::PayzenController < API::PaymentsController
require 'pay_zen/charge'
def sdk_test
@ -15,4 +14,11 @@ class API::PayzenController < API::ApiController
rescue SocketError
@status = false
end
def create_payment
amount = card_amount
client = PayZen::Charge.new
@result = client.create_payment(amount: amount, customer: { reference: params[:customer][:id], email: params[:customer][:email] })
end
end

View File

@ -0,0 +1,188 @@
# frozen_string_literal: true
# API Controller for handling payments process in the front-end
class API::StripeController < API::PaymentsController
##
# Client requests to confirm a card payment will ask this endpoint.
# It will check for the need of a strong customer authentication (SCA) to confirm the payment or confirm that the payment
# was successfully made. After the payment was made, the reservation/subscription will be created
##
def confirm_payment
render(json: { error: 'Online payment is disabled' }, status: :unauthorized) and return unless Setting.get('online_payment_module')
amount = nil # will contains the amount and the details of each invoice lines
intent = nil # stripe's payment intent
res = nil # json of the API answer
begin
amount = card_amount
if params[:payment_method_id].present?
check_coupon
check_plan
# Create the PaymentIntent
intent = Stripe::PaymentIntent.create(
{
payment_method: params[:payment_method_id],
amount: amount[:amount],
currency: Setting.get('stripe_currency'),
confirmation_method: 'manual',
confirm: true,
customer: current_user.stp_customer_id
}, { api_key: Setting.get('stripe_secret_key') }
)
elsif params[:payment_intent_id].present?
intent = Stripe::PaymentIntent.confirm(params[:payment_intent_id], api_key: Setting.get('stripe_secret_key'))
end
rescue Stripe::CardError => e
# Display error on client
res = { status: 200, json: { error: e.message } }
rescue InvalidCouponError
res = { json: { coupon_code: 'wrong coupon code or expired' }, status: :unprocessable_entity }
rescue InvalidGroupError
res = { json: { plan_id: 'this plan is not compatible with your current group' }, status: :unprocessable_entity }
end
if intent&.status == 'succeeded'
if params[:cart_items][:reservation]
res = on_reservation_success(intent, amount[:details])
elsif params[:cart_items][:subscription]
res = on_subscription_success(intent, amount[:details])
end
end
render generate_payment_response(intent, res)
end
def online_payment_status
authorize :payment
key = Setting.get('stripe_secret_key')
render json: { status: false } and return unless key&.present?
charges = Stripe::Charge.list({ limit: 1 }, { api_key: key })
render json: { status: charges.data.length.positive? }
rescue Stripe::AuthenticationError
render json: { status: false }
end
def setup_intent
user = User.find(params[:user_id])
key = Setting.get('stripe_secret_key')
@intent = Stripe::SetupIntent.create({ customer: user.stp_customer_id }, { api_key: key })
render json: { id: @intent.id, client_secret: @intent.client_secret }
end
def confirm_payment_schedule
key = Setting.get('stripe_secret_key')
intent = Stripe::SetupIntent.retrieve(params[:setup_intent_id], api_key: key)
amount = card_amount
if intent&.status == 'succeeded'
if params[:cart_items][:reservation]
res = on_reservation_success(intent, amount[:details])
elsif params[:cart_items][:subscription]
res = on_subscription_success(intent, amount[:details])
end
end
render generate_payment_response(intent, res)
rescue Stripe::InvalidRequestError => e
render json: e, status: :unprocessable_entity
end
def update_card
user = User.find(params[:user_id])
key = Setting.get('stripe_secret_key')
Stripe::Customer.update(user.stp_customer_id,
{ invoice_settings: { default_payment_method: params[:payment_method_id] } },
{ api_key: key })
render json: { updated: true }, status: :ok
rescue Stripe::StripeError => e
render json: { updated: false, error: e }, status: :unprocessable_entity
end
private
def on_reservation_success(intent, details)
@reservation = Reservation.new(reservation_params)
payment_method = params[:cart_items][:reservation][:payment_method] || 'stripe'
user_id = if current_user.admin? || current_user.manager?
params[:cart_items][:reservation][:user_id]
else
current_user.id
end
is_reserve = Reservations::Reserve.new(user_id, current_user.invoicing_profile.id)
.pay_and_save(@reservation,
payment_details: details,
intent_id: intent.id,
schedule: params[:cart_items][:reservation][:payment_schedule],
payment_method: payment_method)
if intent.class == Stripe::PaymentIntent
Stripe::PaymentIntent.update(
intent.id,
{ description: "Invoice reference: #{@reservation.invoice.reference}" },
{ api_key: Setting.get('stripe_secret_key') }
)
end
if is_reserve
SubscriptionExtensionAfterReservation.new(@reservation).extend_subscription_if_eligible
{ template: 'api/reservations/show', status: :created, location: @reservation }
else
{ json: @reservation.errors, status: :unprocessable_entity }
end
end
def on_subscription_success(intent, details)
@subscription = Subscription.new(subscription_params)
user_id = if current_user.admin? || current_user.manager?
params[:cart_items][:subscription][:user_id]
else
current_user.id
end
is_subscribe = Subscriptions::Subscribe.new(current_user.invoicing_profile.id, user_id)
.pay_and_save(@subscription,
payment_details: details,
intent_id: intent.id,
schedule: params[:cart_items][:subscription][:payment_schedule],
payment_method: 'stripe')
if intent.class == Stripe::PaymentIntent
Stripe::PaymentIntent.update(
intent.id,
{ description: "Invoice reference: #{@subscription.invoices.first.reference}" },
{ api_key: Setting.get('stripe_secret_key') }
)
end
if is_subscribe
{ template: 'api/subscriptions/show', status: :created, location: @subscription }
else
{ json: @subscription.errors, status: :unprocessable_entity }
end
end
def generate_payment_response(intent, res = nil)
return res unless res.nil?
if intent.status == 'requires_action' && intent.next_action.type == 'use_stripe_sdk'
# Tell the client to handle the action
{
status: 200,
json: {
requires_action: true,
payment_intent_client_secret: intent.client_secret
}
}
elsif intent.status == 'succeeded'
# The payment didn't need any additional actions and is completed!
# Handle post-payment fulfillment
{ status: 200, json: { success: true } }
else
# Invalid status
{ status: 500, json: { error: 'Invalid PaymentIntent status' } }
end
end
end

View File

@ -1,10 +1,18 @@
import apiClient from './api-client';
import { AxiosResponse } from 'axios';
import { CartItems } from '../models/payment';
import { User } from '../models/user';
import { CreatePaymentResponse, SdkTestResponse } from '../models/payzen';
export default class PayzenAPI {
static async chargeSDKTest(baseURL: string, username: string, password: string): Promise<any> {
static async chargeSDKTest(baseURL: string, username: string, password: string): Promise<SdkTestResponse> {
const res: AxiosResponse = await apiClient.post('/api/payzen/sdk_test', { base_url: baseURL, username, password });
return res?.data;
}
static async chargeCreatePayment(cart_items: CartItems, customer: User): Promise<CreatePaymentResponse> {
const res: AxiosResponse = await apiClient.post('/api/payzen/create_payment', { cart_items, customer: { id: customer.id, email: customer.email } });
return res?.data;
}
}

View File

@ -5,6 +5,7 @@ import { CartItems } from '../../../models/payment';
import { User } from '../../../models/user';
import SettingAPI from '../../../api/setting';
import { SettingName } from '../../../models/setting';
import PayzenAPI from '../../../api/payzen';
interface PayzenFormProps {
onSubmit: () => void,
@ -29,25 +30,31 @@ export const PayzenForm: React.FC<PayzenFormProps> = ({ onSubmit, onSuccess, onE
useEffect(() => {
const api = new SettingAPI();
api.query([SettingName.PayZenEndpoint, SettingName.PayZenPublicKey]).then(settings => {
const formToken = "DEMO-TOKEN-TO-BE-REPLACED";
KRGlue.loadLibrary(settings.get(SettingName.PayZenEndpoint), settings.get(SettingName.PayZenPublicKey)) /* Load the remote library */
.then(({ KR }) =>
KR.setFormConfig({
/* set the minimal configuration */
formToken: formToken,
"kr-language": "en-US" /* to update initialization parameter */
})
)
.then(({ KR }) =>
KR.addForm("#payzenPaymentForm")
) /* add a payment form to myPaymentForm div*/
.then(({ KR, result }) =>
KR.showForm(result.formId)
); /* show the payment form */
}).catch(error => console.error(error));
PayzenAPI.chargeCreatePayment(cartItems, customer).then(formToken => {
KRGlue.loadLibrary(settings.get(SettingName.PayZenEndpoint), settings.get(SettingName.PayZenPublicKey)) /* Load the remote library */
.then(({ KR }) =>
KR.setFormConfig({
/* set the minimal configuration */
formToken: formToken.formToken,
"kr-language": "en-US" /* to update initialization parameter */
})
)
.then(({ KR }) =>
KR.addForm("#payzenPaymentForm")
) /* add a payment form to myPaymentForm div*/
.then(({ KR, result }) =>
KR.showForm(result.formId)
); /* show the payment form */
}).catch(error => console.error(error));
})
});
const submitEmbeddedPayzenForm = (): void => {
// FIXME: not working...
const button: HTMLButtonElement = document.querySelector('button.kr-payment-button');
button.click()
}
/**
* Handle the submission of the form.
*/
@ -57,6 +64,7 @@ export const PayzenForm: React.FC<PayzenFormProps> = ({ onSubmit, onSuccess, onE
try {
submitEmbeddedPayzenForm();
onSuccess(null);
} catch (err) {
// catch api errors

View File

@ -52,6 +52,7 @@ export const PayZenModal: React.FC<PayZenModalProps> = ({ isOpen, toggleModal, a
customer={customer}
operator={operator}
formId={formId}
cartItems={cartItems}
className={className}
paymentSchedule={paymentSchedule}>
{children}

View File

@ -0,0 +1,7 @@
export interface SdkTestResponse {
success: boolean
}
export interface CreatePaymentResponse {
formToken: string
}

View File

@ -1,7 +1,17 @@
.payzen-modal {
.payzen-form {
.container {
display: flex; justify-content: center;
display: flex;
justify-content: center;
width: inherit;
//.kr-payment-button {
// display: none;
//}
.kr-form-error {
display: none;
}
}
}
.payzen-modal-icons {

View File

@ -0,0 +1,3 @@
# frozen_string_literal: true
json.formToken @result['answer']

View File

@ -186,6 +186,7 @@ Rails.application.routes.draw do
# PayZen special endpoint
post 'payzen/sdk_test' => 'payzen#sdk_test'
post 'payzen/create_payment' => 'payzen#create_payment'
end
# rss

View File

@ -14,5 +14,23 @@ class PayZen::Charge < PayZen::Client
def sdk_test(value)
post('/Charge/SDKTest', value: value)
end
##
# @see https://payzen.io/en-EN/rest/V4.0/api/playground/Charge/CreatePayment/
##
def create_payment(amount: 0,
currency: Setting.get('payzen_currency'),
order_id: nil,
form_action: 'PAYMENT',
contrib: "fab-manager #{Version.current}",
customer: nil)
post('/Charge/CreatePayment',
amount: amount,
currency: currency,
orderId: order_id,
formAction: form_action,
contrib: contrib,
customer: customer)
end
end