Jump to content

Stripe.com PHP Integration Help


aarontbarksdale

Recommended Posts

Is there anyone who might be able to assist me in creating a form that will collect all the necessary information that I require for my user set-up then input that information into my database. For more info: https://stripe.com/

Link to comment
Share on other sites

Take it a step at a time. There are examples of creating form elements here for your page: http://www.w3schools.com/html/html_forms.asp Once you have a form set up, then you can move on to processing the form with PHP and adding the data to your database. Are you trying to use the stripe.com API to deal with payments?

Link to comment
Share on other sites

Yes. I downloaded all of the libraries and can get it setup. I have a form but what I don't have is the understanding on how to take that information insert it into MY database. That's what I can't understand how to adjust that.

Link to comment
Share on other sites

there are plenty of tutorials on this site about how to get forms and databases to interact with each other.http://www.w3schools.com/php/default.asp Asd JSG suggested, take it one step at a time1) create a form2) write script that form can submit to, and make sure it can echo out the values correctly3) create your database and table to store the form data you want to submit4) wire up the form submissions script (step 2) to connect to the database and INSERT the data into it5) as POC, you could create another script that reads from the DB and outputs the data to you, so you can view whats in your table

Link to comment
Share on other sites

I have created a form, I have no issues with the FORM or entering that information into the database. I have also been able to successfully get the payment process to work. However, the problem I'm having is getting the form to pass through the payment so that (A) the same information that I store in my db can be in the stripe customer information and (B.) it continues to throw an error with regards to the subscription API.

Fatal error: Uncaught exception 'Stripe_InvalidRequestError' with message 'Plan already exists.' in ../login/stripe/lib/Stripe/ApiRequestor.php:86 Stack trace: #0 ../login/stripe/lib/Stripe/ApiRequestor.php(136): Stripe_ApiRequestor->handleApiError('{? "error": {?...', 400, Array) #1 ../login/stripe/lib/Stripe/ApiRequestor.php(74): Stripe_ApiRequestor->_interpretResponse('{? "error": {?...', 400) #2 ../login/stripe/lib/Stripe/ApiResource.php(76): Stripe_ApiRequestor->request('post', '/v1/plans', Array) #3 ../login/stripe/lib/Stripe/Plan.php(20): Stripe_ApiResource::_scopedCreate('Stripe_Plan', Array, NULL) #4 ../login/stripe/config.php(17): Stripe_Plan::create(Array) #5 ../insert_user.php(141): require_once('/home/content/w...') #6 {main} in ../login/stripe/lib/Stripe/ApiRequestor.phpon line 86
I have the subscription setup, I do NOT have a script that creates a new subscription in the API. Edited by aarontbarksdale
Link to comment
Share on other sites

Its hard to tell without seeing the code you're tying to implement the API calls with. It would help to narrow down which parts of the documentation we would need to review in order to best help you. A specific API method call should have supporting documentation,https://stripe.com/docs which could help narrow down parameters required, common errors/issues, and possible steps omitted.

Edited by thescientist
Link to comment
Share on other sites

JSG: Here's the code for the APIRequestor.php

