Skip to content

Commit

Permalink
stripe adds
Browse files Browse the repository at this point in the history
  • Loading branch information
hasanuzzamanbe committed Oct 4, 2023
1 parent 69dce60 commit 53d722a
Show file tree
Hide file tree
Showing 10 changed files with 294 additions and 16 deletions.
7 changes: 5 additions & 2 deletions includes/Builder/Methods/PayPal/PayPal.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public function makePayment($transactionId, $entryId, $form_data)
'email' => $supporter->supporters_email,
'no_shipping' => '1',
'no_note' => '1',
'currency_code' => $supporter->currency ? $supporter->currency : 'USD',
'currency_code' => $supporter->currency ?? 'USD',
'charset' => 'UTF-8',
'custom' => $transactionId,
'return' => $this->successUrl($supporter),
Expand Down Expand Up @@ -301,11 +301,14 @@ public function render($template)

?>
<label class="wpm_paypal_card_label" for="wpm_paypal_card">
<img width="50px" src="<?php echo esc_url(Vite::staticPath() . 'images/paypal.png'); ?>" alt="">
<img width="60px" src="<?php echo esc_url(Vite::staticPath() . 'images/paypal.png'); ?>" alt="">
<input
style="outline: none;"
type="radio" name="wpm_payment_method" class="wpm_paypal_card" id="wpm_paypal_card"
value="paypal">
<!-- <span class="payment_method_name">-->
<!-- PayPal-->
<!-- </span>-->
</label>
<?php
}
Expand Down
89 changes: 89 additions & 0 deletions includes/Builder/Methods/Stripe/API.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

namespace BuyMeCoffee\Builder\Methods\Stripe;

use BuyMeCoffee\Helpers\ArrayHelper as Arr;

class API
{
private $createSessionUrl;
private $apiUrl = 'https://api.stripe.com/v1/';

public function makeRequest($path, $data, $apiKey, $method = 'GET')
{
$stripeApiKey = $apiKey;
$sessionHeaders = array(
'Authorization' => 'Bearer ' . $stripeApiKey,
'Content-Type' => 'application/x-www-form-urlencoded',
);

$requestData = array(
'headers' => $sessionHeaders,
'body' => http_build_query($data),
'method' => $method,
);

$url = $this->apiUrl . $path;

$sessionResponse = wp_remote_post($url, $requestData);

if (is_wp_error($sessionResponse)) {
echo "API Error: " . esc_html($sessionResponse->get_error_message());
exit;
}

$sessionResponseData = wp_remote_retrieve_body($sessionResponse);

$sessionData = json_decode($sessionResponseData, true);

if (empty($sessionData['id'])) {
$message = Arr::get($sessionData, 'detail');
if (!$message) {
$message = Arr::get($sessionData, 'error.message');
}
if (!$message) {
$message = 'Unknown Stripe API request error';
}

return new \WP_Error(423, $message, $sessionData);
}

return $sessionData;
}


public function verifyIPN()
{
if (!isset($_REQUEST['wpm_bmc_stripe_listener'])) {
return;
}

$post_data = '';
if (ini_get('allow_url_fopen')) {
$post_data = file_get_contents('php://input');
} else {
// If allow_url_fopen is not enabled, then make sure that post_max_size is large enough
ini_set('post_max_size', '12M');
}

$data = json_decode($post_data);

if ($data->id) {
status_header(200);
return $data;
} else {
error_log("specific event");
error_log(print_r($data));
return false;
}

exit(200);
}

public function getInvoice($eventId)
{
$api = new ApiRequest();
$api::set_secret_key((new StripeSettings())->getApiKey());
return $api::request([], 'events/' . $eventId, 'GET');
}
}
91 changes: 86 additions & 5 deletions includes/Builder/Methods/Stripe/Stripe.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use BuyMeCoffee\Builder\Methods\BaseMethods;
use BuyMeCoffee\Classes\Vite;
use BuyMeCoffee\Models\Supporters;
use BuyMeCoffee\Models\Transactions;

class Stripe extends BaseMethods
{
Expand All @@ -21,9 +23,79 @@ public function __construct()

public function makePayment($transactionId, $entryId, $form_data)
{
// TO-Do will implement later on upcoming version
$transactionModel = new Transactions();
$transaction = $transactionModel->find($transactionId);

$supportersModel = new Supporters();
$supporter = $supportersModel->find($entryId);
$hash = $transaction->entry_hash;

$keys = StripeSettings::getKeys();
$apiKey = $keys['secret'];

$paymentArgs = array(
'payment_method_type' => ['card'],
'client_reference_id' => $hash,
'amount' => (int) round($transaction->payment_total, 0),
'currency' => strtolower($transaction->currency),
'description' => "Buy coffee from {$supporter->supporters_name}",
'customer_email' => $supporter->supporters_email,
'success_url' => $this->successUrl($supporter),
'public_key' => $keys['public']
);

$this->handleInlinePayment($transaction, $paymentArgs, $apiKey);
}

public function handleInlinePayment($transaction, $paymentArgs, $apiKey)
{
try {
$intentData = $this->intentData($paymentArgs);
$invoiceResponse = (new API())->makeRequest('payment_intents', $intentData, $apiKey, 'POST');

$transaction->payment_args = $paymentArgs;

$responseData = [
'nextAction' => 'stripe',
'actionName' => 'custom',
'buttonState' => 'hide',
'intent' => $invoiceResponse,
'order_items' => $transaction,
'message_to_show' => __('Payment Modal is opening, Please complete the payment', 'buy-me-coffee'),
];

wp_send_json_success($responseData, 200);
} catch (\Exception $e) {
wp_send_json_error([
'status' => 'failed',
'message' => $e->getMessage()
], 423);
}
}

public function intentData($args)
{
$sessionPayload = array(
'amount' => $args['amount'],
'currency' => $args['currency'],
'metadata' => [
'ref_id' => $args['client_reference_id'],
],
);

return $sessionPayload;
}
public function successUrl($supporter)
{
return add_query_arg(array(
'send_coffee' => '',
'wpm_bmc_success' => 1,
'hash' => $supporter->entry_hash,
'payment_method' => 'stripe'
), home_url());
}


public function sanitize($settings)
{
foreach ($settings as $key => $value) {
Expand Down Expand Up @@ -55,18 +127,27 @@ public function getSettings()
return wp_parse_args($settings, $defaults);
}

public function maybeLoadModalScript()
{
//phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
wp_enqueue_script('wpm-buymecoffee-checkout-sdk-' . $this->method, 'https://js.stripe.com/v3/',null, false);
Vite::enqueueScript('wpm-buymecoffee-checkout-handler-' . $this->method, 'js/PaymentMethods/stripe-checkout.js', ['wpm-buymecoffee-checkout-sdk-stripe', 'jquery'], '1.0.1', false);
}

public function render($template)
{
$this->maybeLoadModalScript();

?>
<label class="wpm_stripe_card_label" for="wpm_stripe_card">
<img width="50px" src="<?php echo esc_url(WPM_BMC_URL . 'assets/images/credit-card.png'); ?>" alt="">
<img width="60px" src="<?php echo esc_url(Vite::staticPath() . 'images/stripe.svg'); ?>" alt="">
<input
style="outline: none;"
type="radio" class="wpm_stripe_card" name="wpm_payment_method" id="wpm_stripe_card"
value="stripe">
<!-- <span class="payment_method_name">-->
<!-- stripe-->
<!-- </span>-->
<!-- <span class="payment_method_name">-->
<!-- Stripe-->
<!-- </span>-->
</label>
<?php
}
Expand Down
46 changes: 46 additions & 0 deletions includes/Builder/Methods/Stripe/StripeSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace BuyMeCoffee\Builder\Methods\Stripe;

class StripeSettings
{
public static function getSettings($key = null)
{
$settings = get_option('wpm_bmc_payment_settings_stripe', []);

$defaults = array(
'enable' => 'no',
'payment_mode' => 'test',
'live_pub_key' => '',
'live_secret_key' => '',
'test_pub_key' => '',
'test_secret_key' => ''
);

$data = wp_parse_args($settings, $defaults);
return $key && isset($data[$key]) ? $data[$key] : $data;
}

public static function getKeys($key = null)
{
$settings = self::getSettings();

if ($settings['payment_mode'] == 'test') {
$data = array(
'secret' => $settings['test_secret_key'],
'public' => $settings['test_pub_key']
);
} else {
$data = array(
'secret' => $settings['live_secret_key'],
'public' =>$settings['live_pub_key']
);
}

return $key && isset($data[$key]) ? $data[$key] : $data;

}



}
6 changes: 3 additions & 3 deletions includes/Builder/Render.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public static function renderInputElements($template = [])
</div>
<?php endif; ?>

<div class="wpm_bmc_form_item wpm_bmc_pay_methods">
<div class="wpm_bmc_form_item wpm_bmc_pay_methods" id="wpm_bmc_pay_methods">
<div class="wpm_bmc_pay_method" data-payment_selected="none">
<?php echo static::payMethod($template); ?>
</div>
Expand All @@ -230,8 +230,8 @@ public static function renderInputElements($template = [])
to="360 20 20" dur="0.5s" repeatCount="indefinite"/>
</path></svg>
</div>
<?php echo esc_html($symbool); ?></php> <span
class="wpm_payment_total_amount"><?php echo esc_html($defaultAmount); ?></span>
<span class="wpm_payment_total_amount_prefix"><?php echo esc_html($symbool); ?></span>
<span class="wpm_payment_total_amount"><?php echo esc_html($defaultAmount); ?></span>
</button>
</div>
</div>
Expand Down
5 changes: 1 addition & 4 deletions src/js/Components/Stripe.vue
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
<template>
<div class="wpm_bmc_main_container" v-loading="fetching">
<div class="upcoming_feature_notice">
Upcoming feature
</div>
<div class="wpm_bmc_wrapper wpm_bmc_payment_settings">
<h3 class="wpm_bmc_title">
<router-link style="text-decoration: none;" :to="{name: 'Gateway'}">Gateways / </router-link>Stripe Gateway Settings:
</h3>
<div style="margin-bottom: 23px;">
<label>Enable Stripe Payment
<el-switch disabled active-value="yes" inactive-value="no" active-text="Enable stripe" v-model="settings.enable"></el-switch>
<el-switch active-value="yes" inactive-value="no" active-text="Enable stripe" v-model="settings.enable"></el-switch>
</label>
</div>
<div class="wpm_bmc_section_body" :class="settings.enable !== 'yes' ? 'payment-inactive' : ''">
Expand Down
4 changes: 2 additions & 2 deletions src/js/PaymentMethods/paypal-checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ class PaypalCheckout {
})
.render(paypalButtonContainer[0])

this.form.find('.wpm_bmc_form_submit_wrapper').hide();
this.form.find('.wpm_bmc_form_submit_wrapper, .wpm_bmc_no_signup, .wpm_bmc_input_content, .wpm_bmc_payment_input_content').hide();
this.form.find('.wpm_bmc_pay_methods')?.parent().append(paypalButtonContainer);
this.form.find('.wpm_bmc_no_signup').html('Please complete your payment with PayPal 👇');
this.form.prepend("<p class='complete_payment_instruction'>Please complete your donation with PayPal 👇</p>");
}
}

Expand Down
54 changes: 54 additions & 0 deletions src/js/PaymentMethods/stripe-checkout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
class StripeCheckout {
constructor ($form, $response) {
this.form = $form
this.data = $response.data
this.intent = $response.data?.intent
}

init () {
this.form.find('.wpm_submit_button').hide();
let amounPrefix = this.form.find('.wpm_payment_total_amount_prefix').text();

let buttonText = "Pay " + amounPrefix + (parseInt(this.intent.amount) / 100) + " Now"

let submitButton = "<button id='wpm_bmc_pay_now' style='margin-top: 20px;width: 100%;background: #11d8cc;' type='submit'>" + buttonText + "</button>";
var stripe = Stripe(this.data?.order_items?.payment_args?.public_key);
const elements = stripe.elements({
clientSecret: this.intent.client_secret
});
const paymentElement = elements.create('payment', {});
paymentElement.mount('#wpm_bmc_pay_methods');

this.form.find('.wpm_bmc_pay_methods')?.parent().append("<p class='wpm_bmc_loading_processor' style='color: #48a891;font-size: 14px;'>Payment processing...</p>");
this.form.find('#fluent_cart_order_btn').hide();

let that= this;
paymentElement.on('ready', (event) => {
jQuery('.wpm_bmc_loading_processor').remove();
jQuery('#wpm_bmc_pay_methods').append(submitButton);
this.form.find('.wpm_bmc_input_content, .wpm_bmc_payment_input_content').hide();
this.form.prepend("<p class='complete_payment_instruction'>Please complete your donation with Stripe 👇</p>");

jQuery('#wpm_bmc_pay_now').on('click', function(e) {
e.preventDefault()
jQuery(this).text('Processing...');
elements.submit().then(result=> {
stripe.confirmPayment({
elements,
confirmParams: {
return_url: that.data?.order_items?.payment_args?.success_url
}
}).then((result) => {
jQuery(this).text(buttonText);
})
}).catch(error => {
jQuery(this).text(buttonText);
})
})
});
}
}

window.addEventListener("wpm_bmc_payment_next_action_stripe", function (e) {
new StripeCheckout(e.detail.form, e.detail.response).init();
});
Loading

0 comments on commit 53d722a

Please sign in to comment.