/**
  * Create plan in Stripe
  *
  * @since 2.1
  * @return bool | string - plan_id if successful, false if not
  */
 private function create_plan($plan_name = '')
 {
     global $rcp_options;
     // get all subscription level info for this plan
     $plan = rcp_get_subscription_details_by_name($plan_name);
     $price = round($plan->price * rcp_stripe_get_currency_multiplier(), 0);
     $interval = $plan->duration_unit;
     $interval_count = $plan->duration;
     $name = $plan->name;
     $plan_id = sprintf('%s-%s-%s', strtolower(str_replace(' ', '', $plan_name)), $plan->price, $plan->duration . $plan->duration_unit);
     $currency = strtolower($rcp_options['currency']);
     \Stripe\Stripe::setApiKey($this->secret_key);
     try {
         $plan = \Stripe\Plan::create(array("amount" => $price, "interval" => $interval, "interval_count" => $interval_count, "name" => $name, "currency" => $currency, "id" => $plan_id));
         // plann successfully created
         return $plan->id;
     } catch (Exception $e) {
         $this->handle_processing_error($e);
     }
 }
示例#2
0
/**
 * Update a discount in Stripe when a local code is updated
 *
 * @access      private
 * @param       $discount_id int the id of the discount being updated
 * @param       $args array the array of discount args
 *              array(
 *					'name',
 *					'description',
 *					'amount',
 *					'unit',
 *					'code',
 *					'status',
 *					'expiration',
 *					'max_uses',
 *					'subscription_id'
 *				)
 * @since       2.1
 */
