Skip to content

Instantly share code, notes, and snippets.

@Ocramius
Last active March 16, 2016 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ocramius/2eac05e3a5d9fefd428c to your computer and use it in GitHub Desktop.
Save Ocramius/2eac05e3a5d9fefd428c to your computer and use it in GitHub Desktop.
Fake a stripe payment process in a Mink test context
<?php
declare(strict_types = 1);
namespace MyApp\Web\Utility\Stripe;
use Behat\Mink\Session;
use MyApp\Domain\Payment\Stripe\PublishableKey;
use Zend\Escaper\Escaper;
final class SubmitFakeStripeCreditCard
{
const JS_TEMPLATE = <<<'JS'
(function () {
var stripeJs = document.createElement('script'),
$payForReviewForm = document.querySelector('%s'),
$fakeForm = document.createElement('form'),
$stripeToken = document.createElement('input'),
$stripeTokenType = document.createElement('input'),
$stripeEmail = document.createElement('input'),
$submitButton = document.createElement('input'),
token;
stripeJs.type = 'text/javascript';
stripeJs.src = 'https://js.stripe.com/v2/';
stripeJs.onreadystatechange = stripeJs.onload = function() {
if (! stripeJs.readyState || /loaded|complete/.test(stripeJs.readyState)) {
Stripe.setPublishableKey('%s');
Stripe.card.createToken(
{
number: '4242424242424242',
cvc: '123',
exp_month: '1',
exp_year: (new Date()).getFullYear() + 2
},
function (status, response) {
if (response.error) {
return;
}
$fakeForm = document.createElement('form');
$fakeForm.action = $payForReviewForm.action;
$fakeForm.method = $payForReviewForm.method;
$stripeToken.type = 'hidden';
$stripeToken.name = 'stripeToken';
$stripeToken.value = response.id;
$stripeTokenType.type = 'hidden';
$stripeTokenType.name = 'stripeTokenType';
$stripeTokenType.value = 'card';
$stripeEmail.type = 'hidden';
$stripeEmail.name = 'stripeEmail';
$stripeEmail.value = 'test@code-reviews.io';
$submitButton.type = 'hidden';
$fakeForm.appendChild($stripeToken);
$fakeForm.appendChild($stripeTokenType);
$fakeForm.appendChild($stripeEmail);
$fakeForm.appendChild($submitButton);
document.body.appendChild($fakeForm);
$fakeForm.submit();
}
);
}
}
document.getElementsByTagName('head')[0].appendChild(stripeJs);
}());
JS;
public function __invoke(Session $session, PublishableKey $publishableKey, string $paymentFormToCopySelector)
{
$escaper = new Escaper();
$session->executeScript(sprintf(self::JS_TEMPLATE, $escaper->escapeJs($paymentFormToCopySelector), (string) $publishableKey));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment