Browse Source

Credit Card Payment Form - now rendering

Richard Knight 6 years ago
parent
commit
b9ca0e6d65

+ 6 - 1
config/config.yml.dist

@@ -3,6 +3,11 @@ sq_auth_url: /oauth2/authorize
 
 
 sq_app_id: sq0idp-E62fjwNzSQG08kHHzOhc7w
 sq_app_id: sq0idp-E62fjwNzSQG08kHHzOhc7w
 sq_app_secret: sq0csp-w3zX86p5tbHb5kKlCyL2CM0zP7ldpRXZRHDbHFiAPi4
 sq_app_secret: sq0csp-w3zX86p5tbHb5kKlCyL2CM0zP7ldpRXZRHDbHFiAPi4
+sq_location_id: GEB1SBFPZHVVK
 
 
-sq_sandbox_add_id: sandbox-sq0idp-E62fjwNzSQG08kHHzOhc7w
+sq_sandbox_app_id: sandbox-sq0idp-E62fjwNzSQG08kHHzOhc7w
 sq_sandbox_token: sandbox-sq0atb-pDGW0n945W5jLLIA4eUhpQ
 sq_sandbox_token: sandbox-sq0atb-pDGW0n945W5jLLIA4eUhpQ
+sq_sandbox_location_id: CBASEC73OwdNXqWhk6o3SKFwsvUgAQ
+
+
+

+ 14 - 3
src/Controller/SquareBackendController.php

