On this page payment.php, I would like to create a customer for payment on stripe, but I have nothing in my page, nothing in the console, there is written NULL, I don't know how to make it work.
<?php
$token = $_POST['token'];
$name = $_POST['nom'];
require_once('assets/vendor/stripe/init.php');
// (switch to the live key later)
\Stripe\Stripe::setApiKey("sk_test_p5p8Apo5Mn2LIn1po1tg5tYe33df6vQf");
try
{
$customer = \Stripe\Customer::create([
"name" => $name,
"source" => $token,
]);
$reponse= json_decode($customer);
var_dump($reponse);
}
catch(Exception $e)
{
error_log("unable to sign up customer:" . $_POST['stripeEmail'].
", error:" . $e->getMessage());
}
Related
Recently i got duplicated payments with Stripe.
They told me to use Idempotent Requests.
I made some tests and i see the error message if i tried to refresh the browser for example.
But i don't know how to make the "next step" in case of error.
I mean if my client make a payment and there is a network issue, how to do with Stripe to retry and continu the process or how to display an error message and came back to the payment's page ?
My code for now:
\Stripe\Stripe::setApiKey("xxxxxx");
$charge = \Stripe\Charge::create([
'customer' => $customer->id,
'amount' => $total_payment,
'currency' => $currency,
'description' => $description
], ["idempotency_key" => $idempotency,]);
$chargeJson = $charge->jsonSerialize();
$status = $chargeJson['status'];
if($status=="succeeded") {...
Thank you for your help, if you can just give me some information and then it will help me to improve my code ^^
Here is a functional demo of the try/catch with all the possible errors adding "Idempotent Requests field", just add your own functionality in each catch:
try {
// Use Stripe's library to make requests...
$charge = \Stripe\Charge::create([
'amount' => $amount,
'currency' => "usd",
'description' => $description,
"receipt_email" => $mail,
], [
'idempotency_key' => $uniqueID
]);
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
I am working on an app that does ETH/BTC arbitrage trading of crypto-currency using ccxt crypto API for PHP, and i keep receiving this Network Error exception thrown from the API call usually while trying to place a limit buy order.
{"status":-124,"error_message":"Enter the size in units of 0.0000001 ETH.","data":null}
This above exception is thrown from Bitflyer exchange.
My code is as follows:
$name = '\\ccxt\\'.$exchangeId;
$exchange = new $name(array (
'apiKey' => $api_key, // ←------------ replace with your keys
'secret' => $secret_key,
'enableRateLimit' => true,
));
try{
$symbol = 'ETH/BTC';
$type = 'limit'; // # or 'market', or 'Stop' or 'StopLimit'
$side = 'buy'; // 'sell' or 'buy'
$amount = $data['trade_base_amount']; //0.0515996
$price = $data['exchange_rate']; // 0.01938
// extra params and overrides
$params = array();
$response = $exchange->create_order($symbol, $type, $side, $amount, $price, $params);
print_r($response);
}catch (\ccxt\NetworkError $e) {
echo $exchange->id . ' fetch_trades failed due to a network error: '.$e->getMessage () . "\n";
}catch (\ccxt\ExchangeError $e) {
echo $exchange->id . ' fetch_trades failed due to exchange error: ' .$e->getMessage () . "\n";
}catch (\Exception $e) {
echo $exchange->id . ' fetch_trades failed with: ' . $e->getMessage () . "\n";
}
Can anyone please explain why am I getting this error?
Thanks in advance.
Try using amountToPrecision for me worked
get the documentation on CCXT
Everything is working fine in Stripe - the token is generated, written in the "log" part in my dashboard, etc. However there is no charge done. I got no error from Stripe or my code even if I did all the error handling given by the stripe documentation. How can I correct this?
require_once ("vendor/autoload.php");
if ($_POST) {
echo "catch if";
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
StripeStripe::setApiKey("myApyKey");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create a charge: this will charge the user's card
try {
echo "charging";
$charge = StripeCharge::create(array(
"amount" => 1000, // Amount in cents
"currency" => "eur",
"source" => $token,
"description" => "Example charge"
));
}
catch(StripeErrorCard $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print ('Status is:' . $e->getHttpStatus() . "\n");
print ('Type is:' . $err['type'] . "\n");
print ('Code is:' . $err['code'] . "\n");
// param is '' in this case
print ('Param is:' . $err['param'] . "\n");
print ('Message is:' . $err['message'] . "\n");
}
catch(StripeErrorRateLimit $e) {
// Too many requests made to the API too quickly
}
catch(StripeErrorInvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
}
catch(StripeErrorAuthentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
}
catch(StripeErrorApiConnection $e) {
// Network communication with Stripe failed
}
catch(StripeErrorBase $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
}
catch(Exception $e) {
// Something else happened, completely unrelated to Stripe
}
You are probably getting an error, and your code is handling that error correctly, but you error handling code doesn't actually do anything for many of the cases.
You should probably add something (such as a print call) in each catch block to see exactly what type of issue is being returned.
Alternatively, your Stripe Dashboard has a way to view your accounts Live Mode and Test Mode logs at https://dashboard.stripe.com/logs which will contain an entry for every request (successful or otherwise) that hit Stripe's servers.
Try to use below code find error issue
try {
echo "charging";
$charge = StripeCharge::create(array(
"amount" => 1000, // Amount in cents
"currency" => "eur",
"source" => $token,
"description" => "Example charge"
));
}
catch(StripeErrorCard $e) {
$error = $e->getJsonBody();
<pre>print_r($error);</pre>
//then you can handle like that
if($error == "Your card was declined."){
echo "Your credit card was declined. Please try again with an alternate card.";
}
}
When trying to create an event on YouTube using YouTube Data API I get following error only in case of very few users:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/youtube/v3/liveBroadcasts?part=snippet%2Cstatus: (403) The user is not enabled for live streaming.' in E:\Rupesh\Websites\abtv\abstream\Google\Http\REST.php on line 110
Please also note following :
The user id is of the form xyz#gmail.com only. I know for fact, this code does not work for user id of the form xyz##pages.plusgoogle.com.
User is authenticated using Google's OAuth 2 prior to calling this function.
User has allowed access to Web Application using #gmail.com id.
Following is class I have put together:
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/aprilbr3/public_html/google-api-php-client/src');
require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/Oauth2.php';
require_once 'class.miscellaneous_functions.php';
class GoogleClient
{
public static $cdn_formats = array(
"Poor" => "240p", "Ok" => "360p", "Good" => "480p", "Better" => "720p", "Best" => "1080p");
public static $privacy_statuses = array(
"public" => "public", "unlisted" => "unlisted", "private" => "private");
private static $OAUTH2_CLIENT_ID = 'CLIENT_ID_HERE';
private static $OAUTH2_CLIENT_SECRET = 'CLIENT_SECRET_HERE';
private static $privacy_status = "public"; // $privacy_statuses["public"];
//private static $cdn_format = $cdn_formats["Ok"];
private static $cdn_injestion_type = "rtmp";
var $client;
var $plus;
var $redirect_url;
var $user_info;
function __construct()
{
$this->client = new Google_Client();
$this->client->setClientId(GoogleClient::$OAUTH2_CLIENT_ID);
$this->client->setClientSecret(GoogleClient::$OAUTH2_CLIENT_SECRET);
$redirect_url = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$this->client->setRedirectUri($redirect_url);
$this->client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/youtube'));
$this->plus = new Google_Service_Oauth2($this->client);
} // __construct()
function OAuth2()
{
if (!isset($_SESSION))
session_start();
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
try {
$this->client->authenticate($_GET['code']);
} catch (Google_Auth_Exception $e) {
MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
}
$_SESSION['access_token'] = $this->client->getAccessToken();
header('Location:' . $this->redirect_url);
}
if (isset($_SESSION['access_token'])) {
$this->client->setAccessToken($_SESSION['access_token']);
}
$error = false;
if (!$this->client->getAccessToken()) {
$error = true;
}
if (!$error) {
try {
$user_info = $this->plus->userinfo->get();
return array('result' => true, 'user_info' => $user_info);
} catch (Google_Service_Exception $e) {
MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
//exit();
} catch (Google_Exception $e) {
MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
//exit();
}
}
return array('result' => false, 'auth_url' => $this->client->createAuthUrl());
//MiscellaneousFunctions::DestroySessionAndRedirectTo($this->client->createAuthUrl());
//exit();
} // OAuth2
function CreateEvent($broadcast_title, $broadcast_description, $cdn_format,
$start_date_time, $end_date_time)
{
//echo( "Step 1" . "\n<br><br><br>");
$stream_title = "Stream for " . $broadcast_title;
$youtube = new Google_Service_YouTube($this->client);
try {
// Create an object for the liveBroadcast resource's snippet. Specify values
// for the snippet's title, scheduled start time, and scheduled end time.
$broadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$broadcastSnippet->setTitle($broadcast_title);
//echo( "Step 2" . "\n<br><br><br>");
//echo( "Start Time : " . MiscellaneousFunctions::GetDateTimeStringForYoutube($start_date_time) . "\n</br>");
//echo( "End Time : " . MiscellaneousFunctions::GetDateTimeStringForYoutube($end_date_time) . "\n</br>");
//exit;
$broadcastSnippet->setScheduledStartTime(
MiscellaneousFunctions::GetDateTimeStringForYoutube($start_date_time));
$broadcastSnippet->setScheduledEndTime(
MiscellaneousFunctions::GetDateTimeStringForYoutube($end_date_time));
$broadcastSnippet->setDescription($broadcast_description);
//echo( "Step 3" . "\n<br><br><br>");
// Create an object for the liveBroadcast resource's status, and set the
// broadcast's status to "private".
$status = new Google_Service_YouTube_LiveBroadcastStatus();
$status->setPrivacyStatus(GoogleClient::$privacy_status);
//echo( "Step 4" . "\n<br><br><br>");
// Create the API request that inserts the liveBroadcast resource.
$broadcastInsert = new Google_Service_YouTube_LiveBroadcast();
$broadcastInsert->setSnippet($broadcastSnippet);
$broadcastInsert->setStatus($status);
$broadcastInsert->setKind('youtube#liveBroadcast');
//echo( "Step 5" . "\n<br><br><br>");
//echo( json_encode( $youtube ) . "\n<br><br><br>");
// Execute the request and return an object that contains information
// about the new broadcast.
$broadcastsResponse = $youtube->liveBroadcasts->insert('snippet,status',
$broadcastInsert, array());
//echo( "Step 6" . "\n<br><br><br>");
// Create an object for the liveStream resource's snippet. Specify a value
// for the snippet's title.
$streamSnippet = new Google_Service_YouTube_LiveStreamSnippet();
$streamSnippet->setTitle($stream_title);
// echo( "Step 7" . "\n<br><br><br>");
// Create an object for content distribution network details for the live
// stream and specify the stream's format and ingestion type.
$cdn = new Google_Service_YouTube_CdnSettings();
$cdn->setFormat($cdn_format);
$cdn->setIngestionType(GoogleClient::$cdn_injestion_type);
// echo( "Step 8" . "\n<br><br><br>");
// Create the API request that inserts the liveStream resource.
$streamInsert = new Google_Service_YouTube_LiveStream();
$streamInsert->setSnippet($streamSnippet);
$streamInsert->setCdn($cdn);
$streamInsert->setKind('youtube#liveStream');
// echo( "Step 9" . "\n<br><br><br>");
// Execute the request and return an object that contains information
// about the new stream.
$streamsResponse = $youtube->liveStreams->insert('snippet,cdn', $streamInsert, array());
// Bind the broadcast to the live stream.
$bindBroadcastResponse = $youtube->liveBroadcasts->bind(
$broadcastsResponse['id'], 'id,contentDetails',
array('streamId' => $streamsResponse['id'],));
// echo( "Step 10" . "\n<br><br><br>");
return array('result' => true,
'broadcasts_response' => $broadcastsResponse,
//'broadcasts_response_id' => $broadcastsResponse['id'],
//'broadcasts_response_snippet' => $broadcastsResponse['snippet'],
'streams_response' => $streamsResponse
//'streams_response_id' => $streamsResponse['id'],
//'streams_response_snippet' => $streamsResponse['snippet'],
//'streams_response_cdn' => $streamsResponse['cdn'],
//'streams_response_cdn_ingestionInfo' => $streamsResponse['cdn']['ingestionInfo']
);
} catch (Google_Service_Exception $e) {
//MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
//echo( "Google_Service_Exception:" . json_encode( $e ) . "\n<br><br><br>");
// return array('result' => false, 'reason' => $reason);
} catch (Google_Exception $e) {
//MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
//echo( "Google_Exception:" . json_encode( $e ) . "\n<br><br><br>");
//return array('result' => false, 'reason' => $reason);
}
return array('result' => false, 'reason' => $reason);
}
function GetEvent( $broadcast_id )
{
$youtube = new Google_Service_YouTube($this->client);
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet,contentDetails,status',
array( 'id' => $broadcast_id ));
$broadcastItem = $broadcastsResponse['items'][0];
$streamId = $broadcastItem['contentDetails']['boundStreamId'];
$streamsResponse = $youtube->liveStreams->listLiveStreams(
'id,snippet,cdn,status',
array( 'id' => $streamId ));
$streamItem = $streamsResponse['items'][0];
return array('result' => true,
'broadcasts_response' => $broadcastItem,
'streams_response' => $streamItem
);
} catch (Google_Service_Exception $e) {
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
} catch (Google_Exception $e) {
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
}
return array('result' => false, 'reason' => $reason);
}
} // class GoogleClient
Thank you.
Rupesh
P.S: Sorry, I forgot to mention that all the users of the system have enabled live streaming in their respective youtube accounts. That's what puzzles me!
I am currently developing the " payment " of my site and I use Symfony2 and Stripe . When I make a payment with a "valid" map all goes well but when I test a payment error I get an error 500. I would like to access the response of the payment order to decide on the continuation of the process but I don ' unable to do so. Symfony blocking me with his error 500 and despite all feasible var_dump I can not debug the application ...
Could anyone help me ? Thank you in advance !
Here is my code :
/**
* #Route("/confirm/{offerId}", name="order_confirm")
* #Template()
*/
public function chargeAction(Request $request, $offerId)
{
$em = $this->getDoctrine()->getManager();
$offer = $em->getRepository("CoreBundle:Offer")->findOneById($offerId);
$stripe = array(
'secret_key' => '**********',
'publishable_key' => '*****'
);
$apiKey = new Stripe();
$apiKey->setApiKey($stripe['secret_key']);
$order = new MemberOrder();
$form = $this->createForm(new MemberOrderType(),$order);
$order->setDate(new \DateTime("now"));
$order->setState("created");
if ($request->getMethod() == 'POST') {
$form->getData();
$order->setAmount($offer->getPriceDisplayed());
$token = $_POST['stripeToken'];
$customer = \Stripe\Customer::create(array(
'email' => $this->getUser()->getEmail(),
'source' => $token
));
try {
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'currency' => 'eur',
'amount' => $offer->getPrice()
));
var_dump($charge);die();
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
return $this->render('OrderBundle:Order:charge.html.twig', array(
'title_controller' => "contact",
'title_action' => "Validez votre paiement",
'form' => $form->createView(),
'offer' => $offer
));
}
The answer on Symfony's page project :
Symfony
Erreur 500
Your card was declined.
Retour à l'accueil