cancel
Showing results for 
Search instead for 
Did you mean: 

Accept Hosted help with IFrame/Lightbox asp.net

I currently have a SIM style asp.net page that opens the old school Authorize.net hosted page.  Currently the page collects transaction details, then posts the collected information to the old Authorize.net hosted page via a single button click. I have been looking at the new Accept Hosted implementations and am trying to get the IFRAME/Lightbox up and running as it is the only scenario that appears to support custom reciepts and redirecting (we email our own receipt and redirect to a confirmation page).

 

So modifying the IFrame/Lightbox code shown on 

 

https://developer.authorize.net/api/reference/features/accept_hosted.html#Displaying_the_Form

 

I am able to obtain a token when the button is clicked, however, I have not been able to display the hosted form in the IFrame/Lightbox.  I obtain the token in the asp.net codebehind the page, but can't seem to pass it back out to the AuthorizeNetPopup.openPopup or alternately execute the AuthorizeNetPopup.openPopup script from the codebehind.

 

Basically, what I am wanting to do is obtain the token and display the accept hosted page in an IFrame/Lightbox with a single button click in an asp.net page and I can't seem to figure out how to make that happen, or if it is even possible.  Any thoughts/samples would be appreciated.

emlinney
Contributor
1 ACCEPTED SOLUTION

Accepted Solutions

Finally got this to work.  In the HTML code I removed the following lines:

 

$("#popupToken").val($("<% = thetoken %>").val());
form.action = "https://test.authorize.net/payment/payment";

and in the Sub PosttoProcessingCenter subroutine of the .aspx code behind I added:

 

ScriptManager.RegisterClientScriptBlock(Page, GetType(String), "Javascript", "AuthorizeNetPopup.openPopup(); return false;", True)

 just below the line:

thetoken = mymessage("token").ToString

View solution in original post

8 REPLIES 8

@emlinney 

 

It should be doable. What you do is have your form API call programmed to execute with no button press.   As soon as the page loads, you will have a token. The customer then presses the button which submits that token as a POST request to get the form.  

Renaissance
All Star

This is my .aspx proof of concept page that is mostly made up of the sample page I linked to in my original post:

 

%@ Page Language="vb" AutoEventWireup="false" Codebehind="testaccepthosted.aspx.vb" Inherits="Adv.FoundationWebPages.Website.accepthosted"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>accept hosted test</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

<meta name="vs_defaultClientScript" content="JavaScript" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<script type="text/javascript" src="Scripts/jquery-1.12.2.js"></script>-->
<script type="text/javascript" src="Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="Scripts/bootstrap.js"></script>
<script type="text/javascript" src="Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-3.4.1.js"></script>

<style type="text/css">

body {
margin: 0px;
padding: 0px;
}

#divAuthorizeNetPopupScreen {
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 1;
background-color: #808080;
opacity: 0.5;
-ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)';
filter: alpha(opacity=50);
}

