var app = angular.module('plunker', ['paypal-checkout']);
app.config(function($httpProvider){
$httpProvider.defaults.useXDomain = true
delete $httpProvider.defaults.headers.common["X-Requested-With"]
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
<script src="paypal-checkout.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<paypal-checkout></paypal-checkout>
</body>
</html>
(function () {
'use strict'
angular.module('paypal-checkout', [])
angular
.module('paypal-checkout')
.directive('paypalCheckout', paypalCheckout)
function paypalCheckout ($http, $q, $timeout) {
return {
templateUrl: 'paypal-checkout.html',
restrict: 'EA',
scope: {},
link: function(scope, ele, attrs) {
var environment = 'sandbox' // CHANGE AS NEEDED
var merchantId = '6XF3MPZBZV6HU' // YOUR MERCHANT ID HERE (or import with scope)
var req = {
method: 'POST',
url: 'http://foo.bar', // YOUR SERVER HERE (or import with scope)
data: { foo: 'bar' } // YOUR DATA HERE (or import with scope)
}
scope.showButton = false
function sendRequest(data) {
var deferred = $q.defer()
$http(data)
.success(function(data, status) {
return deferred.resolve(data)
}).error(function(data, status) {
if (status === 0) { data = 'Connection error' }
return deferred.reject(data)
})
return deferred.promise
}
function showButton() {
scope.showButton = true
scope.$apply()
}
function delayAndShowButton() {
$timeout(showButton, 1000)
}
function loadPaypalButton() {
paypal.checkout.setup(merchantId, {
environment: environment,
buttons: [{ container: 't1', shape: 'rect', size: 'medium' }]
})
delayAndShowButton()
}
scope.initPaypal = function() {
if (scope.showButton == false) { return }
paypal.checkout.initXO()
return sendRequest(req)
.then(function(res) {
return paypal.checkout.startFlow(res.href)
})
.catch(function(err) {
console.log('Problem with checkout flow', err)
return paypal.checkout.closeFlow()
})
}
if (window.paypalCheckoutReady != null) {
scope.showButton = true
} else {
var s = document.createElement('script')
s.src = '//www.paypalobjects.com/api/checkout.js'
document.body.appendChild(s)
window.paypalCheckoutReady = function() {
return loadPaypalButton()
}
}
}
}
}
})()
<div>
<style>.paypal-button-widget { display: none !important; }</style>
<div id="t1">
<a href ng-click="initPaypal()"
ng-style="{ opacity: showButton ? '1' : '0.5' }">
<img src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" alt="PayPal">
</a>
</div>
</div>