コード例 #1
0
 public function testUpcoming()
 {
     authorizeFromEnv();
     $c = Stripe_Customer::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015)));
     $invoice = Stripe_Invoice::upcoming(array('customer' => $c->id));
     $this->assertEqual($invoice->customer, $c->id);
     $this->assertEqual($invoice->attempted, false);
 }
コード例 #2
0
ファイル: InvoiceTest.php プロジェクト: bulats/chef
 public function testUpcoming()
 {
     authorizeFromEnv();
     $customer = self::createTestCustomer();
     Stripe_InvoiceItem::create(array('customer' => $customer->id, 'amount' => 0, 'currency' => 'usd'));
     $invoice = Stripe_Invoice::upcoming(array('customer' => $customer->id));
     $this->assertEqual($invoice->customer, $customer->id);
     $this->assertEqual($invoice->attempted, false);
 }
コード例 #3
0
ファイル: Customer.php プロジェクト: vilmark/vilmark_main
 /**
  * @param array|null $params
  *
  * @returns array An array of the customer's Stripe_Invoices.
  */
 public function invoices($params = null)
 {
     if (!$params) {
         $params = array();
     }
     $params['customer'] = $this->id;
     $invoices = Stripe_Invoice::all($params, $this->_apiKey);
     return $invoices;
 }