@@ -7,6 +7,8 @@ use Silex\Application;
 use Silex\ControllerCollection;
 use Silex\ControllerCollection;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+
 
 
 /**
 /**
  * The controller for Square backend routes.
  * The controller for Square backend routes.
@@ -30,8 +32,8 @@ class SquareBackendController extends Base
     
     
     public function addRoutes(ControllerCollection $collection)
     public function addRoutes(ControllerCollection $collection)
     {
     {
-        $collection->match('/', [$this, 'squareDashboard']);
-        $collection->match('/request-oauth-token', [$this, 'oauthRequestToken']);
+        $collection->match('/', [$this, 'squareDashboard'])->before([$this, 'checkUserPermissions']);
+        $collection->match('/request-oauth-token', [$this, 'oauthRequestToken'])->before([$this, 'checkUserPermissions']);
         return $collection;
         return $collection;
     }
     }
 
 
@@ -78,7 +80,16 @@ class SquareBackendController extends Base
 
 
     // ------------------------------------------------------------------------------------------------------------------------------------------
     // ------------------------------------------------------------------------------------------------------------------------------------------
 
 
-    private function getOAuthToken($authorizationCode) {
+	public function checkUserPermissions()
+	{
+		$currentUser = $this->app['users']->getCurrentUser();
+		$currentUserId = $currentUser['id'];
+		if (!$this->app['users']->hasRole($currentUserId, 'root') && !$this->app['users']->hasRole($currentUserId, 'admin')) {
+			return new RedirectResponse($this->generateUrl('dashboard'), Response::HTTP_SEE_OTHER);
+		}
+	}
+	
+	private function getOAuthToken($authorizationCode) {
         // Exchange the authorization code for an OAuth token
         // Exchange the authorization code for an OAuth token
         // Create an OAuth API client
         // Create an OAuth API client
         $oauthApi = new \SquareConnect\Api\OAuthApi($this->apiClient);
         $oauthApi = new \SquareConnect\Api\OAuthApi($this->apiClient);

+ 3 - 3
src/SquarepayExtension.php

@@ -46,7 +46,7 @@ class SquarepayExtension extends SimpleExtension
 		});
 		});
 
 
 		$app['twig.runtime.square'] = $app->share(function ($app) {
 		$app['twig.runtime.square'] = $app->share(function ($app) {
-			return new Twig\SquareTwigRuntime($app['square.apiClient']);
+			return new Twig\SquareTwigRuntime($app['square.apiClient'], $app['twig'], $this->getConfig());
 		});
 		});
 
 
 		$app['twig.runtimes'] = $app->extend(
 		$app['twig.runtimes'] = $app->extend(
@@ -94,10 +94,10 @@ class SquarepayExtension extends SimpleExtension
 	
 	
 	protected function registerTwigFunctions() {
 	protected function registerTwigFunctions() {
         $getCatalog = [Twig\SquareTwigRuntime::class, 'getCatalog'];
         $getCatalog = [Twig\SquareTwigRuntime::class, 'getCatalog'];
-        $displayCCForm = [Twig\SquareTwigRuntime::class, 'displayCCForm'];
+        $cardform = [Twig\SquareTwigRuntime::class, 'displayCCForm'];
 		return [
 		return [
 			'getcatalog' => [ $getCatalog ],
 			'getcatalog' => [ $getCatalog ],
-			'ccform' => [ $displayCCForm, ['is_safe' => ['html']] ]
+			'cardform' => [ $cardform, ['is_safe' => ['html']] ]
 		];
 		];
 	}
 	}
 
 

+ 8 - 4
src/Twig/SquareTwigRuntime.php

@@ -14,9 +14,11 @@ class SquareTwigRuntime
 {
 {
     private $apiClient;
     private $apiClient;
 
 
-	public function __construct($apiClient)
+	public function __construct($apiClient, $twig, $config)
 	{
 	{
 		$this->apiClient = $apiClient;
 		$this->apiClient = $apiClient;
+		$this->twig = $twig;
+		$this->config = $config;
 	}
 	}
 
 
 	public function getCatalog()
 	public function getCatalog()
@@ -37,9 +39,11 @@ class SquareTwigRuntime
 		return $response;
 		return $response;
 	}
 	}
 	
 	
-	public function displayCardEntryForm() {
-		return $this->renderTemplate('@Squarefront/cardentryform.twig');
+	public function displayCCForm() {
+		$context = $this->config + [
+			'testmode' => true
+		];
+		return $this->twig->render('@Squarefront/cardentryform.twig', $context);
 	}
 	}
 
 
-
 }
 }

+ 3 - 1
templates/frontend/cardentryform.twig

@@ -1,5 +1,7 @@
 <h1>Credit Card Payment Form</h1>
 <h1>Credit Card Payment Form</h1>
 
 
+<script type="text/javascript" src="https://js.squareup.com/v2/paymentform"></script>
+<script type="text/javascript" src="/extensions/vendor/ginger/squarepay/sq-paymentform.js"></script>
 <script>
 <script>
 // For sq-paymentform.js	
 // For sq-paymentform.js	
 var isPaymentsPage = true;
 var isPaymentsPage = true;
@@ -12,7 +14,7 @@ var locationId = '{{ testmode ? sq_sandbox_location_id : sq_location_id }}';
 	You should replace the action attribute of the form with the path of
 	You should replace the action attribute of the form with the path of
 	the URL you want to POST the nonce to (for example, "/process-card")
 	the URL you want to POST the nonce to (for example, "/process-card")
 	-->
 	-->
-	<form id="nonce-form" novalidate action="/process.php" method="post">
+	<form id="nonce-form" novalidate action="/process-square" method="post">
 	<table>
 	<table>
 		<tbody>
 		<tbody>
 			<tr>
 			<tr>

+ 90 - 0
web/sq-paymentform.js

@@ -0,0 +1,90 @@
+// Create and initialize a payment form object
+var paymentForm;
+
+// ---------------------------------------------------------------------------------------------------------------------
+
+function init() {
+
+	paymentForm = new SqPaymentForm({
+  
+		// Initialize the payment form elements
+		applicationId: applicationId,
+		locationId: locationId,
+		autoBuild: false,
+	  
+		inputClass: 'sq-input',
+
+		// Customize the CSS for SqPaymentForm iframe elements
+		inputStyles: [{
+			fontSize: '1em',
+			color: 'purple',
+			fontWeight: 'bold',
+			padding: '5px'
+		}],
+	  
+		applePay: false,
+		googlePay: false,
+		masterpass: false,
+
+		// Initialize the credit card placeholders
+		cardNumber: {
+			elementId: 'sq-card-number',
+			placeholder: '•••• •••• •••• ••••'
+		},
+		cvv: {
+			elementId: 'sq-cvv',
+			placeholder: 'CVV'
+		},
+		expirationDate: {
+			elementId: 'sq-expiration-date',
+			placeholder: 'MM/YY'
+		},
+		postalCode: {
+			elementId: 'sq-postal-code'
+		},
+	  
+		// SqPaymentForm callback functions
+		callbacks: {
+	  
+			methodsSupported: function (methods) {
+			},
+
+			unsupportedBrowserDetected: function() {
+				alert('UNSUPPORTED BROWSER');
+			},
+	
+			cardNonceResponseReceived: function(errors, nonce, cardData, billingContact, shippingContact) {
+				if (errors) {
+					// Log errors from nonce generation to the Javascript console
+					console.log("Encountered errors:");
+					errors.forEach(function(error) {
+						console.log('  ' + error.message);
+					});
+					return;
+				}
+				alert('Nonce received: ' + nonce); /* FOR TESTING ONLY */
+				document.getElementById('card-nonce').value = nonce; // Assign the nonce value to the hidden form field
+				document.getElementById('nonce-form').submit();	// POST the nonce form to the payment processing page
+			}
+		}
+	});
+
+	paymentForm.build();
+	return paymentForm;
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+
+// Called when 'Pay With Card' is clicked
+function requestCardNonce(event) {
+	event.preventDefault(); // Don't submit the form until SqPaymentForm returns with a nonce
+	paymentForm.requestCardNonce(); // Request a nonce from the SqPaymentForm object
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+
+if (document.readyState === 'loading') {
+    document.addEventListener('DOMContentLoaded', init);
+} else {  // `DOMContentLoaded` already fired
+    init();
+}