public function do_charge() { if (wp_verify_nonce($_POST['wp-simple-pay-pro-nonce'], 'charge_card')) { global $sc_options; $query_args = array(); // Set redirect $redirect = $_POST['sc-redirect']; $fail_redirect = $_POST['sc-redirect-fail']; $failed = null; $message = ''; // Get the credit card details submitted by the form $token = $_POST['stripeToken']; $amount = $_POST['sc-amount']; $description = $_POST['sc-description']; $store_name = $_POST['sc-name']; $currency = $_POST['sc-currency']; $details_placement = $_POST['sc-details-placement']; $charge = null; $sub = isset($_POST['sc_sub_id']); $interval = isset($_POST['sc_sub_interval']) ? $_POST['sc_sub_interval'] : 'month'; $interval_count = isset($_POST['sc_sub_interval_count']) ? $_POST['sc_sub_interval_count'] : 1; $statement_description = isset($_POST['sc_sub_statement_description']) ? $_POST['sc_sub_statement_description'] : ''; $setup_fee = isset($_POST['sc_sub_setup_fee']) ? $_POST['sc_sub_setup_fee'] : 0; $coupon = isset($_POST['sc_coup_coupon_code']) ? $_POST['sc_coup_coupon_code'] : ''; $test_mode = isset($_POST['sc_test_mode']) ? $_POST['sc_test_mode'] : 'false'; if ($sub) { $sub = !empty($_POST['sc_sub_id']) ? $_POST['sc_sub_id'] : 'custom'; } Stripe_Checkout_Functions::set_key($test_mode); $meta = array(); if (!empty($setup_fee)) { $meta['Setup Fee'] = Stripe_Checkout_Misc::to_formatted_amount($setup_fee, $currency); } $meta = apply_filters('sc_meta_values', $meta); try { if ($sub == 'custom') { $timestamp = time(); $plan_id = $_POST['stripeEmail'] . '_' . $amount . '_' . $timestamp; $name = __('Subscription:', 'sc_sub') . ' ' . Stripe_Checkout_Misc::to_formatted_amount($amount, $currency) . ' ' . strtoupper($currency) . '/' . $interval; // Create a plan $plan_args = array('amount' => $amount, 'interval' => $interval, 'name' => $name, 'currency' => $currency, 'id' => $plan_id, 'interval_count' => $interval_count); if (!empty($statement_description)) { $plan_args['statement_descriptor'] = $statement_description; } $new_plan = \Stripe\Plan::create($plan_args); // Create a customer and charge $new_customer = \Stripe\Customer::create(array('email' => $_POST['stripeEmail'], 'card' => $token, 'plan' => $plan_id, 'metadata' => $meta, 'account_balance' => $setup_fee)); } else { // Create new customer $cust_args = array('email' => $_POST['stripeEmail'], 'card' => $token, 'plan' => $sub, 'metadata' => $meta, 'account_balance' => $setup_fee); if (!empty($coupon)) { $cust_args['coupon'] = $coupon; } $new_customer = \Stripe\Customer::create($cust_args); // Set currency based on sub $plan = \Stripe\Plan::retrieve($sub); //echo $subscription . '<Br>'; $currency = strtoupper($plan->currency); } // We want to add the meta data and description to the actual charge so that users can still view the meta sent with a subscription + custom fields // the same way that they would normally view it without subscriptions installed. // We need the steps below to do this // First we get the latest invoice based on the customer ID $invoice = \Stripe\Invoice::all(array('customer' => $new_customer->id, 'limit' => 1)); // If this is a trial we need to skip this part since a charge is not made $trial = $invoice->data[0]->lines->data[0]->plan->trial_period_days; if (empty($trial) || !empty($setup_fee)) { // Now that we have the invoice object we can get the charge ID $inv_charge = $invoice->data[0]->charge; // Finally, with the charge ID we can update the specific charge and inject our meta data sent from Stripe Custom Fields $ch = \Stripe\Charge::retrieve($inv_charge); $charge = $ch; if (!empty($meta)) { $ch->metadata = $meta; } if (!empty($description)) { $ch->description = $description; } $ch->save(); $query_args = array('charge' => $ch->id, 'store_name' => urlencode($store_name)); $failed = false; } else { $sub_id = $invoice->data[0]->subscription; if (!empty($description)) { $customer = \Stripe\Customer::retrieve($new_customer->id); $subscription = $customer->subscriptions->retrieve($sub_id); $subscription->metadata = array('product' => $description); $subscription->save(); } $query_args = array('cust_id' => $new_customer->id, 'sub_id' => $sub_id, 'store_name' => urlencode($store_name)); $failed = false; } } catch (Exception $e) { // Something else happened, completely unrelated to Stripe $redirect = $fail_redirect; $failed = true; $e = $e->getJsonBody(); $query_args = array('sub' => true, 'error_code' => $e['error']['type'], 'charge_failed' => true); } unset($_POST['stripeToken']); do_action('sc_redirect_before'); if ($test_mode == 'true') { $query_args['test_mode'] = 'true'; } if ('below' == $details_placement) { $query_args['details_placement'] = $details_placement; } if (!empty($trial) && empty($setup_fee)) { $query_args['trial'] = 1; } wp_redirect(esc_url_raw(add_query_arg(apply_filters('sc_redirect_args', $query_args, $charge), apply_filters('sc_redirect', $redirect, $failed)))); exit; } }
/** * Gets info for a charge. * * @return array|null */ public function info() { if (!$this->id || !$this->stripe_customer) { return null; } if (!$this->stripe_charge) { $this->stripe_charge = Stripe_Charge::retrieve($this->id); if ($this->stripe_customer->id != $this->stripe_charge->customer) { return $this->stripe_charge = null; } } if (!$this->stripe_charge) { return null; } return array('id' => $this->id, 'created_at' => date('Y-m-d H:i:s', $this->stripe_charge->created), 'amount' => $this->stripe_charge->amount, 'paid' => $this->stripe_charge->paid, 'refunded' => $this->stripe_charge->refunded, 'captured' => $this->stripe_charge->captured, 'card' => $this->stripe_charge->source ? $this->stripe_charge->source->id : null, 'invoice_id' => $this->stripe_charge->invoice, 'description' => $this->stripe_charge->description); }
/** * Gerer la reponse du POST JS sur paiement/abonnement * @param array $config * @param array $response * @return array */ function stripe_traite_reponse_transaction($config, &$response) { $mode = $config['presta']; if (isset($config['mode_test']) and $config['mode_test']) { $mode .= "_test"; } $config_id = bank_config_id($config); $is_abo = (isset($response['abo']) and $response['abo']); if (!isset($response['id_transaction']) or !isset($response['transaction_hash'])) { return bank_transaction_invalide(0, array('mode' => $mode, 'erreur' => "transaction inconnue", 'log' => var_export($response, true))); } if ((!isset($response['charge_id']) or !$response['charge_id']) and (!isset($response['token']) or !$response['token'])) { return bank_transaction_invalide(0, array('mode' => $mode, 'erreur' => "token/charge_id absent dans la reponse", 'log' => var_export($response, true))); } $id_transaction = $response['id_transaction']; $transaction_hash = $response['transaction_hash']; if (!($row = sql_fetsel('*', 'spip_transactions', 'id_transaction=' . intval($id_transaction)))) { return bank_transaction_invalide($id_transaction, array('mode' => $mode, 'erreur' => "transaction non trouvee", 'log' => var_export($response, true))); } if ($transaction_hash != $row['transaction_hash']) { return bank_transaction_invalide($id_transaction, array('mode' => $mode, 'erreur' => "hash {$transaction_hash} non conforme", 'log' => var_export($response, true))); } $montant = intval(round(100 * $row['montant'], 0)); if (strlen($montant) < 3) { $montant = str_pad($montant, 3, '0', STR_PAD_LEFT); } $email = bank_porteur_email($row); // ok, on traite le reglement $date = $_SERVER['REQUEST_TIME']; $date_paiement = date('Y-m-d H:i:s', $date); $erreur = ""; $erreur_code = 0; // charger l'API Stripe avec la cle stripe_init_api($config); // preparer le paiement $nom_site = textebrut($GLOBALS['meta']['nom_site']); $desc_charge = array('amount' => $montant, "currency" => "eur", "source" => $response['token'], "description" => "Transaction #" . $id_transaction . " [{$nom_site}]", "receipt_email" => $email, "metadata" => array('id_transaction' => $id_transaction, 'id_auteur' => $row['id_auteur'], 'nom_site' => $nom_site, 'url_site' => $GLOBALS['meta']['adresse_site'])); // la charge existe deja (autoresponse webhook sur abonnement) if (isset($response['charge_id']) and $response['charge_id']) { try { $charge = \Stripe\Charge::retrieve($response['charge_id']); $charge->description = $desc_charge['description']; $charge->metadata = $desc_charge['metadata']; $charge->save(); if (!$charge->paid) { $erreur_code = 'unpaid'; $erreur = 'payment failed'; } } catch (Exception $e) { if ($body = $e->getJsonBody()) { $err = $body['error']; list($erreur_code, $erreur) = stripe_error_code($err); } else { $erreur = $e->getMessage(); $erreur_code = 'error'; } } } else { // est-ce un abonnement ? if ($is_abo) { // on decrit l'echeance if ($decrire_echeance = charger_fonction("decrire_echeance", "abos", true) and $echeance = $decrire_echeance($id_transaction)) { if ($echeance['montant'] > 0) { $montant_echeance = intval(round(100 * $echeance['montant'], 0)); if (strlen($montant_echeance) < 3) { $montant_echeance = str_pad($montant_echeance, 3, '0', STR_PAD_LEFT); } $interval = 'month'; if (isset($echeance['freq']) and $echeance['freq'] == 'yearly') { $interval = 'year'; } $desc_plan = array('amount' => $montant_echeance, 'interval' => $interval, 'name' => "#{$id_transaction} [{$nom_site}]", 'currency' => $desc_charge['currency'], 'metadata' => $desc_charge['metadata']); // dans tous les cas on fait preleve la premiere echeance en paiement unique // et en faisant démarrer l'abonnement par "1 periode" en essai sans paiement // ca permet de gerer le cas paiement initial different, et de recuperer les infos de CB dans tous les cas $time_start = strtotime($date_paiement); $time_paiement_1_interval = strtotime("+1 {$interval}", $time_start); $nb_days = intval(round(($time_paiement_1_interval - $time_start) / 86400)); $desc_plan['trial_period_days'] = $nb_days; // un id unique (sauf si on rejoue le meme paiement) $desc_plan['id'] = md5(json_encode($desc_plan) . "-{$transaction_hash}"); try { $plan = \Stripe\Plan::retrieve($desc_plan['id']); } catch (Exception $e) { // erreur si on ne retrouve pas le plan, on ignore $plan = false; } try { if (!$plan) { $plan = \Stripe\Plan::create($desc_plan); } if (!$plan) { $erreur = "Erreur creation plan d'abonnement"; $erreur_code = "plan_failed"; } } catch (Exception $e) { if ($body = $e->getJsonBody()) { $err = $body['error']; list($erreur_code, $erreur) = stripe_error_code($err); } else { $erreur = $e->getMessage(); $erreur_code = 'error'; } } if ($erreur or $erreur_code) { // regarder si l'annulation n'arrive pas apres un reglement (internaute qui a ouvert 2 fenetres de paiement) if ($row['reglee'] == 'oui') { return array($id_transaction, true); } // sinon enregistrer l'absence de paiement et l'erreur return bank_transaction_echec($id_transaction, array('mode' => $mode, 'config_id' => $config_id, 'date_paiement' => $date_paiement, 'code_erreur' => $erreur_code, 'erreur' => $erreur, 'log' => var_export($response, true))); } } } } // essayer de retrouver ou creer un customer pour l'id_auteur $customer = null; try { if ($row['id_auteur']) { $customer_id = sql_getfetsel('pay_id', 'spip_transactions', 'pay_id!=' . sql_quote('') . ' AND id_auteur=' . intval($row['id_auteur']) . ' AND statut=' . sql_quote('ok') . ' AND mode=' . sql_quote("{$mode}/{$config_id}"), '', 'date_paiement DESC', '0,1'); if ($customer_id) { $customer = \Stripe\Customer::retrieve($customer_id); } } // si customer retrouve, on ajoute la source et la transaction if ($customer and $customer->email === $email) { $customer->source = $desc_charge['source']; $metadata = $customer->metadata; if (!$metadata) { $metadata = array(); } if (isset($metadata['id_transaction'])) { $metadata['id_transaction'] .= ',' . $id_transaction; } else { $metadata['id_transaction'] = $id_transaction; } $metadata['id_auteur'] = $row['id_auteur']; $customer->metadata = $metadata; $customer->description = sql_getfetsel('nom', 'spip_auteurs', 'id_auteur=' . intval($row['id_auteur'])); $customer->save(); } else { $d = array('email' => $email, 'source' => $desc_charge['source'], 'metadata' => $desc_charge['metadata']); if ($row['id_auteur']) { $d['description'] = sql_getfetsel('nom', 'spip_auteurs', 'id_auteur=' . intval($row['id_auteur'])); } $customer = \Stripe\Customer::create($d); } if ($is_abo and !$customer) { $erreur = "Erreur creation customer"; $erreur_code = "cust_failed"; } } catch (Exception $e) { if ($body = $e->getJsonBody()) { $err = $body['error']; list($erreur_code, $erreur) = stripe_error_code($err); } else { $erreur = $e->getMessage(); $erreur_code = 'error'; } spip_log("Echec creation/recherche customer transaction #{$id_transaction} {$erreur}", $mode . _LOG_ERREUR); } if ($is_abo and ($erreur or $erreur_code)) { // regarder si l'annulation n'arrive pas apres un reglement (internaute qui a ouvert 2 fenetres de paiement) if ($row['reglee'] == 'oui') { return array($id_transaction, true); } // sinon enregistrer l'absence de paiement et l'erreur return bank_transaction_echec($id_transaction, array('mode' => $mode, 'config_id' => $config_id, 'date_paiement' => $date_paiement, 'code_erreur' => $erreur_code, 'erreur' => $erreur, 'log' => var_export($response, true))); } // Create a charge if needed: this will charge the user's card try { // If we have a Customer if ($customer and $customer->id) { $desc_charge['customer'] = $customer->id; $response['pay_id'] = $customer->id; // permet de faire de nouveau paiement sans saisie CB unset($desc_charge['source']); } if ($desc_charge['amount']) { $charge = \Stripe\Charge::create($desc_charge); // pour les logs en cas d'echec $r = $charge->getLastResponse()->json; $response = array_merge($response, $r); if (!$charge) { $erreur = "Erreur creation charge"; $erreur_code = "charge_failed"; } elseif (!$charge['paid']) { $erreur_code = 'not_paid'; $erreur = 'echec paiement stripe'; if ($charge['failure_code'] or $charge['failure_message']) { $erreur_code = $charge['failure_code']; $erreur = $charge['failure_message']; } } } } catch (\Stripe\Error\Card $e) { // Since it's a decline, \Stripe\Error\Card will be caught $body = $e->getJsonBody(); $err = $body['error']; list($erreur_code, $erreur) = stripe_error_code($err); } catch (Exception $e) { if ($body = $e->getJsonBody()) { $err = $body['error']; list($erreur_code, $erreur) = stripe_error_code($err); } else { $erreur = $e->getMessage(); $erreur_code = 'error'; } } // si abonnement : on a un customer et un plan, creer la subscription if ($is_abo) { if ($plan and $customer) { $desc_sub = array('customer' => $customer->id, 'plan' => $plan->id, 'metadata' => array('id_transaction' => $id_transaction)); try { $sub = \Stripe\Subscription::create($desc_sub); if (!$sub) { $erreur = "Erreur creation subscription"; $erreur_code = "sub_failed"; } else { $response['abo_uid'] = $sub->id; } } catch (Exception $e) { if ($body = $e->getJsonBody()) { $err = $body['error']; list($erreur_code, $erreur) = stripe_error_code($err); } else { $erreur = $e->getMessage(); $erreur_code = 'error'; } } } else { $erreur = "Erreur creation subscription (plan or customer missing)"; $erreur_code = "sub_failed"; } } } if ($erreur or $erreur_code) { // regarder si l'annulation n'arrive pas apres un reglement (internaute qui a ouvert 2 fenetres de paiement) if ($row['reglee'] == 'oui') { return array($id_transaction, true); } // sinon enregistrer l'absence de paiement et l'erreur return bank_transaction_echec($id_transaction, array('mode' => $mode, 'config_id' => $config_id, 'date_paiement' => $date_paiement, 'code_erreur' => $erreur_code, 'erreur' => $erreur, 'log' => var_export($response, true))); } // Ouf, le reglement a ete accepte // on verifie que le montant est bon ! $montant_regle = 0; if ($charge) { $montant_regle = $charge['amount'] / 100; } elseif ($sub) { $montant_regle = $sub->plan->amount; } if ($montant_regle != $row['montant']) { spip_log($t = "call_response : id_transaction {$id_transaction}, montant regle {$montant_regle}!=" . $row['montant'] . ":" . var_export($charge, true), $mode); // on log ca dans un journal dedie spip_log($t, $mode . '_reglements_partiels'); } if ($charge) { $transaction = $charge['balance_transaction']; $authorisation_id = $charge['id']; } elseif ($sub) { $transaction = $sub->id; $authorisation_id = $plan->id; } $set = array("autorisation_id" => "{$transaction}/{$authorisation_id}", "mode" => "{$mode}/{$config_id}", "montant_regle" => $montant_regle, "date_paiement" => $date_paiement, "statut" => 'ok', "reglee" => 'oui'); if (isset($response['pay_id'])) { $set['pay_id'] = $response['pay_id']; } if (isset($response['abo_uid'])) { $set['abo_uid'] = $response['abo_uid']; } // type et numero de carte ? if ($charge) { if (isset($charge['source']) and $charge['source']['object'] == 'card') { // par defaut on note carte et BIN6 dans refcb $set['refcb'] = ''; if (isset($charge['source']['brand'])) { $set['refcb'] .= $charge['source']['brand']; } if (isset($charge['source']['last4']) and $charge['source']['last4']) { $set['refcb'] .= ' ****' . $charge['source']['last4']; } $set['refcb'] = trim($set['refcb']); // validite de carte ? if (isset($charge['source']['exp_month']) and $charge['source']['exp_year']) { $set['validite'] = $charge['source']['exp_year'] . "-" . str_pad($charge['source']['exp_month'], 2, '0', STR_PAD_LEFT); } } } $response = array_merge($response, $set); // il faudrait stocker le $charge aussi pour d'eventuels retour ? sql_updateq("spip_transactions", $set, "id_transaction=" . intval($id_transaction)); spip_log("call_response : id_transaction {$id_transaction}, reglee", $mode); $regler_transaction = charger_fonction('regler_transaction', 'bank'); $regler_transaction($id_transaction, array('row_prec' => $row)); return array($id_transaction, true); }
/** * Error message output */ function default_error_html($html, $charge) { $html = '<div class="sc-payment-details-wrap sc-payment-details-error">' . "\n"; $html .= '<p>' . __('Sorry, but there has been an error processing your payment.', 'stripe') . '</p>' . "\n"; // Display charge failure message if exists. if (!empty($charge)) { $charge = \Stripe\Charge::retrieve($charge); $html .= '<p>' . $charge->failure_message . '</p>' . "\n"; } // Display base error message if exists to site admin only. if (current_user_can('manage_options')) { $html .= '<h6>' . __('Admin note: Please visit the Logs area in your Stripe dashboard to view error details.', 'stripe') . '</h6>' . "\n"; } $html .= '</div>' . "\n"; return $html; }
public function testRetrieve() { authorizeFromEnv(); $c = Charge::create(array('amount' => 100, 'currency' => 'usd', 'card' => array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015))); $d = Charge::retrieve($c->id); $this->assertEqual($d->id, $c->id); }
/** * Payment refund * * @param \Magento\Payment\Model\InfoInterface $payment * @param float $amount * @return $this * @throws \Magento\Framework\Validator\Exception */ public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) { $transactionId = $payment->getParentTransactionId(); try { \Stripe\Charge::retrieve($transactionId)->refund(); } catch (\Exception $e) { $this->debugData(['transaction_id' => $transactionId, 'exception' => $e->getMessage()]); $this->_logger->error(__('Payment refunding error.')); throw new \Magento\Framework\Validator\Exception(__('Payment refunding error.')); } $payment->setTransactionId($transactionId . '-' . \Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND)->setParentTransactionId($transactionId)->setIsTransactionClosed(1)->setShouldCloseParentTransaction(1); return $this; }
/** * Function to show the payment details after the purchase * * @since 1.0.0 */ public static function show_payment_details($content) { if (in_the_loop() && is_main_query()) { global $sc_options; $html = ''; $test_mode = isset($_GET['test_mode']) ? 'true' : 'false'; $details_placement = isset($_GET['details_placement']) ? $_GET['details_placement'] : 'above'; $charge_response = null; // Since this is a GET query arg I reset it here in case someone tries to submit it again with their own string written in the URL. // This helps ensure it can only be set to below or above. $details_placement = $details_placement == 'below' ? 'below' : 'above'; $is_above = $details_placement == 'below' ? 0 : 1; Stripe_Checkout_Functions::set_key($test_mode); // Successful charge output. if (isset($_GET['charge']) && !isset($_GET['charge_failed'])) { $charge_id = esc_html($_GET['charge']); // https://stripe.com/docs/api/php#charges $charge_response = \Stripe\Charge::retrieve($charge_id); if (null === $sc_options->get_setting_value('disable_success_message')) { $html = '<div class="sc-payment-details-wrap">' . "\n"; $html .= '<p>' . __('Congratulations. Your payment went through!', 'stripe') . '</p>' . "\n"; $html .= '<p>' . "\n"; if (!empty($charge_response->description)) { $html .= __("Here's what you purchased:", 'stripe') . '<br/>' . "\n"; $html .= esc_html($charge_response->description) . '<br/>' . "\n"; } if (isset($_GET['store_name']) && !empty($_GET['store_name'])) { $html .= __('From: ', 'stripe') . esc_html($_GET['store_name']) . '<br/>' . "\n"; } $html .= '<br/>' . "\n"; $html .= '<strong>' . __('Total Paid: ', 'stripe') . Stripe_Checkout_Misc::to_formatted_amount($charge_response->amount, $charge_response->currency) . ' ' . strtoupper($charge_response->currency) . '</strong>' . "\n"; $html .= '</p>' . "\n"; $html .= '<p>' . sprintf(__('Your transaction ID is: %s', 'stripe'), $charge_response->id) . '</p>' . "\n"; $html .= '</div>' . "\n"; if ($is_above) { $content = apply_filters('sc_payment_details', $html, $charge_response) . $content; } else { $content = $content . apply_filters('sc_payment_details', $html, $charge_response); } } do_action('sc_after_charge', $charge_response); } elseif (isset($_GET['charge_failed'])) { $charge_id = esc_html($_GET['charge']); $charge = \Stripe\Charge::retrieve($charge_id); // LITE ONLY: Payment details error included in payment details function. $html = '<div class="sc-payment-details-wrap sc-payment-details-error">' . "\n"; $html .= '<p>' . __('Sorry, but there has been an error processing your payment.', 'stripe') . '</p>' . "\n"; $html .= '<p>' . $charge->failure_message . '</p>'; $html .= '</div>' . "\n"; if ($is_above) { $content = apply_filters('sc_payment_details_error', $html) . $content; } else { $content = $content . apply_filters('sc_payment_details_error', $html); } do_action('sc_after_charge', $charge_response); } } return $content; }
/** * request method * * @param string $method * @param array $data * * @return array - containing 'status', 'message' and 'data' keys * if response was successful, keys will be 'success', 'Success' and the stripe response as associated array respectively, * if request failed, keys will be 'error', the card error message if it was card_error, boolen false otherwise, and * error data as an array respectively */ private function request($method = null, $data = null) { if (!$method) { throw new Exception(__('Request method is missing')); } if (is_null($data)) { throw new Exception(__('Request Data is not provided')); } Stripe::setApiKey($this->key); $success = null; $error = null; $message = false; $log = null; try { switch ($method) { /** * * CHARGES * */ case 'charge': $success = $this->fetch(Charge::create($data)); break; case 'retrieveCharge': $success = $this->fetch(Charge::retrieve($data['charge_id'])); if (!empty($success['refunds'])) { foreach ($success['refunds'] as &$refund) { $refund = $this->fetch($refund); } } break; case 'updateCharge': $charge = Charge::retrieve($data['charge_id']); foreach ($data['fields'] as $field => $value) { $charge->{$field} = $value; } $success = $this->fetch($charge->save()); break; case 'refundCharge': $charge = Charge::retrieve($data['charge_id']); // to prevent unknown param error unset($data['charge_id']); $success = $this->fetch($charge->refund($data)); foreach ($success['refunds']['data'] as &$refund) { $refund = $this->fetch($refund); } break; case 'captureCharge': $charge = Charge::retrieve($data['charge_id']); unset($data['charge_id']); $success = $this->fetch($charge->capture($data)); if (!empty($success['refunds']['data'])) { foreach ($success['refunds']['data'] as &$refund) { $refund = $this->fetch($refund); } } break; case 'listCharges': $charges = Charge::all(); $success = $this->fetch($charges); foreach ($success['data'] as &$charge) { $charge = $this->fetch($charge); if (isset($charge['refunds']['data']) && !empty($charge['refunds']['data'])) { foreach ($charge['refunds']['data'] as &$refund) { $refund = $this->fetch($refund); } unset($refund); } } break; /** * CUSTOMERS */ /** * CUSTOMERS */ case 'createCustomer': $customer = Customer::create($data); $success = $this->fetch($customer); if (!empty($success['cards']['data'])) { foreach ($success['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($success['subscriptions']['data'])) { foreach ($success['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } break; case 'retrieveCustomer': $customer = Customer::retrieve($data['customer_id']); $success = $this->fetch($customer); if (!empty($success['cards']['data'])) { foreach ($success['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($success['subscriptions']['data'])) { foreach ($success['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } break; case 'updateCustomer': $cu = Customer::retrieve($data['customer_id']); foreach ($data['fields'] as $field => $value) { $cu->{$field} = $value; } $success = $this->fetch($cu->save()); if (!empty($success['cards']['data'])) { foreach ($success['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($success['subscriptions']['data'])) { foreach ($success['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } break; case 'deleteCustomer': $cu = Customer::retrieve($data['customer_id']); $success = $this->fetch($cu->delete()); break; case 'listCustomers': $customers = Customer::all($data['options']); $success = $this->fetch($customers); foreach ($success['data'] as &$customer) { $customer = $this->fetch($customer); if (!empty($customer['cards']['data'])) { foreach ($customer['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($customer['subscriptions']['data'])) { foreach ($customer['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } } break; /** * CARDS * */ /** * CARDS * */ case 'createCard': $cu = Customer::retrieve($data['customer_id']); $validCardFields = ['object', 'address_zip', 'address_city', 'address_state', 'address_country', 'address_line1', 'address_line2', 'number', 'exp_month', 'exp_year', 'cvc', 'name', 'metadata']; // unset not valid keys to prevent unknown parameter stripe error unset($data['customer_id']); foreach ($data['source'] as $k => $v) { if (!in_array($k, $validCardFields)) { unset($data['source'][$k]); } } $card = $cu->sources->create($data); $success = $this->fetch($card); break; case 'retrieveCard': $cu = Customer::retrieve($data['customer_id']); $card = $cu->sources->retrieve($data['card_id']); $success = $this->fetch($card); break; case 'updateCard': $cu = Customer::retrieve($data['customer_id']); $cuCard = $cu->sources->retrieve($data['card_id']); foreach ($data['fields'] as $field => $value) { $cuCard->{$field} = $value; } $card = $cuCard->save(); $success = $this->fetch($card); break; case 'deleteCard': $cu = Customer::retrieve($data['customer_id']); $card = $cu->sources->retrieve($data['card_id'])->delete(); $success = $this->fetch($card); break; case 'listCards': $cu = Customer::retrieve($data['customer_id']); $cards = $cu->sources->all($data['options']); $success = $this->fetch($cards); foreach ($success['data'] as &$card) { $card = $this->fetch($card); } break; /** * SUBSCRIPTIONS * */ /** * SUBSCRIPTIONS * */ case 'createSubscription': $cu = Customer::retrieve($data['customer_id']); // unset customer_id to prevent unknown parameter stripe error unset($data['customer_id']); $subscription = $cu->subscriptions->create($data['subscription']); $success = $this->fetch($subscription); break; case 'retrieveSubscription': $cu = Customer::retrieve($data['customer_id']); $subscription = $cu->subscriptions->retrieve($data['subscription_id']); $success = $this->fetch($subscription); break; case 'updateSubscription': $cu = Customer::retrieve($data['customer_id']); $cuSubscription = $cu->subscriptions->retrieve($data['subscription_id']); foreach ($data['fields'] as $field => $value) { $cuSubscription->{$field} = $value; } $subscription = $cuSubscription->save(); $success = $this->fetch($subscription); break; case 'cancelSubscription': $cu = Customer::retrieve($data['customer_id']); $subscription = $cu->subscriptions->retrieve($data['subscription_id'])->cancel($data['at_period_end']); $success = $this->fetch($subscription); break; case 'listSubscriptions': $cu = Customer::retrieve($data['customer_id']); $subscriptions = $cu->subscriptions->all($data['options']); $success = $this->fetch($subscriptions); foreach ($success['data'] as &$subscription) { $subscription = $this->fetch($subscription); } break; /** * PLANS * */ /** * PLANS * */ case 'createPlan': $plan = Plan::create($data); $success = $this->fetch($plan); break; case 'retrievePlan': $plan = Plan::retrieve($data['plan_id']); $success = $this->fetch($plan); break; case 'updatePlan': $p = Plan::retrieve($data['plan_id']); foreach ($data['fields'] as $field => $value) { $p->{$field} = $value; } $plan = $p->save(); $success = $this->fetch($plan); break; case 'deletePlan': $p = Plan::retrieve($data['plan_id']); $plan = $p->delete(); $success = $this->fetch($plan); break; case 'listPlans': $plans = Plan::all($data['options']); $success = $this->fetch($plans); foreach ($success['data'] as &$plan) { $plan = $this->fetch($plan); } break; /** * COUPONS * */ /** * COUPONS * */ case 'createCoupon': $coupon = Coupon::create($data); $success = $this->fetch($coupon); break; case 'retrieveCoupon': $coupon = Coupon::retrieve($data['coupon_id']); $success = $this->fetch($coupon); break; case 'deleteCoupon': $c = Coupon::retrieve($data['coupon_id']); $coupon = $c->delete(); $success = $this->fetch($coupon); break; case 'listCoupons': $coupons = Coupon::all($data['options']); $success = $this->fetch($coupons); foreach ($success['data'] as &$coupon) { $coupon = $this->fetch($coupon); } break; /** * * EVENTS * */ /** * * EVENTS * */ case 'retrieveEvent': $event = Event::retrieve($data['event_id']); $success = $this->fetch($event); // cards if (isset($success['data']['object']['cards']['data']) && !empty($success['data']['object']['cards']['data'])) { foreach ($success['data']['object']['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($refund); } break; case 'listEvents': $events = Event::all($data['options']); $success = $this->fetch($events); foreach ($success['data'] as &$event) { $event = $this->fetch($event); // refunds if (isset($event['data']['object']['refunds']) && !empty($event['data']['object']['refunds'])) { foreach ($event['data']['object']['refunds'] as &$refund) { $refund = $this->fetch($refund); } unset($refund); } // cards if (isset($event['data']['object']['cards']['data']) && !empty($event['data']['object']['cards']['data'])) { foreach ($event['data']['object']['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($refund); } } break; } } catch (Card $e) { $body = $e->getJsonBody(); $error = $body['error']; $error['http_status'] = $e->getHttpStatus(); $message = $error['message']; } catch (InvalidRequest $e) { $body = $e->getJsonBody(); $error = $body['error']; $error['http_status'] = $e->getHttpStatus(); } catch (Authentication $e) { $error = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } catch (ApiConnection $e) { $body = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } catch (Base $e) { $body = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } catch (\Exception $e) { $body = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } if ($success) { // if ($this->logFile && in_array($this->logType, ['both', 'success'])) { // CakeLog::write('Success', $method, $this->logFile); // } return ['status' => 'success', 'message' => 'Success', 'response' => $success]; } $str = ''; $str .= $method . ", type:" . (!empty($error['type']) ? $error['type'] : ''); $str .= ", type:" . (!empty($error['type']) ? $error['type'] : ''); $str .= ", http_status:" . (!empty($error['http_status']) ? $error['http_status'] : ''); $str .= ", param:" . (!empty($error['param']) ? $error['param'] : ''); $str .= ", message:" . (!empty($error['message']) ? $error['message'] : ''); // if ($this->logFile && in_array($this->logType, array('both', 'error'))) { // CakeLog::write('Error', $str, $this->logFile ); // } return ['status' => 'error', 'message' => $message, 'response' => $error]; }
/** * Retrieve stripe charge object * * @param string $id Charge StripeID * * @return \Stripe\Charge */ public function retrieve($id) { return StripeChargeApi::retrieve($id); }
public function capture($id) { Stripe::setApiKey(\Config::get('stripe.key')); try { $capture = StripeCharge::retrieve($id); $capture->capture(); } catch (StripeError\Base $e) { $errorBody = $e->getJsonBody(); echo 'Status is: ' . $e->getHttpStatus() . '<br>'; echo 'Param is: ' . $errorBody['error']['param'] . '<br>'; echo 'Message is: ' . $errorBody['error']['message'] . '<br>'; } }
/** * Gets the order id, total amount, refunded positions and an optional comment * from the request and uses them to create a new refund with Stripe. * If successful, the information abouth the refund are added to the internal coment * of ther order. Finally the new internal comment is added to the response. */ public function refundAction() { // Get order id, total amount, positions and comment from the request $orderId = $this->Request()->getParam('orderId'); if ($orderId === null) { // Missing orderId $this->View()->success = false; $this->View()->message = 'Required parameter "orderId" not found'; $this->Response()->setHttpResponseCode(400); return; } $amount = floatval($this->Request()->getParam('amount')); if ($amount <= 0.0) { // Invalid amount $this->View()->success = false; $this->View()->message = 'Required parameter "amount" must be greater zero'; $this->Response()->setHttpResponseCode(400); return; } $positions = $this->Request()->getParam('positions', array()); if (count($positions) === 0) { // Missing positions $this->View()->success = false; $this->View()->message = 'Required parameter "positions" not found or empty'; $this->Response()->setHttpResponseCode(400); return; } $comment = $this->Request()->getParam('comment'); // Try to get order /** @var Shopware\Models\Order\Order $order */ $order = $this->get('models')->getRepository('Shopware\\Models\\Order\\Order')->findOneById($orderId); if ($order === null) { // Order does not exist $this->View()->success = false; $this->View()->message = 'Order with id ' . $orderId . ' not found'; $this->Response()->setHttpResponseCode(404); return; } if ($order->getTransactionId() === null) { // Order wasn't payed with Stripe $this->View()->success = false; $this->View()->message = 'Order with id ' . $orderId . ' has no Stripe charge'; $this->Response()->setHttpResponseCode(404); return; } // Set the Stripe API key $apiKey = $this->plugin->Config()->get('stripeSecretKey'); \Stripe\Stripe::setApiKey($apiKey); // Load the charge and add new refund to it try { $charge = \Stripe\Charge::retrieve($order->getTransactionId()); $charge->refund(array('amount' => intval($amount * 100))); } catch (Exception $e) { // Try to get the error response if ($e->getJsonBody() !== null) { $body = $e->getJsonBody(); $message = $body['error']['message']; } else { $message = $e->getMessage(); } $this->View()->success = false; $this->View()->message = $message; $this->Response()->setHttpResponseCode(500); return; } // Add a new refund comment to the internal comment of the order $internalComment = $order->getInternalComment(); $internalComment .= "\n--------------------------------------------------------------\n" . 'Stripe Rückerstattung (' . date('d.m.Y, G:i:s') . ")\n" . 'Betrag: ' . number_format($amount, 2, ',', '.') . " €\n" . "Kommentar: {$comment}\n" . "Positionen:\n"; foreach ($positions as $position) { $price = number_format($position['price'], 2, ',', '.'); $totalPrice = number_format($position['total'], 2, ',', '.'); $internalComment .= ' - ' . $position['quantity'] . ' x ' . $position['articleNumber'] . ', je ' . $price . ' €, Gesamt: ' . $totalPrice . " €\n"; } $internalComment .= "--------------------------------------------------------------\n"; $order->setInternalComment($internalComment); $this->get('models')->flush($order); // Respond with the new internal comment $this->View()->success = true; $this->View()->internalComment = $internalComment; }
public function verify() { if (!$this->initStripe()) { return false; } $chargeId = $this->order->getLog('Stripe Charge ID'); if (empty($chargeId)) { return false; } try { $charge = \Stripe\Charge::retrieve($chargeId); } catch (\Exception $e) { $this->order->addLog('Stripe Verify Fail', $e->getMessage()); return false; } if ($charge && $charge['status'] === 'succeeded') { return true; } return false; }
public function refundCharge($id) { $charge = Charge::retrieve($id); try { return $charge->refund(); } catch (\Stripe\Error\InvalidRequest $e) { throw new \Exception($e->getMessage()); // throw new \Exception('You cannot make the same transaction twice.'); } catch (\Stripe\Error\Base $e) { throw new \Exception($e->getMessage()); } catch (\Exception $e) { return $e->getMessage(); } }
function captureCharge() { $this->setApiKey(); $charge = \Stripe\Charge::retrieve("ch_17QtQXFCflfB1pEyEMJ3vb4B"); $captured = $charge->capture(); return $captured; }
/** * Capture the Stripe charge which was authorized during validation. * * @param array $auth Contains the result of the authorize() function. * @param array $feed The feed object currently being processed. * @param array $submission_data The customer and transaction data. * @param array $form The form object currently being processed. * @param array $entry The entry object currently being processed. * * @return array */ public function capture($auth, $feed, $submission_data, $form, $entry) { // Get Stripe charge from authorization. $charge = \Stripe\Charge::retrieve($auth['transaction_id']); try { // Set charge description and metadata. $charge->description = $this->get_payment_description($entry, $submission_data, $feed); $metadata = $this->get_stripe_meta_data($feed, $entry, $form); if (!empty($metadata)) { $charge->metadata = $metadata; } // Save charge. $charge->save(); /** * Allow authorization only transactions by preventing the capture request from being made after the entry has been saved. * * @param bool $authorization_only Defaults to false, return true to prevent payment being captured. * @param array $feed The feed object currently being processed. * @param array $submission_data The customer and transaction data. * @param array $form The form object currently being processed. * @param array $entry The entry object currently being processed. * * @since 2.1.0 */ $authorization_only = apply_filters('gform_stripe_charge_authorization_only', false, $feed, $submission_data, $form, $entry); if ($authorization_only) { $this->log_debug(__METHOD__ . '(): The gform_stripe_charge_authorization_only filter was used to prevent capture.'); return array(); } // Capture the charge. $charge = $charge->capture(); // Prepare payment details. $payment = array('is_success' => true, 'transaction_id' => $charge->id, 'amount' => $this->get_amount_import($charge->amount, $entry['currency']), 'payment_method' => rgpost('stripe_credit_card_type')); } catch (\Exception $e) { // Log that charge could not be captured. $this->log_error(__METHOD__ . '(): Unable to capture charge; ' . $e->getMessage()); // Prepare payment details. $payment = array('is_success' => false, 'error_message' => $e->getMessage()); } return $payment; }
public function submitOrder($short_name) { $university = $this->university->where('short_name', $short_name)->first(); $firstName = $this->request->input('first_name', ''); $lastName = $this->request->input('last_name', ''); $emainAddress = $this->request->input('email_address', ''); $customer = $this->customer->where('first_name', $firstName)->where('last_name', $lastName)->where('email_address', $emainAddress)->first(); $customerId; if ($customer === null) { //This customer is new $this->customer->fill($this->request->all())->save(); $customerId = $this->customer->id; } else { $this->customer->find($customer->id)->fill($this->request->all())->save(); $customerId = $customer->id; } $totalPrice = $this->request->input('totalPrice', ''); $orderId = $this->order->insertGetId(['customer_id' => $customerId, 'payment' => $this->request->input('payment', ''), 'order_status' => "initialized", 'street_address1' => $this->request->input('street_address1', ''), 'street_address2' => $this->request->input('street_address2', ''), 'city' => $this->request->input('city', ''), 'post_code' => $this->request->input('post_code', ''), 'country' => $this->request->input('country', ''), 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'total_price' => $totalPrice]); $itemsInCart = $this->cart->where('customer_id', $this->request->cookie('customer_id'))->get(); foreach ($itemsInCart as $item) { $this->orderitem->insert(['order_id' => $orderId, 'product_id' => $item->product_id, 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'price' => $item->price]); $cart = $this->cart->find($item->id); $cart->order_id = $orderId; $cart->save(); } $temporaryCustomerId = $this->request->cookie('customer_id'); $allProductsInCart = $this->getAllProductsInCart($temporaryCustomerId); $allProductsInCart = $this->convertProductsForCheckout($allProductsInCart); \Stripe\Stripe::setApiKey("sk_test_I561ILtdEXsIVDoAc9169tcC"); $transactionInformation = \Stripe\Charge::all(); $transactionId = $transactionInformation->data[0]->id; $token = $this->request->input('stripeToken', ''); $tokenInformation = \Stripe\Token::retrieve($token); $chargeInformation = \Stripe\Charge::retrieve($transactionId); //dd($transactionInformation); try { $charge = \Stripe\Charge::create(array("amount" => bcmul($totalPrice, 100), "currency" => "aud", "source" => $token, "description" => "Example charge")); $type = $tokenInformation->type; $clientIp = $tokenInformation->client_ip; $createdTime = $chargeInformation->created; $country = $chargeInformation->source->country; $expMonth = $chargeInformation->source->exp_month; $expYear = $chargeInformation->source->exp_year; $brand = $chargeInformation->source->brand; $last4CardNumber = $chargeInformation->source->last4; $paymentResponse = json_encode(array('type' => $type, 'client_ip' => $clientIp, 'created' => $createdTime, 'country' => $country, 'expMonth' => $expMonth, 'expYear' => $expYear, 'brand' => $brand, 'last4CardNumber' => $last4CardNumber)); $transactionId = \Stripe\Charge::all()->data[0]->id; $order = $this->order->find($orderId); $order->transaction_id = $transactionId; $order->order_status = "paid"; $order->payment_response = $paymentResponse; $order->save(); $shippingFee = $this->request->input('shipping_fee', ''); $this->sendConfirmationMail($customerId, $allProductsInCart, $totalPrice, $shippingFee); foreach ($allProductsInCart as $productInCart) { $product = $this->product->find($productInCart['id']); $product->stock -= $productInCart['quantity']; $product->save(); if ($product->stock < 0) { $this->sendStockShortageNotification($product, $orderId); $order->order_status = "out_of_stock"; $order->save(); } } foreach ($itemsInCart as $item) { $this->cart->destroy($item->id); } return view('www.orderSubmitted', ['template' => $university->template, 'basket' => $this->getTheNumberOfItems(), 'products' => $allProductsInCart, 'totalPrice' => $totalPrice, 'shippingFee' => $shippingFee, 'headerLinks' => $this->headerPages, 'footerLinks' => $this->footerPages]); } catch (\Stripe\Error\Card $e) { $type = $tokenInformation->type; $clientIp = $tokenInformation->client_ip; $createdTime = $chargeInformation->created; $country = $chargeInformation->source->country; $expMonth = $chargeInformation->source->exp_month; $expYear = $chargeInformation->source->exp_year; $brand = $chargeInformation->source->brand; $last4CardNumber = $chargeInformation->source->last4; $failureCode = $chargeInformation->failure_code; $failureMessage = $chargeInformation->failure_message; $paymentResponse = json_encode(array('type' => $type, 'client_ip' => $clientIp, 'created' => $createdTime, 'country' => $country, 'expMonth' => $expMonth, 'expYear' => $expYear, 'brand' => $brand, 'last4CardNumber' => $last4CardNumber, 'failureCode' => $failureCode, 'failureMessage' => $failureMessage)); $order = $this->order->find($orderId); $order->order_status = "failed"; $order->payment_response = $paymentResponse; $order->save(); include 'countries.php'; $isShipping = false; foreach ($allProductsInCart as $productInCart) { if ($productInCart['is_shipping'] === "Yes" && $isShipping === false) { $isShipping = true; } } $domesticShippingFee = $this->setting->where('key', 'domesticShippingFee')->first(); $domesticShippingFee = json_decode($domesticShippingFee->json)->data; $overseasShippingFee = $this->setting->where('key', 'overseasShippingFee')->first(); $overseasShippingFee = json_decode($overseasShippingFee->json)->data; $message = "Unfortunately, the submission has been failed :" . $failureCode; return view('www.checkout', ['template' => $university->template, 'universityShortName' => $short_name, 'basket' => $this->getTheNumberOfItems(), 'products' => $allProductsInCart, 'totalPrice' => $totalPrice, 'countries' => $countries, 'is_shipping' => $isShipping, 'domesticShippingFee' => $domesticShippingFee, 'overseasShippingFee' => $overseasShippingFee, 'message' => $message, 'headerLinks' => $this->headerPages, 'footerLinks' => $this->footerPages]); } }
public function process_refund($order_id, $amount = NULL, $reason = '') { if ($amount > 0) { $CHARGE_ID = get_post_meta($order_id, '_transaction_id', true); $charge = \Stripe\Charge::retrieve($CHARGE_ID); $refund = $charge->refunds->create(array('amount' => $amount * 100, 'metadata' => array('Order #' => $order_id, 'Refund reason' => $reason))); if ($refund) { $repoch = $refund->created; $rdt = new DateTime("@{$repoch}"); $rtimestamp = $rdt->format('Y-m-d H:i:s e'); $refundid = $refund->id; $wc_order = new WC_Order($order_id); $wc_order->add_order_note(__('Stripe Refund completed at. ' . $rtimestamp . ' with Refund ID = ' . $refundid, 'woocommerce')); return true; } else { return false; } } else { return false; } }
/** * Retrieve the charge * * @param $transaction_id * * @return Charge * @since 1.0.0 */ public function get_charge($transaction_id) { return Charge::retrieve($transaction_id); }
<?php require_once dirname(__FILE__) . '/init.php'; require_once dirname(__FILE__) . '/config.php'; $arr = array(); //headers array_push($arr, array('balance_id', 'charge_id', 'type', 'amount', 'net', 'fee', 'created', 'available_on', 'status', 'description', 'product_id', 'product_type', 'order_id', 'customer_name', 'customer_email')); $out = fopen('balance_history_expanded.csv', 'w'); $increment = 100; $continue = true; $ending_before = 'txn_16U0xRGYjKzzi3FkTJGKL2Vo'; while ($continue) { $transactionsJSON = \Stripe\BalanceTransaction::all(array("limit" => $increment, "ending_before" => $ending_before)); $transactions = $transactionsJSON->__toArray(true); $continue = $transactions['has_more']; $ending_before = current($transactions['data'])['id']; foreach ($transactions['data'] as $transaction) { if ($transaction['type'] != 'transfer') { $charge = NULL; $chargeJSON = \Stripe\Charge::retrieve($transaction['source']); $charge = $chargeJSON->__toArray(true); array_push($arr, array($transaction['id'], $transaction['source'], $transaction['type'], $transaction['amount'] / 100, $transaction['net'] / 100, $transaction['fee'] / 100, gmdate("Y-m-d H:i:s", $transaction['created']), gmdate("Y-m-d H:i:s", $transaction['available_on']), $transaction['status'], $transaction['description'], $charge['metadata']['product_id'], $charge['metadata']['product_type'], $charge['metadata']['order_id'], $charge['metadata']['customer_name'], $charge['metadata']['customer_email'])); } } } foreach ($arr as $rows) { fputcsv($out, $rows); } fclose($out);
/** * [getCharge Retrieves the details of a charge that has previously been created. Supply the unique charge * ID that was returned from your previous request, and Stripe will return the corresponding * charge information. The same information is returned when creating or refunding the charge.] * * @param $charge_id [ID stripe of charge] * @return [stripe charge object] */ public function getCharge($charge_id) { return \Stripe\Charge::retrieve($charge_id); }
function default_error_html($html, $charge) { $html = '<div class="sc-payment-details-wrap sc-payment-details-error">' . "\n"; $html .= '<p>' . __('Sorry, but there has been an error processing your payment.', 'sc') . '</p>' . "\n"; if (!empty($charge)) { $charge = \Stripe\Charge::retrieve($charge); $html .= '<p>' . $charge->failure_message . '</p>'; } $html .= '</div>' . "\n"; return $html; }
public function validatePayment($response, $amount, User $user) { if (!$response->paid || $response->refunded) { throw new \Exception('Stripe: card is not paid'); } $updatedCharge = Charge::retrieve($response->id); if ($updatedCharge->metadata['user'] != $user->id) { throw new \Exception('Stripe: user id mismatch'); } if ($response->amount != $amount) { throw new \Exception('Stripe: wrong amount'); } if (strtoupper($response->currency) != $this->currency) { throw new \Exception('Stripe: wrong currency'); } return true; }