コード例 #4
0
 /**
  * Print an invoice
  */
 public function printAction($id)
 {
     \Stripe::setApiKey($this->container->getParameter('avro_stripe.secret_key'));
     $invoice = \Stripe_Invoice::retrieve($id);
     if (!$invoice) {
         throw new NotFoundHttpException('Invoice not found');
     }
     $user = $this->container->get('fos_user.user_manager')->findUserBy(array('stripeCustomerId' => $invoice->customer));
     if (!$user) {
         throw new NotFoundHttpException('User not found');
     }
     $html = $this->container->get('templating')->render('AvroStripeBundle:Invoice:print.html.twig', array('invoice' => $invoice, 'user' => $user));
     return new Response($this->container->get('knp_snappy.pdf')->getOutputFromHtml($html), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="' . $invoice->id . '.pdf"'));
 }
コード例 #5
0
    /**
     * Populate an array with existing user information
     *
     * Array will be rendered by ProSites_View_Front_Gateway
     *
     * @param $blog_id
     * @param $domain
     * @param bool $get_all
     *
     * @return array|bool
     */
    public static function get_existing_user_information($blog_id, $domain, $get_all = true)
    {
        global $psts;
        $args = array();
        $img_base = $psts->plugin_url . 'images/';
        $trialing = ProSites_Helper_Registration::is_trial($blog_id);
        if ($trialing) {
            $args['trial'] = '<div id="psts-general-error" class="psts-warning">' . __('You are still within your trial period. Once your trial finishes your account will be automatically charged.', 'psts') . '</div>';
        }
        // Pending information
        /**
         * @todo: Hook psts_blog_info_pending (Front/Gateway.php)
         */
        if (!empty($blog_id) && 1 == get_blog_option($blog_id, 'psts_stripe_waiting')) {
            $args['pending'] = '<div id="psts-general-error" class="psts-warning">' . __('There are pending changes to your account. This message will disappear once these pending changes are completed.', 'psts') . '</div>';
        }
        // Successful payment
        if (self::$complete_message) {
            // @todo: Hook psts_blog_info_complete_message
            $args['complete_message'] = '<div id="psts-complete-msg">' . self::$complete_message . '</div>';
            // @todo: Hook psts_blog_info_thanks_message
            $args['thanks_message'] = '<p>' . $psts->get_setting('stripe_thankyou') . '</p>';
            //If Checking out on signup, there wouldn't be a blogid probably
            //			if ( ! empty ( $domain ) ) {
            //				//Hardcoded, TODO: Search for alternative
            //				$admin_url = is_ssl() ? trailingslashit( "https://$domain" ) . 'wp-admin/' : trailingslashit( "http://$domain" ) . 'wp-admin/';
            //				$args['visit_site_message'] = '<p><a href="' . $admin_url . '">' . __( 'Visit your newly upgraded site &raquo;', 'psts' ) . '</a></p>';
            //			} else {
            $args['visit_site_message'] = '<p><a href="' . get_admin_url($blog_id, '', 'http') . '">' . __('Go to your site &raquo;', 'psts') . '</a></p>';
            //			}
            self::$complete_message = false;
        }
        // Cancellation message
        if (self::$cancel_message) {
            $args['cancel'] = true;
            $args['cancellation_message'] = self::$cancel_message;
            self::$cancel_message = false;
        }
        // Existing customer information --- only if $get_all is true (default)
        $customer_id = self::get_customer_data($blog_id)->customer_id;
        if (!empty($customer_id) && $get_all) {
            try {
                $customer_object = Stripe_Customer::retrieve($customer_id);
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            // Move to render info class
            $end_date = date_i18n(get_option('date_format'), $psts->get_expire($blog_id));
            $level = $psts->get_level_setting($psts->get_level($blog_id), 'name');
            $is_recurring = $psts->is_blog_recurring($blog_id);
            $args['recurring'] = $is_recurring;
            // If invoice cant be created, its not looking good. Cancel.
            try {
                $invoice_object = Stripe_Invoice::upcoming(array("customer" => $customer_id));
            } catch (Exception $e) {
                if ($is_recurring) {
                    $args['cancel'] = true;
                    $args['cancellation_message'] = '<div class="psts-cancel-notification">
													<p class="label"><strong>' . __('Your subscription has been canceled', 'psts') . '</strong></p>
													<p>' . sprintf(__('This site should continue to have %1$s features until %2$s.', 'psts'), $level, $end_date) . '</p>';
                }
            }
            $args['level'] = $level;
            $args['expires'] = $end_date;
            // All good, keep populating the array.
            if (!isset($args['cancel'])) {
                // Get the last valid card
                if (isset($customer_object->cards->data[0]) && isset($customer_object->default_card)) {
                    foreach ($customer_object->cards->data as $tmpcard) {
                        if ($tmpcard->id == $customer_object->default_card) {
                            $card = $tmpcard;
                            break;
                        }
                    }
                } elseif (isset($customer_object->active_card)) {
                    //for API pre 2013-07-25
                    $card = $customer_object->active_card;
                }
                $args['card_type'] = $card->brand;
                $args['card_reminder'] = $card->last4;
                $args['card_digit_location'] = 'end';
                $args['card_expire_month'] = $card->exp_month;
                $args['card_expire_year'] = $card->exp_year;
                // Get the period
                $plan_parts = explode('_', $customer_object->subscriptions->data[0]->plan->id);
                $period = array_pop($plan_parts);
                $args['period'] = $period;
                // Get last payment date
                try {
                    $existing_invoice_object = Stripe_Invoice::all(array("customer" => $customer_id, "count" => 1));
                } catch (Exception $e) {
                    $error = $e->getMessage();
                }
                if (isset($existing_invoice_object->data[0]) && $customer_object->subscriptions->data[0]->status != 'trialing') {
                    $args['last_payment_date'] = $existing_invoice_object->data[0]->date;
                }
                // Get next payment date
                if (isset($invoice_object->next_payment_attempt)) {
                    $args['next_payment_date'] = $invoice_object->next_payment_attempt;
                }
                // Cancellation link
                if ($is_recurring) {
                    if (is_pro_site($blog_id)) {
                        $args['cancel_info'] = '<p class="prosites-cancel-description">' . sprintf(__('If you choose to cancel your subscription this site should continue to have %1$s features until %2$s.', 'psts'), $level, $end_date) . '</p>';
                        $cancel_label = __('Cancel Your Subscription', 'psts');
                        // CSS class of <a> is important to handle confirmations
                        $args['cancel_link'] = '<p class="prosites-cancel-link"><a class="cancel-prosites-plan button" href="' . wp_nonce_url($psts->checkout_url($blog_id) . '&action=cancel', 'psts-cancel') . '" title="' . esc_attr($cancel_label) . '">' . esc_html($cancel_label) . '</a></p>';
                    }
                }
                // Receipt form
                $args['receipt_form'] = $psts->receipt_form($blog_id);
            }
            // Show all is true
            $args['all_fields'] = true;
        }
        return empty($args) ? array() : $args;
    }
コード例 #6
0
 public function buySubscription($userDetail, $token, $plan, $userEmail)
 {
     try {
         $secret_key = config_item('stripe_secret');
         Stripe::setApiKey($secret_key);
         $description = sprintf("One year subscription fee for %s", $plan);
         $customerOption = array("card" => $token, "email" => $userEmail);
         $customer = Stripe_Customer::create($customerOption);
         //            echo "Customer Information: <br>";
         //            $this->util->echoObject($customer);
         $subscriptionOption = array("plan" => $plan);
         $subscriptionInfo = $customer->subscriptions->create($subscriptionOption);
         //            echo "Customer Information: <br>";
         //            $this->util->echoObject($subscriptionInfo);
         $stripeCustomerID = $customer->id;
         $amount = $subscriptionInfo->plan->amount;
         $currency = $subscriptionInfo->plan->currency;
         $discount = 0;
         $invoice_item = Stripe_InvoiceItem::create(array('customer' => $stripeCustomerID, 'amount' => $amount, 'currency' => $currency, 'description' => $description));
         //            echo "Invoice Item: <br>";
         //            $this->util->echoObject($invoice_item);
         $invoice = Stripe_Invoice::create(array('customer' => $stripeCustomerID));
         //            echo "Invoice: <br>";
         //            $this->util->echoObject($invoice);
         $invoice->pay();
         if (!$invoice->paid) {
             return false;
         }
         $this->updateUserProfile($userDetail->ID, $stripeCustomerID, $plan, $subscriptionInfo->current_period_start, $subscriptionInfo->current_period_end, $amount, $currency, $discount, $subscriptionInfo->name, $subscriptionInfo->id);
         $order_no = $invoice->id;
         if ($order_no) {
             $pdf_html = $this->util->makeInvoicePDFContent($userDetail, $subscriptionInfo, $invoice, $order_no, $customer->sources->data[0]->last4, $discount);
             $this->load->library('dompdf_lib');
             $pdf_content = $this->dompdf_lib->convert_html_to_pdf($pdf_html, $order_no, false);
             $file_name = $this->util->getEncryptedFileName($order_no);
             $this->util->uploadFileToServer($file_name, $pdf_content);
             /* Send invoice in mail */
             $ci = get_instance();
             $ci->load->library('email');
             $ci->email->from(config_item('support_email'), 'Taxideals support service');
             $list = array($userEmail);
             $ci->email->to($list);
             $this->email->reply_to($userEmail, '');
             $ci->email->subject('New invoice email');
             $ci->email->attach($_SERVER['DOCUMENT_ROOT'] . 'dev/invoices/' . $file_name . '.pdf');
             $msg = "Dear customer,<br/><br/>";
             $msg = $msg . "We are contacting you in regard to a new invoice that has been created on your account. You may find the invoice attached.<br/>";
             $msg = $msg . "If you have questions, we're happy to help. ";
             $msg = $msg . "Please conntact us via email: <a href=\"mailto:support@taxideals.com.au\">Taxideals Support</a>.<br/>";
             $msg = $msg . "<br/>Regards,<br/>The Taxideals team";
             $ci->email->message($msg);
             $ci->email->send();
         }
         return $order_no;
     } catch (Stripe_CardError $e) {
         $this->printError($e);
         return false;
     } catch (Stripe_InvalidRequestError $e) {
         $this->printError($e);
         return false;
     } catch (Stripe_AuthenticationError $e) {
         $this->printError($e);
         return false;
     } catch (Stripe_ApiConnectionError $e) {
         $this->printError($e);
         return false;
     } catch (Stripe_Error $e) {
         $this->printError($e);
         return false;
     } catch (Exception $e) {
         $this->printError($e);
         return false;
     } catch (ErrorException $e) {
         $this->printError($e);
         return false;
     }
 }
コード例 #7
0
ファイル: gateway-stripe.php プロジェクト: hscale/webento
    function checkout_screen($content, $blog_id)
    {
        global $psts, $wpdb, $current_site, $current_user;
        if (!$blog_id) {
            return $content;
        }
        //cancel subscription
        if (isset($_GET['action']) && $_GET['action'] == 'cancel' && wp_verify_nonce($_GET['_wpnonce'], 'psts-cancel')) {
            $error = '';
            try {
                $customer_id = $this->get_customer_id($blog_id);
                $cu = Stripe_Customer::retrieve($customer_id);
                $cu->cancelSubscription();
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            if ($error != '') {
                $content .= '<div id="message" class="error fade"><p>' . __('There was a problem canceling your subscription, please contact us for help: ', 'psts') . $error . '</p></div>';
            } else {
                //record stat
                $psts->record_stat($blog_id, 'cancel');
                $psts->email_notification($blog_id, 'canceled');
                update_blog_option($blog_id, 'psts_stripe_canceled', 1);
                $end_date = date_i18n(get_option('date_format'), $psts->get_expire($blog_id));
                $psts->log_action($blog_id, sprintf(__('Subscription successfully cancelled by %1$s. They should continue to have access until %2$s', 'psts'), $current_user->display_name, $end_date));
                $content .= '<div id="message" class="updated fade"><p>' . sprintf(__('Your %1$s subscription has been canceled. You should continue to have access until %2$s.', 'psts'), $current_site->site_name . ' ' . $psts->get_setting('rebrand'), $end_date) . '</p></div>';
            }
        }
        $cancel_status = get_blog_option($blog_id, 'psts_stripe_canceled');
        $cancel_content = '';
        $img_base = $psts->plugin_url . 'images/';
        $pp_active = false;
        //hide top part of content if its a pro blog
        if (is_pro_site($blog_id) || $psts->errors->get_error_message('coupon')) {
            $content = '';
        }
        if ($errmsg = $psts->errors->get_error_message('general')) {
            $content = '<div id="psts-general-error" class="psts-error">' . $errmsg . '</div>';
            //hide top part of content if theres an error
        }
        //if transaction was successful display a complete message and skip the rest
        if ($this->complete_message) {
            $content = '<div id="psts-complete-msg">' . $this->complete_message . '</div>';
            $content .= '<p>' . $psts->get_setting('stripe_thankyou') . '</p>';
            $content .= '<p><a href="' . get_admin_url($blog_id, '', 'http') . '">' . __('Visit your newly upgraded site &raquo;', 'psts') . '</a></p>';
            return $content;
        }
        if ($customer_id = $this->get_customer_id($blog_id)) {
            try {
                $customer_object = Stripe_Customer::retrieve($customer_id);
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            $content .= '<div id="psts_existing_info">';
            $end_date = date_i18n(get_option('date_format'), $psts->get_expire($blog_id));
            $level = $psts->get_level_setting($psts->get_level($blog_id), 'name');
            try {
                $invoice_object = Stripe_Invoice::upcoming(array("customer" => $customer_id));
            } catch (Exception $e) {
                $cancel_status = 1;
            }
            try {
                $existing_invoice_object = Stripe_Invoice::all(array("customer" => $customer_id, "count" => 1));
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            if ($cancel_status == 1) {
                $content .= '<h3>' . __('Your subscription has been canceled', 'psts') . '</h3>';
                $content .= '<p>' . sprintf(__('This site should continue to have %1$s features until %2$s.', 'psts'), $psts->get_setting('rebrand'), $end_date) . '</p>';
            }
            if ($cancel_status == 0) {
                $content .= '<ul>';
                if (is_pro_site($blog_id)) {
                    $content .= '<li>' . __('Level:', 'psts') . ' <strong>' . $level . '</strong></li>';
                }
                if (isset($customer_object->active_card)) {
                    $content .= '<li>' . __('Payment Method: <strong>' . $customer_object->active_card->type . ' Card</strong> ending in <strong>' . $customer_object->active_card->last4 . '</strong>. Expires <strong>' . $customer_object->active_card->exp_month . '/' . $customer_object->active_card->exp_year . '</strong>', 'psts') . '</li>';
                }
                if (isset($exitsing_invoice_object->data[0])) {
                    $content .= '<li>' . __('Last Payment Date:', 'psts') . ' <strong>' . date_i18n(get_option('date_format'), $existing_invoice_object->data[0]->date) . '</strong></li>';
                }
                if (isset($invoice_object->next_payment_attempt)) {
                    $content .= '<li>' . __('Next Payment Date:', 'psts') . ' <strong>' . date_i18n(get_option('date_format'), $invoice_object->next_payment_attempt) . '</strong></li>';
                }
                $content .= "</ul>";
                $cancel_content .= '<h3>' . __('Cancel Your Subscription', 'psts') . '</h3>';
                $pp_active = false;
                if (is_pro_site($blog_id)) {
                    $cancel_content .= '<p>' . sprintf(__('If you choose to cancel your subscription this site should continue to have %1$s features until %2$s.', 'psts'), $level, $end_date) . '</p>';
                    $cancel_content .= '<p><a id="stripe_cancel" href="' . wp_nonce_url($psts->checkout_url($blog_id) . '&action=cancel', 'psts-cancel') . '" title="' . __('Cancel Your Subscription', 'psts') . '"><img src="' . $img_base . 'cancel_subscribe_gen.gif" /></a></p>';
                    $pp_active = true;
                }
                //print receipt send form
                $content .= $psts->receipt_form($blog_id);
                if (!defined('PSTS_CANCEL_LAST')) {
                    $content .= $cancel_content;
                }
                $content .= "<br>";
                $content .= '</div>';
            }
        }
        if (!$cancel_status && is_pro_site($blog_id) && !is_pro_trial($blog_id)) {
            $content .= '<h2>' . __('Change Your Plan or Payment Details', 'psts') . '</h2>
        <p>' . __('You can modify or upgrade your plan or just change your payment method or information below. Your new subscription will automatically go into effect when your next payment is due.', 'psts') . '</p>';
        } else {
            if (!is_pro_site($blog_id) || is_pro_trial($blog_id)) {
                $content .= '<p>' . __('Please choose your desired plan then click the checkout button below.', 'psts') . '</p>';
            }
        }
        $content .= '<form action="' . $psts->checkout_url($blog_id) . '" method="post" autocomplete="off"  id="payment-form">';
        //print the checkout grid
        $content .= $psts->checkout_grid($blog_id);
        $content .= '<div id="psts-stripe-checkout">
			<h2>' . __('Checkout With a Credit Card:', 'psts') . '</h2>';
        $content .= '<div id="psts-processcard-error"></div>';
        $content .= '
				<table id="psts-cc-table">
				<tbody>
				<!-- Credit Card Type -->
				<tr>
				<td class="pypl_label" align="right">' . __('Cardholder Name:', 'psts') . '&nbsp;</td><td>';
        if ($errmsg = $psts->errors->get_error_message('name')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<input id="cc_name" type="text" class="cctext card-first-name" value="" size="25" /> </td>
				</tr>
					<tr>
					<td class="pypl_label" align="right">' . __('Card Number:', 'psts') . '&nbsp;</td>
					<td>';
        if ($errmsg = $psts->errors->get_error_message('number')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<input id="cc_number" type="text" class="cctext card-number" value="" size="23" /><br /><img src="' . $img_base . 'stripe-cards.png" />
					</td>
					</tr>

					<tr>
					<td class="pypl_label" align="right">' . __('Expiration Date:', 'psts') . '&nbsp;</td>
					<td valign="middle">';
        if ($errmsg = $psts->errors->get_error_message('expiration')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<select id="cc_month" class="card-expiry-month">' . $this->month_dropdown() . '</select>&nbsp;/&nbsp;<select id="cc_year" class="card-expiry-year">' . $this->year_dropdown() . '</select>
					</td>
					</tr>

					<!-- Card Security Code -->
					<tr>
						<td class="pypl_label" align="right"><nobr>' . __('Card Security Code:', 'psts') . '</nobr>&nbsp;</td>
						<td valign="middle">';
        if ($errmsg = $psts->errors->get_error_message('cvv2')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<label><input id="cc_cvv2" size="5" maxlength="4" type="password" class="cctext card-cvc" title="' . __('Please enter a valid card security code. This is the 3 digits on the signature panel, or 4 digits on the front of Amex cards.', 'psts') . '" />
						<img src="' . $img_base . 'buy-cvv.gif" height="27" width="42" title="' . __('Please enter a valid card security code. This is the 3 digits on the signature panel, or 4 digits on the front of Amex cards.', 'psts') . '" /></label>
						</td>
					</tr>
				

				</table>
				</tbody></table>
				<input type="hidden" name="cc_checkout" value="1" />
			<p>
				<input type="submit" id="cc_checkout" name="stripe_checkout_button" value="' . __('Subscribe', 'psts') . ' &raquo;" class="submit-button"/>
				<span id="stripe_processing" style="display: none;float: right;"><img src="' . $img_base . 'loading.gif" /> ' . __('Processing...', 'psts') . '</span>
			</p>
			</div>';
        $content .= '</form>';
        if (defined('PSTS_CANCEL_LAST')) {
            $content .= $cancel_content;
        }
        return $content;
    }
コード例 #8
0
 /**
  * Gets upcoming invoice for customer
  * @param $customer_id
  * @return array|bool
  */
 public function get_upcoming_customer($customer_id)
 {
     try {
         $ch = Stripe_Invoice::upcoming(array('customer' => $customer_id));
         return $ch;
     } catch (Exception $e) {
         $this->error = TRUE;
         $this->message = $e->getMessage();
         $this->code = $e->getCode();
         return FALSE;
     }
 }
コード例 #9
0
ファイル: stripe.php プロジェクト: wallydz/whmcs-stripe
if ($gatewaytestmode == "on") {
    Stripe::setApiKey($gateway['private_test_key']);
} else {
    Stripe::setApiKey($gateway['private_live_key']);
}
$body = @file_get_contents('php://input');
$event_json = json_decode($body);
$event_id = $event_json->id;
try {
    $event = Stripe_Event::retrieve($event_id);
    if ($event->type == 'charge.succeeded') {
        // Pull invoice ID from Stripe description
        if ($event->data->object->invoice != "") {
            // This is an invoice/subscription payment, get the WHMCS invoice ID
            $invoice_id = $event->data->object->invoice;
            $retrieved_invoice = Stripe_Invoice::retrieve($invoice_id)->lines->all(array('count' => 1, 'offset' => 0));
            $description_invoice = $retrieved_invoice["data"][0]["plan"]["name"];
            $description = $description_invoice;
        } else {
            // This is a one time payment
            $description = $event->data->object->description;
        }
        // Get the invoice ID from the transaction
        $start = strpos($description, "#") + strlen("#");
        $end = strpos($description, " ", $start);
        $invoiceid = substr($description, $start, $end - $start);
        $transid = $event->data->object->id;
        $amount_cents = $event->data->object->amount;
        $amount = $amount_cents / 100;
        $fee_cents = floatval($event->data->object->fee);
        $fee = $fee_cents / 100;
コード例 #10
0
 public function testAll()
 {
     authorizeFromEnv();
     $invoices = Stripe_Invoice::all();
     $this->assertTrue(count($invoices) > 0);
 }
コード例 #11
0
    public function send_gift_manual()
    {
        global $wpdb, $ntm_mail;
        if (isset($_POST['send_gift'])) {
            $option = get_option('giftbit');
            if ($option['amount'] >= $_POST['gift_amount']) {
                $this->fa_lead_options = get_option('fa_lead_settings');
                Stripe::setApiKey($this->fa_lead_options['api_key']);
                Stripe::setAPIVersion("2015-07-13");
                $customer_id = get_user_meta(get_blog_option(get_current_blog_id(), 'agent_id'), "pmpro_stripe_customerid");
                $amount = $this->fa_lead_options['admin_fee'] * 100;
                $giftAmount = $this->fa_lead_options['init_gift'];
                $invoice_item = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $this->fa_lead_options['admin_fee'], 'currency' => 'usd', 'description' => 'One-time setup fee'));
                $invoice = Stripe_Invoice::create(array('customer' => $customer_id));
                $result = $invoice->pay();
                if (isset($result->object) && $result->object == 'invoice') {
                    $data = array('endorser_id' => $_POST['endorser_id'], 'amout' => $_POST['gift_amount'], 'agent_id' => get_current_user_id(), 'created' => date("Y-m-d H:i:s"));
                    $wpdb->insert($wpdb->prefix . "gift_transaction", $data);
                    $gift_id = $wpdb->insert_id;
                    $ntm_mail->send_gift_mail('get_manualgift_mail', $_POST['endorser_id'], $gift_id);
                    $option['amount'] = $option['amount'] - $_POST['gift_amount'];
                    update_option("giftbit", $option);
                    $message = "Gift send successfully!!";
                } else {
                    $message = "Error when payment";
                }
            } else {
                $message = "Error! Insufficient balance!";
            }
        }
        //print_r(get_users(array('role'=>'endorser')));
        ?>
		
		<script>
			jQuery(document).ready(function(){
				jQuery("#gift_amount").change(function(){
					if(jQuery("#gift_amount").val() <= jQuery("#poststuff").data('amount'))
						jQuery("#send_gift").show();
					else
					{
						alert("Insufficient balance");
						jQuery("#send_gift").hide();
					}
				});
			});
		</script>
		
		<div data-amount="<?php 
        echo get_option('giftbit')['amount'];
        ?>
" id="poststuff" class="wrap">
		<h2>Send Gift By Manual</h2>
		<?php 
        if (isset($message)) {
            ?>
		<div id="message" class="updated"><p><?php 
            echo $message;
            ?>
</p></div>
		<?php 
        }
        ?>
			<div class="postbox">
				<div class="inside group">
					<form name="myform" method="post" >
					<table id="country" class="form-table">
						<tr>
							<th scope="row"><label for="blogname">Endorser</label></th>
							<td>
								<select class="regular-text" name="endorser_id">
									<option value="">Select Endorser</option>
									<?php 
        foreach (get_users(array('role' => 'endorser')) as $res) {
            ?>
									<option value="<?php 
            _e($res->data->ID);
            ?>
"><?php 
            _e($res->data->user_login . ' - ' . $res->data->user_email);
            ?>
</option>
									<?php 
        }
        ?>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="blogname">Gift Amount</label></th>
							<td>
								<select class="regular-text" id="gift_amount" name="gift_amount">
									<option value="5">5$</option>
									<option value="10">10$</option>
									<option value="25">25$</option>
									<option value="50">50$</option>
									<option value="100">100$</option>
									<option value="150">150$</option>
									<option value="200">200$</option>
								</select>
							</td>
						</tr>
					</table>
					<p class="submit">
						<input style="display:none;" id="send_gift" name="send_gift" class="button-primary seeker_btn" value="<?php 
        _e('Save Changes');
        ?>
" type="submit" />
					</p>
					</form>
				</div>
			</div>
		</div> 
		<?php 
    }
コード例 #12
0
ファイル: StripeClient.php プロジェクト: Daltonmedia/stripe
 /**
  * Get all invoices
  * @param mixed $cus_attr
  * @param string $limit				Number of invoices to retrieve
  * @param string $ending_before		ID of the first element in the previous list
  * @param string $starting_after	ID of the last element in the previous list
  * @param mixed $date
  * @return boolean
  */
 public function getInvoices($cus_attr = null, $limit = 10, $ending_before = null, $starting_after = null, $date = null)
 {
     try {
         $params = array_filter(array('limit' => $limit, 'ending_before' => $ending_before, 'starting_after' => $starting_after, 'date' => $date));
         $customer = new StripeCustomer($cus_attr);
         $params['customer'] = $customer->getCustomerAccount()->id;
         return Stripe_Invoice::all(array_filter($params), $this->access_token);
     } catch (Exception $ex) {
         $this->log($ex);
         return false;
     }
 }
コード例 #13
0
 /**
  * Get Next Invoice
  *
  * Get user next invoice details details
  */
 public function postGetUpcomingInvoice()
 {
     if ($this->_isValidRequest()) {
         // Include Stripe Library
         $this->_include_stripe_lib();
         $customer_id = $this->_get_stripe_customer_id();
         try {
             // Get customer's upcoming invoice
             $invoice = Stripe_Invoice::upcoming(array("customer" => $customer_id));
         } catch (Exception $e) {
             $this->_invalidRequest($e->getMessage());
         }
         if (!empty($invoice->lines)) {
             $invoice = json_decode($invoice);
             $lines_data = !empty($invoice->lines->data) ? $invoice->lines->data : NULL;
             $lines = NULL;
             if ($lines_data) {
                 foreach ($lines_data as $line) {
                     $lines[] = array('description' => $this->_get_stripe_invoice_line_description($line), 'amount' => $this->_format_stripe_amount($line->amount));
                 }
             }
             $invoiceObj = new StdClass();
             $invoiceObj->duration = date('M d, Y', $invoice->period_start) . ' to ' . date('M d, Y', $invoice->period_end);
             $invoiceObj->summary = array('subtotal' => $this->_format_stripe_amount($invoice->subtotal), 'total' => $this->_format_stripe_amount($invoice->total), 'amount_due' => $this->_format_stripe_amount($invoice->amount_due) . ' USD');
             $invoiceObj->lines = $lines;
             return Response::json($invoiceObj);
         }
     }
 }
コード例 #14
0
ファイル: invoice.php プロジェクト: sgh1986915/stripe-webhook
<?php

require 'lib/Stripe.php';
$cus_id = $_POST['cus_id'];
$sub_id = $_POST['sub_id'];
$stripeKey = "sk_test_9b496fHXP5VKKsecxIzFxMld";
date_default_timezone_set('UTC');
Stripe::setApiKey($stripeKey);
//$invoiceID = 'in_16jRNHGoIOM2Af5cmztSyj57';
$invoiceID = Stripe_Invoice::all(array("customer" => $cus_id))->data[0]->id;
$invoice = Stripe_Invoice::retrieve($invoiceID);
$customer = Stripe_Customer::retrieve($cus_id);
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Invoice</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Customer Invoice">
    <meta name="author" content="5marks">

    <link rel="stylesheet" href="css/bootstrap-min.css">
    <style>
      .invoice-head td {
        padding: 0 8px;
      }
      .container {
      	padding-top:30px;
      }
      .invoice-body{
コード例 #15
0
 public function external_hook($hook)
 {
     switch ($hook) {
         case 'event_ipn':
             require_once 'includes/plugin_paymethod_stripe/stripe-php/lib/Stripe.php';
             $stripe = array("secret_key" => module_config::c('payment_method_stripe_secret_key'), "publishable_key" => module_config::c('payment_method_stripe_publishable_key'));
             Stripe::setApiKey($stripe['secret_key']);
             $body = @file_get_contents('php://input');
             $event_json = json_decode($body);
             ob_start();
             //                 echo "INPUT: <br>\n";
             //                 print_r($body);
             //                 echo "<br><br>\n";
             echo "UCM STRIPE DEBUG:<br><br>JSON: <br>\n";
             print_r($event_json);
             echo "<br><br>\n";
             $event_id = $event_json->id;
             try {
                 $event = Stripe_Event::retrieve($event_id);
                 // This will send receipts on succesful invoices
                 if ($event->type == 'charge.succeeded' && $event->data->object->invoice) {
                     $paid_amount = $event->data->object->amount / 100;
                     // get the invoice.
                     $invoice = Stripe_Invoice::retrieve($event->data->object->invoice);
                     echo "INVOICE: <br>\n";
                     print_r($invoice);
                     echo "<br><br>\n";
                     if ($invoice && $invoice->subscription && $invoice->paid) {
                         // this payment was for a subscription! which one though?
                         $customer = Stripe_Customer::retrieve($invoice->customer);
                         echo "CUSTOMER: <br>\n";
                         print_r($customer);
                         echo "<br><br>\n";
                         $subscription = $customer->subscriptions->retrieve($invoice->subscription);
                         echo "SUBSCRIPTION: <br>\n";
                         print_r($subscription);
                         echo "<br><br>\n";
                         // now we have the Customer and Subscription we can look through our invoice_payment_subscription table for those values.
                         /*update_insert('invoice_payment_subscription_id',$invoice_payment_subscription_id,'invoice_payment_subscription',array(
                               'status' => _INVOICE_SUBSCRIPTION_ACTIVE,
                               'date_start' => date('Y-m-d'),
                           // we also have to store the stripe details here so we can easily search for them later on.
                           'stripe_customer' => $stripe_customer->id,
                           'stripe_subscription' => $stripe_subscription->id,
                           ));*/
                         $invoice_payment_subscription = get_single('invoice_payment_subscription', array('stripe_customer', 'stripe_subscription'), array($customer->id, $subscription->id));
                         if ($invoice_payment_subscription) {
                             // FIND THE linked invoice_payment for this original invoice payment subscription, this allows us to perform the same creatE_new_invoice as paypal below:
                             $invoice_payment_subscription_id = $invoice_payment_subscription['invoice_payment_subscription_id'];
                             $invoice_payment = get_single('invoice_payment', 'invoice_payment_subscription_id', $invoice_payment_subscription_id);
                             if ($invoice_payment) {
                                 $payment_id = $invoice_payment['invoice_payment_id'];
                                 $invoice_id = $invoice_payment['invoice_id'];
                                 // we have a subscription payment. woo!
                                 // this gets a bit tricky, we have to work out if the invoice has been generated for this subscription yet.
                                 // if this invoice hasn't been generated yet then we have to generate it.
                                 // pass this back to the invoice class so we can reuse this feature in the future.
                                 $data = module_invoice::create_new_invoice_for_subscription_payment($invoice_id, $payment_id, $invoice_payment_subscription_id);
                                 if ($data && $data['invoice_id'] && $data['invoice_payment_id']) {
                                     $next_time = time();
                                     $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['days']) . ' days', $next_time);
                                     $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['months']) . ' months', $next_time);
                                     $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['years']) . ' years', $next_time);
                                     update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('date_last_pay' => date('Y-m-d'), 'date_next' => date('Y-m-d', $next_time)));
                                     update_insert("invoice_payment_id", $data['invoice_payment_id'], "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $paid_amount, 'method' => 'Stripe (Subscription)', 'invoice_payment_subscription_id' => $invoice_payment_subscription_id));
                                     module_paymethod_stripe::add_payment_data($data['invoice_payment_id'], 'log', "Payment Received via Webhook: " . var_export(array('event.type' => $event->type, 'invoice.id' => $invoice->id, 'subscription.id' => $subscription->id, 'customer.id' => $customer->id, '$invoice_payment_subscription_id' => $invoice_payment_subscription_id, '$invoice_payment_id' => $payment_id), true));
                                     module_invoice::save_invoice($data['invoice_id'], array());
                                     echo "Successful Subscription Payment For Invoice " . $data['invoice_id'];
                                 } else {
                                     send_error("Stripe Webhook Subscription Error (failed to generate new invoice!) " . var_export($data, true));
                                 }
                             } else {
                                 echo 'Failed to find matching invoice payment in db';
                             }
                         } else {
                             echo 'Failed to find matching subscription payment in db';
                         }
                     }
                 }
             } catch (Exception $e) {
                 $body = $e->getJsonBody();
                 $err = $body['error'];
                 $error = "Sorry: Webhook failed. <br><br>\n\n";
                 $error .= $err['message'];
                 $error .= "\n\n\n" . var_export($e, true);
                 echo $error;
             }
             $debug = ob_get_clean();
             //mail('*****@*****.**','Stripe Webhook debug',$debug);
             if (module_config::c('stripe_payment_debug', 0)) {
                 echo $debug;
             }
             echo "Thanks! (set stripe_payment_debug to 1 in UCM to see more data here)";
             exit;
             break;
         case 'pay_subscription':
             $invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : false;
             $invoice_payment_id = isset($_REQUEST['invoice_payment_id']) ? $_REQUEST['invoice_payment_id'] : false;
             $invoice_payment_subscription_id = isset($_REQUEST['invoice_payment_subscription_id']) ? $_REQUEST['invoice_payment_subscription_id'] : false;
             $stripe_plan_id = isset($_REQUEST['stripe_plan_id']) ? $_REQUEST['stripe_plan_id'] : false;
             $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : false;
             if ($invoice_id && $invoice_payment_id && $stripe_plan_id && $invoice_payment_subscription_id && $user_id && isset($_POST['stripeToken'])) {
                 $user_data = module_user::get_user($user_id);
                 $email = isset($_REQUEST['stripeEmail']) && strlen($_REQUEST['stripeEmail']) ? $_REQUEST['stripeEmail'] : $user_data['email'];
                 if (!$email || !strpos($email, '@')) {
                     die('Please ensure your user account has a valid email address before paying with stripe');
                 }
                 $invoice_payment = get_single('invoice_payment', 'invoice_payment_id', $invoice_payment_id);
                 $invoice_payment_subscription = get_single('invoice_payment_subscription', 'invoice_payment_subscription_id', $invoice_payment_subscription_id);
                 if (!$invoice_payment || !$invoice_payment_subscription || $invoice_payment['invoice_id'] != $invoice_id || $invoice_payment['invoice_payment_subscription_id'] != $invoice_payment_subscription_id) {
                     die('Invalid invoice payment subscription id');
                 }
                 $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id);
                 $invoice_data = module_invoice::get_invoice($invoice_id);
                 if ($invoice_payment_data && $invoice_data && $invoice_id == $invoice_data['invoice_id'] && $invoice_payment_data['invoice_id'] == $invoice_data['invoice_id']) {
                     $currency = module_config::get_currency($invoice_payment_data['currency_id']);
                     $currency_code = $currency['code'];
                     $description = isset($_REQUEST['description']) ? $_REQUEST['description'] : 'N/A';
                     $template = new module_template();
                     ob_start();
                     require_once 'includes/plugin_paymethod_stripe/stripe-php/lib/Stripe.php';
                     $stripe = array("secret_key" => module_config::c('payment_method_stripe_secret_key'), "publishable_key" => module_config::c('payment_method_stripe_publishable_key'));
                     Stripe::setApiKey($stripe['secret_key']);
                     try {
                         // todo- search for existing customer based on email address???
                         // todo: check if adding new plan to existing customer work??
                         $stripe_customer = Stripe_Customer::create(array("card" => $_POST['stripeToken'], "email" => $email, 'metadata' => array('user_id' => $user_id)));
                         if ($stripe_customer && $stripe_customer->id) {
                             //} && $stripe_customer->subscriptions){
                             $stripe_subscription = $stripe_customer->subscriptions->create(array('plan' => $stripe_plan_id));
                             if ($stripe_subscription && $stripe_subscription->id) {
                                 update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'), 'stripe_customer' => $stripe_customer->id, 'stripe_subscription' => $stripe_subscription->id));
                                 module_paymethod_stripe::add_payment_data($invoice_payment_id, 'log', "Started Stripe Subscription: " . var_export(array('customer.id' => $stripe_customer->id, 'plan.id' => $stripe_plan_id, 'subscription.id' => $stripe_subscription->id), true));
                                 // success!
                                 // redirect to receipt page.
                                 redirect_browser(module_invoice::link_public_payment_complete($invoice_id));
                             } else {
                                 echo 'Failed to create subscription with stripe';
                             }
                         }
                         $error = "Something went wrong during stripe payment. Please confirm invoice payment went through: " . htmlspecialchars($description);
                         send_error($error);
                         echo $error;
                     } catch (Stripe_CardError $e) {
                         // The card has been declined
                         $body = $e->getJsonBody();
                         $err = $body['error'];
                         $error = "Sorry: Payment failed. <br><br>\n\n" . htmlspecialchars($description) . ". <br><br>\n\n";
                         $error .= $err['message'];
                         echo $error;
                         $error .= "\n\n\n" . var_export($err, true);
                         send_error($error);
                     } catch (Exception $e) {
                         $body = $e->getJsonBody();
                         $err = $body['error'];
                         $error = "Sorry: Payment failed. <br><br>\n\n" . htmlspecialchars($description) . ". <br><br>\n\n";
                         $error .= $err['message'];
                         echo $error;
                         $error .= "\n\n\n" . var_export($err, true);
                         send_error($error);
                     }
                     $template->content = ob_get_clean();
                     echo $template->render('pretty_html');
                     exit;
                 }
             }
             echo 'Error paying via Stripe';
             exit;
         case 'pay':
             $invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : false;
             $invoice_payment_id = isset($_REQUEST['invoice_payment_id']) ? $_REQUEST['invoice_payment_id'] : false;
             if ($invoice_id && $invoice_payment_id && isset($_POST['stripeToken'])) {
                 $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id);
                 $invoice_data = module_invoice::get_invoice($invoice_id);
                 if ($invoice_payment_data && $invoice_data && $invoice_id == $invoice_data['invoice_id'] && $invoice_payment_data['invoice_id'] == $invoice_data['invoice_id']) {
                     $currency = module_config::get_currency($invoice_payment_data['currency_id']);
                     $currency_code = $currency['code'];
                     $description = _l('Payment for invoice %s', $invoice_data['name']);
                     $template = new module_template();
                     ob_start();
                     include module_theme::include_ucm('includes/plugin_paymethod_stripe/pages/stripe_form.php');
                     $template->content = ob_get_clean();
                     echo $template->render('pretty_html');
                     exit;
                 }
             }
             echo 'Error paying via Stripe';
             exit;
     }
 }
コード例 #16
0
 public function getInvoices(User $user)
 {
     $customer_id = $user->getProfile() ? $user->getProfile()->getCustomerId() : null;
     if ($customer_id) {
         $invoices = \Stripe_Invoice::all(array("customer" => $customer_id));
         if ($invoices && $invoices->data) {
             return $invoices->data;
         }
     }
     return null;
 }
コード例 #17
0
 /**
  * Refund a payment or invoice
  * @param  object &$order         Related PMPro order object.
  * @param  string $transaction_id Payment or invoice id to void.
  * @return bool                   True or false if the refund worked.
  */
 function refund(&$order, $transaction_id = NULL)
 {
     //default to using the payment id from the order
     if (empty($transaction_id) && !empty($order->payment_transaction_id)) {
         $transaction_id = $order->payment_transaction_id;
     }
     //need a transaction id
     if (empty($transaction_id)) {
         return false;
     }
     //if an invoice ID is passed, get the charge/payment id
     if (strpos($transaction_id, "in_") !== false) {
         $invoice = Stripe_Invoice::retrieve($transaction_id);
         if (!empty($invoice) && !empty($invoice->payment)) {
             $transaction_id = $invoice->payment;
         }
     }
     //get the charge
     $charge = Stripe_Charge::retrieve($transaction_id);
     //can't find the charge?
     if (empty($charge)) {
         $order->status = "error";
         $order->errorcode = "";
         $order->error = "";
         $order->shorterror = "";
         return false;
     }
     //attempt refund
     try {
         $refund = $charge->refund();
     } catch (Exception $e) {
         //$order->status = "error";
         $order->errorcode = true;
         $order->error = __("Error: ", "pmpro") . $e->getMessage();
         $order->shorterror = $order->error;
         return false;
     }
     if ($refund->status == "succeeded") {
         $order->status = "refunded";
         $order->saveOrder();
         return true;
     } else {
         $order->status = "error";
         $order->errorcode = true;
         $order->error = sprintf(__("Error: Unkown error while refunding charge #%s", "pmpro"), $transaction_id);
         $order->shorterror = $order->error;
         return false;
     }
 }
コード例 #18
0
ファイル: stripe.trt.php プロジェクト: carriercomm/atikit
 public function stripe_getInvoice($invoice)
 {
     try {
         $inv = Stripe_Invoice::retrieve($invoice);
         return $inv;
     } catch (Exception $e) {
         return false;
     }
 }
コード例 #19
0
<?php

require_once './config.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $postdata = file_get_contents("php://input");
    $event = json_decode($postdata);
    if ($event->type == 'invoice.payment_succeeded') {
        $customer_id = $event->data->object->customer;
        $customer = Stripe_Customer::retrieve($customer_id);
        $invoice = Stripe_Invoice::retrieve($event->data->object->id);
        // This is where we'd normally e-mail the invoice, but we'll just write out the invoice to a file instead.
        $from = "From: Oscar Wilde";
        $to = "To: " . $customer->email;
        $subject = "Subject: You have made a payment for another month of Wilde quotes";
        $body = "You have made a new payment for \$" . $invoice->total / 100.0 . ":\n\n";
        foreach ($invoice->lines->data as &$line) {
            if ($line->type == 'subscription') {
                $body .= "Subscription - " . $line->plan->name . ": " . $line->amount . "\n";
            } else {
                if ($line->type == 'invoiceitem') {
                    $body .= "Additional -" . $line->description . ": " . $line->amount;
                }
            }
        }
        $email_file = fopen('/public/' . $customer->id . "-" . $invoice->date, 'a');
        $email = $from . "\n" . $to . "\n" . $subject . "\n" . $body;
        fwrite($email_file, $email);
    }
}
コード例 #20
0
/**
 * Process stripe checkout submission
 *
 * @access      public
 * @since       1.0
 * @return      void
 */
function edds_process_stripe_payment($purchase_data)
{
    global $edd_options;
    if (!class_exists('Stripe')) {
        require_once EDDS_PLUGIN_DIR . '/Stripe/Stripe.php';
    }
    if (edd_is_test_mode()) {
        $secret_key = trim($edd_options['test_secret_key']);
    } else {
        $secret_key = trim($edd_options['live_secret_key']);
    }
    $purchase_summary = edd_get_purchase_summary($purchase_data, false);
    // make sure we don't have any left over errors present
    edd_clear_errors();
    if (!isset($_POST['edd_stripe_token'])) {
        // check for fallback mode
        if (isset($edd_options['stripe_js_fallback'])) {
            if (!isset($_POST['card_name']) || strlen(trim($_POST['card_name'])) == 0) {
                edd_set_error('no_card_name', __('Please enter a name for the credit card.', 'edds'));
            }
            if (!isset($_POST['card_number']) || strlen(trim($_POST['card_number'])) == 0) {
                edd_set_error('no_card_number', __('Please enter a credit card number.', 'edds'));
            }
            if (!isset($_POST['card_cvc']) || strlen(trim($_POST['card_cvc'])) == 0) {
                edd_set_error('no_card_cvc', __('Please enter a CVC/CVV for the credit card.', 'edds'));
            }
            if (!isset($_POST['card_exp_month']) || strlen(trim($_POST['card_exp_month'])) == 0) {
                edd_set_error('no_card_exp_month', __('Please enter a expiration month.', 'edds'));
            }
            if (!isset($_POST['card_exp_year']) || strlen(trim($_POST['card_exp_year'])) == 0) {
                edd_set_error('no_card_exp_year', __('Please enter a expiration year.', 'edds'));
            }
            $card_data = array('number' => $purchase_data['card_info']['card_number'], 'name' => $purchase_data['card_info']['card_name'], 'exp_month' => $purchase_data['card_info']['card_exp_month'], 'exp_year' => $purchase_data['card_info']['card_exp_year'], 'cvc' => $purchase_data['card_info']['card_cvc'], 'address_line1' => $purchase_data['card_info']['card_address'], 'address_line2' => $purchase_data['card_info']['card_address_2'], 'address_city' => $purchase_data['card_info']['card_city'], 'address_zip' => $purchase_data['card_info']['card_zip'], 'address_state' => $purchase_data['card_info']['card_state'], 'address_country' => $purchase_data['card_info']['card_country']);
        } else {
            // no Stripe token
            edd_set_error('no_token', __('Missing Stripe token. Please contact support.', 'edds'));
            edd_record_gateway_error(__('Missing Stripe Token', 'edds'), __('A Stripe token failed to be generated. Please check Stripe logs for more information', ' edds'));
        }
    } else {
        $card_data = $_POST['edd_stripe_token'];
    }
    $errors = edd_get_errors();
    if (!$errors) {
        try {
            Stripe::setApiKey($secret_key);
            // setup the payment details
            $payment_data = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => edd_get_currency(), 'downloads' => $purchase_data['downloads'], 'cart_details' => $purchase_data['cart_details'], 'user_info' => $purchase_data['user_info'], 'status' => 'pending', 'gateway' => 'stripe');
            $customer_exists = false;
            if (is_user_logged_in()) {
                $user = get_user_by('email', $purchase_data['user_email']);
                if ($user) {
                    $customer_id = get_user_meta($user->ID, edd_stripe_get_customer_key(), true);
                    if ($customer_id) {
                        $customer_exists = true;
                        try {
                            // Update the customer to ensure their card data is up to date
                            $cu = Stripe_Customer::retrieve($customer_id);
                            if (isset($cu->deleted) && $cu->deleted) {
                                // This customer was deleted
                                $customer_exists = false;
                            } else {
                                $cu->card = $card_data;
                                $cu->save();
                            }
                            // No customer found
                        } catch (Exception $e) {
                            $customer_exists = false;
                        }
                    }
                }
            }
            if (!$customer_exists) {
                // Create a customer first so we can retrieve them later for future payments
                $customer = Stripe_Customer::create(array('description' => $purchase_data['user_email'], 'email' => $purchase_data['user_email'], 'card' => $card_data));
                $customer_id = is_array($customer) ? $customer['id'] : $customer->id;
                if (is_user_logged_in()) {
                    update_user_meta($user->ID, edd_stripe_get_customer_key(), $customer_id);
                }
            }
            if (edds_is_recurring_purchase($purchase_data) && (!empty($customer) || $customer_exists)) {
                // Process a recurring subscription purchase
                $cu = Stripe_Customer::retrieve($customer_id);
                /**********************************************************
                 * Taxes, fees, and discounts have to be handled differently
                 * with recurring subscriptions, so each is added as an
                 * invoice item and then charged as one time items
                 **********************************************************/
                $invoice_items = array();
                $needs_invoiced = false;
                if ($purchase_data['tax'] > 0 && !edd_prices_include_tax()) {
                    if (edds_is_zero_decimal_currency()) {
                        $tax = $purchase_data['tax'];
                    } else {
                        $tax = $purchase_data['tax'] * 100;
                    }
                    $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $tax, 'currency' => edd_get_currency(), 'description' => sprintf(__('Sales tax for order %s', 'edds'), $purchase_data['purchase_key'])));
                    if (!empty($invoice->id)) {
                        $invoice_items[] = $invoice->id;
                    }
                    $needs_invoiced = true;
                }
                if (!empty($purchase_data['fees'])) {
                    foreach ($purchase_data['fees'] as $fee) {
                        if (edds_is_zero_decimal_currency()) {
                            $fee_amount = $fee['amount'];
                        } else {
                            $fee_amount = $fee['amount'] * 100;
                        }
                        $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $fee_amount, 'currency' => edd_get_currency(), 'description' => $fee['label']));
                        if (!empty($invoice->id)) {
                            $invoice_items[] = $invoice->id;
                        }
                    }
                    $needs_invoiced = true;
                }
                if ($purchase_data['discount'] > 0) {
                    if (edds_is_zero_decimal_currency()) {
                        $discount_amount = $purchase_data['discount'];
                    } else {
                        $discount_amount = $purchase_data['discount'] * 100;
                    }
                    $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $discount_amount * -1, 'currency' => edd_get_currency(), 'description' => $purchase_data['user_info']['discount']));
                    if (!empty($invoice->id)) {
                        $invoice_items[] = $invoice->id;
                    }
                    $needs_invoiced = true;
                }
                try {
                    $plan_id = edds_get_plan_id($purchase_data);
                    // record the pending payment
                    $payment = edd_insert_payment($payment_data);
                    set_transient('_edd_recurring_payment_' . $payment, '1', DAY_IN_SECONDS);
                    // Store the parent payment ID in the user meta
                    EDD_Recurring_Customer::set_customer_payment_id($user->ID, $payment);
                    // Update the customer's subscription in Stripe
                    $customer_response = $cu->updateSubscription(array('plan' => $plan_id));
                    // Set user as subscriber
                    EDD_Recurring_Customer::set_as_subscriber($user->ID);
                    // store the customer recurring ID
                    EDD_Recurring_Customer::set_customer_id($user->ID, $customer_id);
                    // Set the customer status
                    EDD_Recurring_Customer::set_customer_status($user->ID, 'active');
                    // Calculate the customer's new expiration date
                    $new_expiration = EDD_Recurring_Customer::calc_user_expiration($user->ID, $payment);
                    // Set the customer's new expiration date
                    EDD_Recurring_Customer::set_customer_expiration($user->ID, $new_expiration);
                } catch (Stripe_CardError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    if (isset($err['message'])) {
                        edd_set_error('payment_error', $err['message']);
                    } else {
                        edd_set_error('payment_error', __('There was an error processing your payment, please ensure you have entered your card number correctly.', 'edds'));
                    }
                    edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error while processing a Stripe payment. Payment data: %s', ' edds'), json_encode($err)), 0);
                } catch (Stripe_ApiConnectionError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    edd_set_error('payment_error', __('There was an error processing your payment (Stripe\'s API is down), please try again', 'edds'));
                    edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error processing your payment (Stripe\'s API was down). Error: %s', 'edds'), json_encode($err['message'])), 0);
                } catch (Stripe_InvalidRequestError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    // Bad Request of some sort. Maybe Christoff was here ;)
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('request_error', sprintf(__('The Stripe API request was invalid, please try again. Error: %s', 'edds'), json_encode($err['message'])));
                    }
                } catch (Stripe_ApiError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds'));
                    }
                    edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error with Stripe\'s API: ', 'edds'), json_encode($err['message'])), 0);
                } catch (Stripe_AuthenticationError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    // Authentication error. Stripe keys in settings are bad.
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('api_error', __('The API keys entered in settings are incorrect', 'edds'));
                    }
                } catch (Stripe_Error $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    // generic stripe error
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('api_error', __('Something went wrong.', 'edds'));
                    }
                } catch (Exception $e) {
                    // some sort of other error
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('api_error', __('Something went wrong.', 'edds'));
                    }
                }
                if (!empty($err)) {
                    // Delete any invoice items we created for fees, taxes, and other
                    foreach ($invoice_items as $invoice) {
                        $ii = Stripe_InvoiceItem::retrieve($invoice);
                        $ii->delete();
                    }
                    edd_send_back_to_checkout('?payment-mode=stripe');
                }
            } elseif (!empty($customer) || $customer_exists) {
                // Process a normal one-time charge purchase
                if (!isset($edd_options['stripe_preapprove_only'])) {
                    if (edds_is_zero_decimal_currency()) {
                        $amount = $purchase_data['price'];
                    } else {
                        $amount = $purchase_data['price'] * 100;
                    }
                    $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => edd_get_currency(), "customer" => $customer_id, "description" => html_entity_decode($purchase_summary, ENT_COMPAT, 'UTF-8'), 'statement_description' => substr($purchase_summary, 0, 15), 'metadata' => array('email' => $purchase_data['user_info']['email'])));
                }
                // record the pending payment
                $payment = edd_insert_payment($payment_data);
            } else {
                edd_record_gateway_error(__('Customer Creation Failed', 'edds'), sprintf(__('Customer creation failed while processing a payment. Payment Data: %s', ' edds'), json_encode($payment_data)), $payment);
            }
            if ($payment && (!empty($customer_id) || !empty($charge))) {
                if (!empty($needs_invoiced)) {
                    try {
                        // Create the invoice containing taxes / discounts / fees
                        $invoice = Stripe_Invoice::create(array('customer' => $customer_id));
                        $invoice = $invoice->pay();
                    } catch (Exception $e) {
                        // If there is nothing to pay, it just means the invoice item was taken care of with the subscription payment
                    }
                }
                if (isset($edd_options['stripe_preapprove_only'])) {
                    edd_update_payment_status($payment, 'preapproval');
                    add_post_meta($payment, '_edds_stripe_customer_id', $customer_id);
                } else {
                    edd_update_payment_status($payment, 'publish');
                }
                // You should be using Stripe's API here to retrieve the invoice then confirming it's been paid
                if (!empty($charge)) {
                    edd_insert_payment_note($payment, 'Stripe Charge ID: ' . $charge->id);
                    if (function_exists('edd_set_payment_transaction_id')) {
                        edd_set_payment_transaction_id($payment, $charge->id);
                    }
                } elseif (!empty($customer_id)) {
                    edd_insert_payment_note($payment, 'Stripe Customer ID: ' . $customer_id);
                }
                edd_empty_cart();
                edd_send_to_success_page();
            } else {
                edd_set_error('payment_not_recorded', __('Your payment could not be recorded, please contact the site administrator.', 'edds'));
                // if errors are present, send the user back to the purchase page so they can be corrected
                edd_send_back_to_checkout('?payment-mode=stripe');
            }
        } catch (Stripe_CardError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            if (isset($err['message'])) {
                edd_set_error('payment_error', $err['message']);
            } else {
                edd_set_error('payment_error', __('There was an error processing your payment, please ensure you have entered your card number correctly.', 'edds'));
            }
            edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error while processing a Stripe payment. Payment data: %s', ' edds'), json_encode($err)), 0);
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_ApiConnectionError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            edd_set_error('payment_error', __('There was an error processing your payment (Stripe\'s API is down), please try again', 'edds'));
            edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error processing your payment (Stripe\'s API was down). Error: %s', 'edds'), json_encode($err['message'])), 0);
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_InvalidRequestError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            // Bad Request of some sort. Maybe Christoff was here ;)
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_ApiError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds'));
            }
            edd_set_error('request_error', sprintf(__('The Stripe API request was invalid, please try again. Error: %s', 'edds'), json_encode($err['message'])));
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_AuthenticationError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            // Authentication error. Stripe keys in settings are bad.
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('api_error', __('The API keys entered in settings are incorrect', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_Error $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            // generic stripe error
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('api_error', __('Something went wrong.', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Exception $e) {
            // some sort of other error
            $body = $e->getJsonBody();
            $err = $body['error'];
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('api_error', __('Something went wrong.', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        }
    } else {
        edd_send_back_to_checkout('?payment-mode=stripe');
    }
}
コード例 #21
0
function getOldOrderFromInvoiceEvent($event)
{
    //pause here to give PMPro a chance to finish checkout
    sleep(PMPRO_STRIPE_WEBHOOK_DELAY);
    global $wpdb;
    $customer_id = $event->data->object->customer;
    // no customer passed? we can't cross reference
    if (empty($customer_id)) {
        return false;
    }
    // okay, add an invoice. first lookup the user_id from the subscription id passed
    $old_order_id = $wpdb->get_var("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE subscription_transaction_id = '" . $customer_id . "' AND gateway = 'stripe' ORDER BY timestamp DESC LIMIT 1");
    // since v1.8, PMPro may store the Stripe subscription_id (sub_XXXX) instead of the Stripe customer_id (cus_XXXX)
    // so that last query may turn up an empty result
    if (empty($old_order_id)) {
        // let's look up the Stripe subscription_id instead
        // unfortunately, the subscription_id is not included in the JSON data from the Stripe event
        // so, we must look up the subscription_id from the invoice_id, which IS included in the JSON data from the Stripe event
        $invoice_id = $event->data->object->invoice;
        $invoice = Stripe_Invoice::retrieve($invoice_id);
        $subscription_id = $invoice->subscription;
        $old_order_id = $wpdb->get_var("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE subscription_transaction_id = '" . $subscription_id . "' AND gateway = 'stripe' ORDER BY timestamp DESC LIMIT 1");
    }
    $old_order = new MemberOrder($old_order_id);
    if (!empty($old_order->id)) {
        return $old_order;
    } else {
        return false;
    }
}
コード例 #22
0
 public function invoices($data)
 {
     global $WishListMemberInstance;
     global $current_user;
     if (empty($current_user->ID)) {
         return;
     }
     $cust_id = $this->wlm->Get_UserMeta($current_user->ID, 'stripe_cust_id');
     try {
         $stripeapikey = $this->wlm->GetOption('stripeapikey');
         $txns = $this->wlm->GetMembershipLevelsTxnIDs($current_user->ID);
         Stripe::setApiKey($stripeapikey);
         $inv = Stripe_Invoice::all(array('count' => 100, 'customer' => $cust_id));
         $invoices = array();
         if (!empty($inv['data'])) {
             $invoices = array_merge($invoices, $inv['data']);
         }
         //try to get manual charges
         //$manual_charges = Stripe_Charge::all(array("count" => 100, 'customer' => $cust_id));
         // $invoices = array_merge($invoices, $inv['data']);
         //var_dump($manual_charges);
         include $this->get_view_path('invoice_list');
         die;
     } catch (Exception $e) {
         echo __("<p>No invoices found for this user</p>", "wishlist-member");
         die;
     }
 }