<?php class Stripe_ApiRequestor{  public $apiKey;   public function __construct($apiKey=null)  {	$this->_apiKey = $apiKey;  }   public static function apiUrl($url='')  {	$apiBase = Stripe::$apiBase;	return "$apiBase$url";  }   public static function utf8($value)  {	if (is_string($value) && mb_detect_encoding($value, "UTF-8", TRUE) != "UTF-8")	  return utf8_encode($value);	else	  return $value;  }   private static function _encodeObjects($d)  {	if ($d instanceof Stripe_ApiResource) {	  return self::utf8($d->id);	} else if ($d === true) {	  return 'true';	} else if ($d === false) {	  return 'false';	} else if (is_array($d)) {	  $res = array();	  foreach ($d as $k => $v)	   $res[$k] = self::_encodeObjects($v);	  return $res;	} else {	  return self::utf8($d);	}  }   public static function encode($arr, $prefix=null)  {	if (!is_array($arr))	  return $arr; 	$r = array();	foreach ($arr as $k => $v) {	  if (is_null($v))		continue; 	  if ($prefix && $k && !is_int($k))		$k = $prefix."[".$k."]";	  else if ($prefix)		$k = $prefix."[]"; 	  if (is_array($v)) {		$r[] = self::encode($v, $k, true);	  } else {		$r[] = urlencode($k)."=".urlencode($v);	  }	} 	return implode("&", $r);  }   public function request($meth, $url, $params=null)  {	if (!$params)	  $params = array();	list($rbody, $rcode, $myApiKey) = $this->_requestRaw($meth, $url, $params);	$resp = $this->_interpretResponse($rbody, $rcode);	return array($resp, $myApiKey);  }   public function handleApiError($rbody, $rcode, $resp)  {	if (!is_array($resp) || !isset($resp['error']))	  throw new Stripe_ApiError("Invalid response object from API: $rbody (HTTP response code was $rcode)", $rcode, $rbody, $resp);	$error = $resp['error'];	switch ($rcode) {	case 400:	case 404://LINE 86	  throw new Stripe_InvalidRequestError(isset($error['message']) ? $error['message'] : null,										   isset($error['param']) ? $error['param'] : null,										   $rcode, $rbody, $resp);	case 401:	  throw new Stripe_AuthenticationError(isset($error['message']) ? $error['message'] : null, $rcode, $rbody, $resp);	case 402:	  throw new Stripe_CardError(isset($error['message']) ? $error['message'] : null,								 isset($error['param']) ? $error['param'] : null,								 isset($error['code']) ? $error['code'] : null,								 $rcode, $rbody, $resp);	default:	  throw new Stripe_ApiError(isset($error['message']) ? $error['message'] : null, $rcode, $rbody, $resp);	}  }   private function _requestRaw($meth, $url, $params)  {	$myApiKey = $this->_apiKey;	if (!$myApiKey)	  $myApiKey = Stripe::$apiKey;	if (!$myApiKey)	  throw new Stripe_AuthenticationError('No API key provided.  (HINT: set your API key using "Stripe::setApiKey(<API-KEY>)".  You can generate API keys from the Stripe web interface.  See [url="https://stripe.com/api"]https://stripe.com/api[/url] for details, or email support@stripe.com if you have any questions.'); 	$absUrl = $this->apiUrl($url);	$params = self::_encodeObjects($params);	$langVersion = phpversion();	$uname = php_uname();	$ua = array('bindings_version' => Stripe::VERSION,'lang' => 'php','lang_version' => $langVersion,'publisher' => 'stripe','uname' => $uname);	$headers = array('X-Stripe-Client-User-Agent: ' . json_encode($ua),	'User-Agent: Stripe/v1 PhpBindings/' . Stripe::VERSION,					 'Authorization: Bearer ' . $myApiKey);	if (Stripe::$apiVersion)	  $headers[] = 'Stripe-Version: ' . Stripe::$apiVersion;	list($rbody, $rcode) = $this->_curlRequest($meth, $absUrl, $headers, $params);	return array($rbody, $rcode, $myApiKey);  }   private function _interpretResponse($rbody, $rcode)  {	try {	  $resp = json_decode($rbody, true);	} catch (Exception $e) {	  throw new Stripe_ApiError("Invalid response body from API: $rbody (HTTP response code was $rcode)", $rcode, $rbody);	} 	if ($rcode < 200 || $rcode >= 300) {	  $this->handleApiError($rbody, $rcode, $resp);	}	return $resp;  }   private function _curlRequest($meth, $absUrl, $headers, $params)  {	$curl = curl_init();	$meth = strtolower($meth);	$opts = array();	if ($meth == 'get') {	  $opts[CURLOPT_HTTPGET] = 1;	  if (count($params) > 0) {$encoded = self::encode($params);$absUrl = "$absUrl?$encoded";	  }	} else if ($meth == 'post') {	  $opts[CURLOPT_POST] = 1;	  $opts[CURLOPT_POSTFIELDS] = self::encode($params);	} else if ($meth == 'delete')  {	  $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';	  if (count($params) > 0) {$encoded = self::encode($params);$absUrl = "$absUrl?$encoded";	  }	} else {	  throw new Stripe_ApiError("Unrecognized method $meth");	} 	$absUrl = self::utf8($absUrl);	$opts[CURLOPT_URL] = $absUrl;	$opts[CURLOPT_RETURNTRANSFER] = true;	$opts[CURLOPT_CONNECTTIMEOUT] = 30;	$opts[CURLOPT_TIMEOUT] = 80;	$opts[CURLOPT_RETURNTRANSFER] = true;	$opts[CURLOPT_HTTPHEADER] = $headers;	if (!Stripe::$verifySslCerts)	  $opts[CURLOPT_SSL_VERIFYPEER] = false; 	curl_setopt_array($curl, $opts);	$rbody = curl_exec($curl); 	$errno = curl_errno($curl);	if ($errno == CURLE_SSL_CACERT ||$errno == CURLE_SSL_PEER_CERTIFICATE ||$errno == 77 // CURLE_SSL_CACERT_BADFILE (constant not defined in PHP though)) {	  array_push($headers, 'X-Stripe-Client-Info: {"ca":"using Stripe-supplied CA bundle"}');	  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);	  curl_setopt($curl, CURLOPT_CAINFO,				  dirname(__FILE__) . '/../data/ca-certificates.crt');	  $rbody = curl_exec($curl);	} 	if ($rbody === false) {	  $errno = curl_errno($curl);	  $message = curl_error($curl);	  curl_close($curl);	  $this->handleCurlError($errno, $message);	} 	$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);	curl_close($curl);	return array($rbody, $rcode);  }   public function handleCurlError($errno, $message)  {	$apiBase = Stripe::$apiBase;	switch ($errno) {	case CURLE_COULDNT_CONNECT:	case CURLE_COULDNT_RESOLVE_HOST:	case CURLE_OPERATION_TIMEOUTED:	  $msg = "Could not connect to Stripe ($apiBase).  Please check your internet connection and try again.  If this problem persists, you should check Stripe's service status at [url="https://twitter.com/stripestatus"]https://twitter.com/stripestatus[/url], or let us know at support@stripe.com.";	  break;	case CURLE_SSL_CACERT:	case CURLE_SSL_PEER_CERTIFICATE:	  $msg = "Could not verify Stripe's SSL certificate.  Please make sure that your network is not intercepting certificates.  (Try going to $apiBase in your browser.)  If this problem persists, let us know at support@stripe.com.";	  break;	default:	  $msg = "Unexpected error communicating with Stripe.  If this problem persists, let us know at support@stripe.com.";	} 	$msg .= "\n\n(Network error [errno $errno]: $message)";	throw new Stripe_ApiConnectionError($msg);  }} 

Edited by aarontbarksdale
Link to comment
Share on other sites

Okay...so after playing around with the damn thing and making it NOT have the above error, it runs ONCE and gives me the error. Here's the code snippets that the signup.php file for processing:

<head>  <script type="text/javascript" src="https://js.stripe.com/v1/"></script>  <!-- jQuery is used only for this example; it isn't required to use Stripe -->  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <script type="text/javascript">    // This identifies your website in the createToken call below    Stripe.setPublishableKey('pk_test_jsKjsHzkOpK2PG7ZMLQ9XYj8');    var stripeResponseHandler = function(status, response) {      var $form = $('#payment-form');      if (response.error) {        // Show the errors on the form        $form.find('.payment-errors').text(response.error.message);        $form.find('button').prop('disabled', false);      } else {        // token contains id, last4, and card type        var token = response.id;        // Insert the token into the form so it gets submitted to the server        $form.append($('<input type="hidden" name="stripeToken" />').val(token));        // and re-submit        $form.get(0).submit();      }    };    jQuery(function($) {      $('#payment-form').submit(function(e) {        var $form = $(this);        // Disable the submit button to prevent repeated clicks        $form.find('button').prop('disabled', true);        Stripe.createToken($form, stripeResponseHandler);        // Prevent the form from submitting with the default action        return false;      });    });  </script></head>....//utilizes the Checkout script<?php require_once('login/stripe/config.php'); ?><form method="post" action="charge.php"><script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"          data-key="<?php echo $stripe['publishable_key']; ?>"          data-amount="2499"           data-description="Monthly Subscription"          data-name="Child Support Arrearage Calculator"          data-panel-label="Subscribe"          data-address="Customer's Address"></script></form>

The charge.php script is:

<?php require_once(dirname(__FILE__) . '/login/stripe/config.php'); $token  = $_POST['stripeToken']; $customer = Stripe_Customer::create(array(      "email" => $_POST['email'],      "card"  => $token,)); $charge = Stripe_Charge::create(array(      'customer' => $customer->id,      'amount'   => 2499,      'currency' => 'usd')); echo '<h1>Successfully charged $24.99!</h1><br/>'; $_SESSION['stripeToken'] = $token;?>

Link to comment
Share on other sites

Okay, so I found this tutorial, http://net.tutsplus.com/tutorials/tools-and-tips/so-you-want-to-accept-credit-cards-online/ and I got it to work...the ONLY thing that I have done to change the code is my Secret/Publish Live and Test keys...and the price...all code is the same. I've tried to redirect a successful payment to another page, and an unsuccessful payment to reload. But it throws an error reading pay.php file. So, I remove the code and viola! it works again. I tried to add a CreateCustomer script (per the Stripe.com docs) and it threw the an error saying the credit card is invalid. I need it to do like it's supposed to...collect and store the information, charge the card, redirect to a page where they can continue logging in and using the system. Any suggestions...

Link to comment
Share on other sites

Okay, I think I've resolved my issue. Since I could not get everything to generate like I needed it to, I simply added a line in the Javascript that will redirect the page upon success to the CONFIRMED page that will include the php script for adding information to the database.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...