Implementation CyberSource in Python
I am trying to implement CyberSource´s Microform in Python, but there is a problem with the captureContext I am sending to the frontend. This is the message error:
r {name: 'MicroformError', reason: 'CAPTURE_CONTEXT_INVALID', message: 'You have not supplied a valid capture context.', informationLink: 'https://www.cybersource.com/products/payment_security/secure_acceptance', correlationId: undefined, …} correlationId: undefined details: undefined informationLink: "https://www.cybersource.com/products/payment_security/secure_acceptance" message: "You have not supplied a valid capture context." name: "MicroformError" reason: "CAPTURE_CONTEXT_INVALID"
captureContext I am sending is something like this:
{"kty":"RSA",
"use":"enc",
"kid":"08ajMBidgTrHvGJVzpR3ZxrNylkXqVA1",
"n":"i6vpy5CdziPfwAMk6YyQxfLE2xGjA11gRzp1pL_LwIL87gSSsevZgRRVkI_Y2Jv95wT12O0DgumypVeHcGXmW5oR5tBJNhGp61f2qYHhl4PGMXyYFZ5OTgRYfJ2le0OYL4F4eQdqGd25ghq3qJkMvEN-USLyEGsNfeLwGvHsVtlJK9_QnKshcc-2oT2sKSNIkwxs7FH6afHc67WJUCFtqQQARJBX45O47MSlRbpRHAqJkw2zD35l6RDMQpRAKLzbJ9-cmsZpdWAhCTAvaSU2yH-LvVeEvzfDjWPrd6QcPpV_FYHxO1lHE18rmJHFTow6-LURaLQwl1PuG-C7PI2pZw",
"e":"AQAB"}
I am using this code to generate the key:
def generate_key(compra, medio_pago):
encryptionType = "RsaOaep"
targetOrigin = "http://localhost:8000"
requestObj = GeneratePublicKeyRequest(
encryption_type = encryptionType,
target_origin = targetOrigin
)
requestObj = del_none(requestObj.__dict__)
requestObj = json.dumps(requestObj)
format = "legacy"
try:
config_obj = PagoCyberSource(medio_pago).get_configuration()
api_instance = KeyGenerationApi(config_obj)
return_data, status, body = api_instance.generate_public_key(format, requestObj)
print("\nAPI RESPONSE CODE : ", status)
print("\nAPI RESPONSE BODY : ", body)
return return_data
except Exception as e:
print("\nException when calling KeyGenerationApi->generate_public_key: %s\n" % e)
And these are the Microform and scripts ({{boton_compra.jwk}} is the captureContext):
<h1>Checkout</h1>
<div id="errors-output" role="alert"></div>
<form action="/token" id="my-sample-form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="cardholderName">Name</label>
<input id="cardholderName" class="form-control" name="cardholderName" placeholder="Name on the card">
<label id="cardNumber-label">Card Number</label>
<div id="number-container" class="form-control"></div>
<label for="securityCode-container">Security Code</label>
<div id="securityCode-container" class="form-control"></div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="expMonth">Expiry month</label>
<select id="expMonth" class="form-control">
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="expYear">Expiry year</label>
<select id="expYear" class="form-control">
<option>2022</option>
<option>2023</option>
<option>2024</option>
<option>2025</option>
<option>2026</option>
<option>2027</option>
<option>2028</option>
<option>2029</option>
</select>
</div>
</div>
<button type="button" id="pay-button" class="btn btn-primary">Pay</button>
<input type="hidden" id="flexresponse" name="flexresponse">
<input type="hidden" id="key-id" value="{{boton_compra.jwk}}">
</form>
<script src="https://flex.cybersource.com/microform/bundle/v2/flex-microform.min.js"></script>
<script type="module">
// Variables from the HTML form
var form = document.querySelector('#my-sample-form');
var payButton = document.querySelector('#pay-button');
var flexResponse = document.querySelector('#flexresponse');
var expMonth = document.querySelector('#expMonth');
var expYear = document.querySelector('#expYear');
var errorsOutput = document.querySelector('#errors-output');
// the capture context that was requested server-side for this transaction
var captureContext = document.getElementById("key-id").value ;
console.log(captureContext);
// custom styles that will be applied to each field we create using Microform
var myStyles = {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#555'
},
':focus': { 'color': 'blue' },
':disabled': { 'cursor': 'not-allowed' },
'valid': { 'color': '#3c763d' },
'invalid': { 'color': '#a94442' }
};
// setup Microform
var flexx = new Flex(captureContext);
var microform = flexx.microform({ styles: myStyles });
var number = microform.createField('number', { placeholder: 'Enter card number' });
var securityCode = microform.createField('securityCode', { placeholder: '•••' });
number.load('#number-container');
securityCode.load('#securityCode-container');
// Configuring a Listener for the Pay button
payButton.addEventListener('click', function() {
// Compiling MM & YY into optional paramiters
var options = {
expirationMonth: document.querySelector('#expMonth').value,
expirationYear: document.querySelector('#expYear').value
};
//
microform.createToken(options, function (err, token) {
if (err) {
// handle error
console.error(err);
errorsOutput.textContent = err.message;
} else {
// At this point you may pass the token back to your server as you wish.
// In this example we append a hidden input to the form and submit it.
console.log(JSON.stringify(token));
flexResponse.value = JSON.stringify(token);
form.submit();
}
});
});
</script>
I was using these samples as a reference: https://github.com/CyberSource/cybersource-rest-samples-python/tree/master/samples/FlexMicroform Please tell me if you need something else