function rcp_stripe_update_discount($discount_id, $args)
{
    if (!is_admin()) {
        return;
    }
    // bail if the discount id or args are empty
    if (empty($discount_id) || empty($args)) {
        return;
    }
    if (function_exists('rcp_stripe_add_discount')) {
        return;
        // Old Stripe gateway is active
    }
    if (!rcp_is_gateway_enabled('stripe') && !rcp_is_gateway_enabled('stripe_checkout')) {
        return;
    }
    global $rcp_options;
    if (!class_exists('Stripe\\Stripe')) {
        require_once RCP_PLUGIN_DIR . 'includes/libraries/stripe/init.php';
    }
    if (!empty($_REQUEST['deactivate_discount']) || !empty($_REQUEST['activate_discount'])) {
        return;
    }
    if (rcp_is_sandbox()) {
        $secret_key = trim($rcp_options['stripe_test_secret']);
    } else {
        $secret_key = trim($rcp_options['stripe_live_secret']);
    }
    \Stripe\Stripe::setApiKey($secret_key);
    $discount_details = rcp_get_discount_details($discount_id);
    $discount_name = $discount_details->code;
    if (!rcp_stripe_does_coupon_exists($discount_name)) {
        try {
            if ($args['unit'] == '%') {
                \Stripe\Coupon::create(array("percent_off" => sanitize_text_field($args['amount']), "duration" => "forever", "id" => sanitize_text_field($discount_name), "currency" => strtolower($rcp_options['currency'])));
            } else {
                \Stripe\Coupon::create(array("amount_off" => sanitize_text_field($args['amount']) * rcp_stripe_get_currency_multiplier(), "duration" => "forever", "id" => sanitize_text_field($discount_name), "currency" => strtolower($rcp_options['currency'])));
            }
        } catch (Exception $e) {
            wp_die('<pre>' . $e . '</pre>', __('Error', 'rcp'));
        }
    } else {
        // first delete the discount in Stripe
        try {
            $cpn = \Stripe\Coupon::retrieve($discount_name);
            $cpn->delete();
        } catch (Exception $e) {
            wp_die('<pre>' . $e . '</pre>', __('Error', 'rcp'));
        }
        // now add a new one. This is a fake "update"
        try {
            if ($args['unit'] == '%') {
                \Stripe\Coupon::create(array("percent_off" => sanitize_text_field($args['amount']), "duration" => "forever", "id" => sanitize_text_field($discount_name), "currency" => strtolower($rcp_options['currency'])));
            } else {
                \Stripe\Coupon::create(array("amount_off" => sanitize_text_field($args['amount']) * rcp_stripe_get_currency_multiplier(), "duration" => "forever", "id" => sanitize_text_field($discount_name), "currency" => strtolower($rcp_options['currency'])));
            }
        } catch (\Stripe\Error\InvalidRequest $e) {
            // Invalid parameters were supplied to Stripe's API
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (\Stripe\Error\Authentication $e) {
            // Authentication with Stripe's API failed
            // (maybe you changed API keys recently)
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (\Stripe\Error\ApiConnection $e) {
            // Network communication with Stripe failed
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (\Stripe\Error\Base $e) {
            // Display a very generic error to the user
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
            $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
            $error .= print_r($e, true);
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        }
    }
}
/**
 * Displays stripe checkout form
 *
 * @since 2.5
 * @access public
 *
 * @param $atts
 * @return mixed|void
 */
function rcp_register_form_stripe_checkout($atts)
{
    global $rcp_options;
    if (empty($atts['id'])) {
        return '';
    }
    // button is an alias for data-label
    if (isset($atts['button'])) {
        $atts['data-label'] = $atts['button'];
    }
    $key = rcp_is_sandbox() ? $rcp_options['stripe_test_publishable'] : $rcp_options['stripe_live_publishable'];
    $member = new RCP_Member(wp_get_current_user()->ID);
    $subscription = rcp_get_subscription_details($atts['id']);
    $amount = $subscription->price + $subscription->fee;
    if ($member->ID > 0) {
        $amount -= $member->get_prorate_credit_amount();
    }
    if ($amount < 0) {
        $amount = 0;
    }
    $data = wp_parse_args($atts, array('id' => 0, 'data-key' => $key, 'data-name' => get_option('blogname'), 'data-description' => $subscription->description, 'data-label' => sprintf(__('Join %s', 'rcp'), $subscription->name), 'data-panel-label' => __('Register - {{amount}}', 'rcp'), 'data-amount' => $amount * rcp_stripe_get_currency_multiplier(), 'data-locale' => 'auto', 'data-allow-remember-me' => true, 'data-currency' => rcp_get_currency(), 'data-alipay' => isset($rcp_options['stripe_alipay']) && '1' === $rcp_options['stripe_alipay'] && 'USD' === rcp_get_currency() ? 'true' : 'false'));
    if (empty($data['data-email']) && !empty($member->user_email)) {
        $data['data-email'] = $member->user_email;
    }
    if (empty($data['data-image']) && ($image = get_site_icon_url())) {
        $data['data-image'] = $image;
    }
    $data = apply_filters('rcp_stripe_checkout_data', $data);
    if ('USD' !== rcp_get_currency()) {
        unset($data['data-alipay']);
    }
    ob_start();
    if ($member->ID > 0 && $member->get_subscription_id() == $subscription->id && $member->is_active()) {
        ?>

		<div class="rcp-stripe-checkout-notice"><?php 
        _e('You are already subscribed.', 'rcp');
        ?>
</div>

	<?php 
    } else {
        ?>
		<form action="" method="post">
			<?php 
        do_action('register_form_stripe_fields', $data);
        ?>
			<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" <?php 
        foreach ($data as $label => $value) {
            printf(' %s="%s" ', esc_attr($label), esc_attr($value));
        }
        ?>
 ></script>
			<input type="hidden" name="rcp_level" value="<?php 
        echo $subscription->id;
        ?>
" />
			<input type="hidden" name="rcp_register_nonce" value="<?php 
        echo wp_create_nonce('rcp-register-nonce');
        ?>
"/>
			<input type="hidden" name="rcp_gateway" value="stripe_checkout"/>
			<input type="hidden" name="rcp_stripe_checkout" value="1"/>
		</form>
	<?php 
    }
    return apply_filters('register_form_stripe', ob_get_clean(), $atts);
}
    /**
     * Print fields for this gateway
     *
     * @return string
     */
    public function fields()
    {
        global $rcp_options;
        if (is_user_logged_in()) {
            $email = wp_get_current_user()->user_email;
        } else {
            $email = false;
        }
        $data = apply_filters('rcp_stripe_checkout_form_data', array('key' => $this->publishable_key, 'locale' => 'auto', 'allowRememberMe' => true, 'email' => $email, 'currency' => rcp_get_currency(), 'alipay' => isset($rcp_options['stripe_alipay']) && '1' === $rcp_options['stripe_alipay'] && 'USD' === rcp_get_currency() ? true : false));
        $subscriptions = array();
        foreach (rcp_get_subscription_levels('active') as $subscription) {
            $subscriptions[$subscription->id] = array('description' => $subscription->description, 'name' => $subscription->name, 'panelLabel' => __('Register', 'rcp'));
        }
        $subscriptions = apply_filters('rcp_stripe_checkout_subscription_data', $subscriptions);
        ob_start();
        ?>

		<script>
			var rcp_script_options;
			var rcpSubscriptions = <?php 
        echo json_encode($subscriptions);
        ?>
;
			var checkoutArgs     = <?php 
        echo json_encode($data);
        ?>
;

			// define the token function
			checkoutArgs.token = function(token){ jQuery('body').trigger('rcp_stripe_checkout_submit', token); };

			if( ! checkoutArgs.email ) {
				checkoutArgs.email = jQuery('#rcp_registration_form #rcp_user_email' ).val();
			}

			jQuery('#rcp_registration_form #rcp_submit').val( rcp_script_options.pay_now );

			jQuery('body').on('rcp_level_change', function(event, target) {
				jQuery('#rcp_registration_form #rcp_submit').val(
					jQuery(target).attr('rel') > 0 ? rcp_script_options.pay_now : rcp_script_options.register
				);
			});

			jQuery('body').on('rcp_stripe_checkout_submit', function(e, token){
				jQuery('#rcp_registration_form').append('<input type="hidden" name="stripeToken" value="' + token.id + '" />').submit();
			});

			jQuery('#rcp_registration_form #rcp_user_email' ).focusout(function() {
				checkoutArgs.email = jQuery('#rcp_registration_form #rcp_user_email' ).val();
			});

			var rcpStripeCheckout = StripeCheckout.configure(checkoutArgs);

			jQuery('#rcp_registration_form #rcp_submit').on('click', function(e) {

				if ( jQuery('#rcp_gateway option:selected').val() !== 'stripe_checkout' && jQuery('input[name=rcp_gateway]').val() !== 'stripe_checkout' && jQuery('input[name=rcp_gateway]:checked').val() !== 'stripe_checkout' ) {
					return;
				}

				var $form = jQuery(this).closest('form');
				var $level = $form.find('input[name=rcp_level]:checked');

				var $price = $level.parent().find('.rcp_price').attr('rel') * <?php 
        echo rcp_stripe_get_currency_multiplier();
        ?>
;
				if ( ! $level.length ) {
					$level = $form.find('input[name=rcp_level]');
					$price = $form.find('.rcp_level').attr('rel') * <?php 
        echo rcp_stripe_get_currency_multiplier();
        ?>
;
				}

				if( jQuery('.rcp_gateway_fields').hasClass('rcp_discounted_100') ) {
					return true;
				}

				// Open Checkout with further options
				if ( $price > 0 ) {
					rcpStripeCheckout.open(rcpSubscriptions[$level.val()]);
					e.preventDefault();

					return false;
				}
			});

			// Close Checkout on page navigation
			jQuery(window).on('popstate', function() {
				rcpStripeCheckout.close();
			});
		</script>

		<?php 
        return ob_get_clean();
    }