#divAuthorizeNetPopup {
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -200px;
z-index: 2;
overflow: visible;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupOuter {
background-color: #dddddd;
border-width: 1px;
border-style: solid;
border-color: #a0a0a0 #909090 #909090 #a0a0a0;
padding: 4px;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupTop {
height: 23px;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose {
position: absolute;
right: 7px;
top: 7px;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose a {
background-image: url('content/closeButton1.png');
background-repeat: no-repeat;
height: 16px;
width: 16px;
display: inline-block;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose a:hover {
background-image: url('content/closeButton1h.png');
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose a:active {
background-image: url('content/closeButton1a.png');
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupInner {
background-color: #ffffff;
border-width: 2px;
border-style: solid;
border-color: #cfcfcf #ebebeb #ebebeb #cfcfcf;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupBottom {
height: 30px;
}

.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupLogo {
position: absolute;
right: 9px;
bottom: 4px;
width: 200px;
height: 25px;
background-image: url('content/powered_simple.png');
}

.AuthorizeNetPopupSimpleTheme .AuthorizeNetPopupOuter {
border: 1px solid #585858;
background-color: #ffffff;
}


</style>
</HEAD>

<body MS_POSITIONING="FlowLayout" >

 

<form id="Form1" method="post" runat="server">

<asp:Button ID="button1" Runat="server" Text="Process Credit Card" ></asp:Button>

</form>

 

<form method="post" action="https://test.authorize.net/payment/payment" id="formAuthorizeNetPopup" name="formAuthorizeNetPopup" target="iframeAuthorizeNet" style="display:none;">

<input type="hidden" id="popupToken" name="token" value="" />

</form>

 

<br />


<div id="divAuthorizeNetPopup" style="display:none;" class="AuthorizeNetPopupGrayFrameTheme">
<div class="AuthorizeNetPopupOuter">
<div class="AuthorizeNetPopupTop">
<div class="AuthorizeNetPopupClose">
<a href="javascript&colon;;" onclick="AuthorizeNetPopup.closePopup();" title="Close"> </a>
</div>
</div>
<div class="AuthorizeNetPopupInner">
<iframe name="iframeAuthorizeNet" id="iframeAuthorizeNet" src="empty.html" frameborder="0" scrolling="no" width="100%" height="650px"></iframe>
</div>
<div class="AuthorizeNetPopupBottom">
<div class="AuthorizeNetPopupLogo" title="Powered by Authorize.Net"></div>
</div>
<div id="divAuthorizeNetPopupScreen" style="display:none;"></div>
</div>
</div>

 

<script type="text/javascript">
(function () {
if (!window.AuthorizeNetPopup) window.AuthorizeNetPopup = {};
if (!AuthorizeNetPopup.options) AuthorizeNetPopup.options = {
onPopupClosed: null
};

AuthorizeNetPopup.closePopup = function () {
document.getElementById("divAuthorizeNetPopupScreen").style.display = "none";
document.getElementById("divAuthorizeNetPopup").style.display = "none";
document.getElementById("iframeAuthorizeNet").src="empty.html";
document.getElementById("btnOpenAuthorizeNetPopup").disabled = false;
if (AuthorizeNetPopup.options.onPopupClosed) AuthorizeNetPopup.options.onPopupClosed();
};


AuthorizeNetPopup.openPopup = function () {
alert('you are in popup!');
var popup = document.getElementById("divAuthorizeNetPopup");
var popupScreen = document.getElementById("divAuthorizeNetPopupScreen");
var ifrm = document.getElementById("iframeAuthorizeNet");
var form = document.forms["formAuthorizeNetPopup"];
$("#popupToken").val($("<% = thetoken %>").val());
form.action = "https://test.authorize.net/payment/payment";
ifrm.style.width = "442px";
ifrm.style.height = "578px";

form.submit();

popup.style.display = "";
popupScreen.style.display = "";
centerPopup();
};

AuthorizeNetPopup.onReceiveCommunication = function (querystr) {
var params = parseQueryString(querystr);
switch (params["action"]) {
case "successfulSave":
AuthorizeNetPopup.closePopup();
break;
case "cancel":
AuthorizeNetPopup.closePopup();
break;
case "transactResponse":
var response = params["response"];
document.getElementById("token").value = response;
AuthorizeNetPopup.closePopup();
break;
case "resizeWindow":
var w = parseInt(params["width"]);
var h = parseInt(params["height"]);
var ifrm = document.getElementById("iframeAuthorizeNet");
ifrm.style.width = w.toString() + "px";
ifrm.style.height = h.toString() + "px";
centerPopup();
break;
}
};


function centerPopup() {
var d = document.getElementById("divAuthorizeNetPopup");
d.style.left = "50%";
d.style.top = "50%";
var left = -Math.floor(d.clientWidth / 2);
var top = -Math.floor(d.clientHeight / 2);
d.style.marginLeft = left.toString() + "px";
d.style.marginTop = top.toString() + "px";
d.style.zIndex = "2";
if (d.offsetLeft < 16) {
d.style.left = "16px";
d.style.marginLeft = "0px";
}
if (d.offsetTop < 16) {
d.style.top = "16px";
d.style.marginTop = "0px";
}
}

function parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
vars.push(pair[0]);
vars[pair[0]] = unescape(pair[1]);
}
return vars;
}
}());

</script>

</body>
</HTML>

 

Again, I'm trying to develop a proof of concept for the page that I need to incorporate this into.  That page is just a form that donors to our foundation fill out noting how much they would like to donate. They would then click a button which should generate the token and display the credit card payment. page.

emlinney
Contributor

And the codebehind page...there is extra code in here from stuff that I have tried which did not seem to work...hopefully someone will see something that can get me going in the right direction.  I can generate the token, but can't seem to display the accept hosted form in the lightbox.

 

Imports plg = Adv.FoundationWebPages.Forms.Business
Imports Adv.FoundationWebPages.Security.Business
Imports System.Net
Imports System.Web.Services
Imports System.Text
Imports System.IO
Imports System.Data
Imports System.Linq
Imports System.IO.TextReader
Imports Newtonsoft.Json

Partial Class accepthosted
Inherits BasePage

Dim solicitation As String
Dim systemsolic As String
Dim millid As String
Dim college As String
Dim department As String
Dim project As String
Public myidnumber As String
Dim x As Integer
Dim myURL As String

Dim otherrowcount As Integer
Dim rowcount As Integer
Dim itemcount As Integer
Dim dataitemcount As Integer
Dim TotalDonation As Double = 0
Dim SubTotal As Double = 0
Dim activeProtocol As SecurityProtocolType = ServicePointManager.SecurityProtocol 'TLS 1.2 support
Public mytoken As String '8/30/19
Public thetoken As String '9/09/19
Public myreturnURL As String '8/30/19
Dim x_login As String
Dim x_tran_key As String
Dim x_signature_key As String 'signature key is not an actual NVP for Auth.net just wanted the variable to follow the convention
Dim myPaymentFormUri As New Uri("https://test.authorize.net/payment/payment") '8/30/19
Dim myTokenUri As New Uri("https://apitest.authorize.net/xml/v1/request.api") '8/30/19
Dim addsettings As String

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim objAuth As New AuthCode(True, "S") ' Change to S for sandbox acct F for foundation
x_login = objAuth.AuthLogin
x_tran_key = objAuth.AuthTransKey
x_signature_key = objAuth.AuthSigKey

' set up fingerprint
Dim random As New Random
Dim x_fp_sequence = random.Next(0, 1000)
Dim x_fp_timestamp = CInt(DateDiff(DateInterval.Second, DateTime.UtcNow, New DateTime(1970, 1, 1)) * -1)
Dim x_fp_hash = GetAuthorizeNetHMACSHA512(x_signature_key, x_login & "^" & x_fp_sequence & "^" & x_fp_timestamp & "^" & Request.Form("x_amount") & "^")

'Put user code to initialize the page here
If Not Page.IsPostBack Then
Try

Catch ex As ExecutionEngineException
'add redirect to error page
End Try
End If

End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
Dim CCFrequency, PaymentType As String
Dim PrintFlg As Boolean
PrintFlg = False
PaymentType = "O"
PosttoProcessingCenter("0000", PrintFlg, PaymentType, 5.82, "IA")

End Sub

Sub PosttoProcessingCenter(ByVal pledgeid As Integer, ByVal PrintFlg As Boolean, ByVal PaymentType As String, ByVal ChargeAmt As Double, ByVal State As String)
Dim testrequest As String
Dim e As EventArgs
testrequest = System.Configuration.ConfigurationSettings.AppSettings("ccTestSupportUNI")

Dim myremotepost As RemotePostwTarget = New RemotePostwTarget
'Dim myremotepost As RemotePost = New RemotePost

Dim cust_id As String

If Request("m") > 0 Then
cust_id = Request("m")
Else
cust_id = "0"
End If

Dim x_source = "Sandbox"
Dim x_source_key = pledgeid
Dim x_cust_id = "0"
Dim x_amount = ChargeAmt
Dim x_first_name = "TEST"
Dim x_last_name = "AcceptHostedTESTING"
Dim x_address1 = "zzz Commons"
Dim x_address2 = ""
Dim x_address3 = ""
Dim x_city = "CF"
Dim x_state = State
Dim x_zip = "50000"
Dim x_country = "United States"
Dim x_phone = "1234567890"
Dim x_email = "test.accepthosted@test.com"
Dim x_URL = "https://www.adv.uni.edu/foundation/pledgeConfirm.aspx?PK=" & pledgeid & "&PrntFlg=" & PrintFlg & "&PayType=" & PaymentType
Dim x_test_request = testrequest
Dim token = ""

Dim mytransaction As New Transaction
mytransaction.apiloginid = x_login
mytransaction.apitransactionkey = x_tran_key
mytransaction.firstname = x_first_name
mytransaction.lastname = x_last_name
mytransaction.address = x_address1 + " " + x_address2 + " " + x_address3
mytransaction.city = x_city
mytransaction.state = x_state
mytransaction.zip = x_zip
mytransaction.amount = x_amount
mytransaction.source = x_source
mytransaction.cust_id = x_cust_id
mytransaction.phone = x_phone
mytransaction.email = x_email
mytransaction.return_url = x_URL
myreturnURL = mytransaction.return_url + "\"

Dim invoiceNum As String
invoiceNum = mytransaction.source + "_" + mytransaction.source

Dim JSONtokenstring
Dim JSONpformstring
JSONtokenstring = "{ ""getHostedPaymentPageRequest"": { ""merchantAuthentication"": { ""name"": """ + x_login + """,""transactionKey"": """ + x_tran_key + """ } ,""transactionRequest"": { ""transactionType"": ""authCaptureTransaction"",""amount"": """ + mytransaction.amount + """,""order"":{""invoiceNumber"": """ + invoiceNum + """, ""description"": ""AF gift""},""customer"":{""email"":""" + mytransaction.email + """},""billTo"":{""firstName"":""" + mytransaction.firstname + """,""lastName"":""" + mytransaction.lastname + """,""address"":""" + mytransaction.address + """,""city"":""" + mytransaction.city + """,""state"":""" + mytransaction.state + """,""zip"":""" + mytransaction.zip + """,""country"":""" + mytransaction.country + """,""phoneNumber"":""" + mytransaction.phone + """} }, " ' ""hostedPaymentSettings"": { ""setting"": [{""settingName"": ""hostedPaymentButtonOptions"",""settingValue"": ""{\""text\"":\""Pay\"" }"" }] } }"
addsettings = PaymentFormSettings()
JSONtokenstring = JSONtokenstring + addsettings + "] } }"

Dim tokendata As Byte() = Encoding.UTF8.GetBytes(JSONtokenstring)

Dim result_post = SendRequest(myTokenUri, tokendata, "application/json", "POST")

Dim mymessage = JsonConvert.DeserializeObject(result_post)
If mymessage("messages")("message")(0)("code").ToString = "I00001" Then

JSONpformstring = """token"""":""" & mymessage("token").ToString & """"

Dim pformdata As Byte() = Encoding.UTF8.GetBytes(JSONpformstring)
Dim payment_form_result = SendRequest(myPaymentFormUri, pformdata, "application/text", "POST")
thetoken = mymessage("token").ToString

Else
Response.Write("<br/><br/>You failed!")
Response.Write("<br/><br/>Result Code: " & mymessage("messages")("resultCode").ToString)
Response.Write("<br/><br/>Result Message Code: " & mymessage("messages")("message")(0)("code").ToString)
Response.Write("<br/><br/>Result Message Code text: " & mymessage("messages")("message")(0)("text").ToString)
End If

End Sub

Public Shared Function GetAuthorizeNetHMACSHA512(ByVal key As String, ByVal textToHash As String)

If String.IsNullOrEmpty(key) Then Return ""
If String.IsNullOrEmpty(textToHash) Then Return ""

If key.Length Mod 2 <> 0 OrElse key.Trim().Length < 2 Then
Return ""
End If

Try
Dim k As Byte() = Enumerable.Range(0, key.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(key.Substring(x, 2), 16)).ToArray()
Dim hmac As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(k)
Dim HashedValue As Byte() = hmac.ComputeHash((New System.Text.ASCIIEncoding()).GetBytes(textToHash))
Return BitConverter.ToString(HashedValue).Replace("-", String.Empty)
Catch ex As Exception
Return ""
End Try

End Function
Class Transaction
Public apiloginid As String
Public apitransactionkey As String
Public firstname As String
Public lastname As String
Public amount As String
Public address As String
Public city As String
Public state As String
Public zip As String
Public source As String
Public source_key As String
Public cust_id As String
Public country As String
Public phone As String
Public email As String
Public return_url As String
Public test_req As String

End Class

Private Function PaymentFormSettings()
Dim settings As String
Dim style As String
Dim paybutton As String
Dim showaddress As String
Dim showbankaccount As String
Dim showemail As String
Dim orderoptions As String
Dim returnoptions As String
Dim bgcolor As String
Dim iframecommunicator As String

settings = """hostedPaymentSettings"" : { ""setting"" : [{"
style = """settingName"" : ""hostedPaymentStyleOptions"",""settingValue"" : ""{\""bgColor\"":\""#4B116F\"" }"" },"
paybutton = "{""settingName"" : ""hostedPaymentButtonOptions"",""settingValue"" : ""{\""text\"":\""Complete Donation\"" }"" },"
showaddress = "{""settingName"" : ""hostedPaymentBillingAddressOptions"",""settingValue"" : ""{\""show\"":true }"" },"
showbankaccount = "{""settingName"" : ""hostedPaymentPaymentOptions"",""settingValue"" : ""{\""showBankAccount\"":false }"" },"
showemail = "{""settingName"" : ""hostedPaymentCustomerOptions"",""settingValue"" : ""{\""showEmail\"":true }"" },"
orderoptions = "{""settingName"" : ""hostedPaymentOrderOptions"",""settingValue"" : ""{\""show\"":true,\""merchantName\"":\""Foundation\"" }"" },"
iframecommunicator = "{""settingName"" : ""hostedPaymentIFrameCommunicatorUrl"",""settingValue"" : ""{\""url\"":\""https://localhost/foundation/IFrameCommunicator.html\"" }"" },"
returnoptions = "{""settingName"" : ""hostedPaymentReturnOptions"",""settingValue"" : ""{\""showReceipt\"":false,\""cancelUrl\"": \""https://localhost/foundation/pledgeform.aspx\"",\""cancelUrlText\"":\""Cancel\"" }"" }"
settings = settings + style + paybutton + showaddress + showbankaccount + showemail + orderoptions + iframecommunicator + returnoptions
Return settings
End Function

Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length


Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()

Dim response As Stream = req.GetResponse().GetResponseStream()

'Dim reader As New StreamReader(response, Encoding.UTF8)
Dim reader As New StreamReader(response, Encoding.ASCII)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()

Return res
End Function

Private Function GetPaymentForm(ByVal JsonData As String) As HttpWebRequest
Dim objhttpWebRequest As HttpWebRequest
Try
Dim httpWebRequest = DirectCast(WebRequest.Create("https://test.authorize.net/payment/payment"), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "POST"

Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream().ToString)


streamWriter.Write(JsonData)
streamWriter.Flush()
streamWriter.Close()
End Using

objhttpWebRequest = httpWebRequest

Catch ex As Exception
Response.Write("Send Request Error[{0}]" + ex.Message)

Return Nothing
End Try

Return objhttpWebRequest

End Function


End Class

Thank you for the reply and the suggestion.  I'm just not sure how to do what you propose.  Our current form takes in an amount and uses the button click to initiate the "get token" process. It is at that point that I can't figure out how to launch the accept hosted form in an iframe/lightbox.

Finally got this to work.  In the HTML code I removed the following lines:

 

$("#popupToken").val($("<% = thetoken %>").val());
form.action = "https://test.authorize.net/payment/payment";

and in the Sub PosttoProcessingCenter subroutine of the .aspx code behind I added:

 

ScriptManager.RegisterClientScriptBlock(Page, GetType(String), "Javascript", "AuthorizeNetPopup.openPopup(); return false;", True)

 just below the line:

thetoken = mymessage("token").ToString

Glad you found your solution. There are many ways to go about this. I am building an iframe integration right now and I have my token generated entirely with values that are pulled from the customers records in the database. 


@Renaissance wrote:

Glad you found your solution. There are many ways to go about this. I am building an iframe integration right now and I have my token generated entirely with values that are pulled from the customers records in the database. 


Interesting.  If you have some time, would you be able to briefly explain how you are doing that? I thought a token could only be generated if you had an amount to pass along to the API.

@emlinney

That is correct. I have a Review Your Order page and then the next button click takes them to the iframe payment page. On the iframe payment page all of the customers info, including the products in their cart, are pulled from the dB and those are used to calculate the amount to make the api call. The api call is made by the server side code and JavaScript loads the iframe on load.