Paypal SDK problems - asp.net

Goodmornig,
I have some problems with the integration of SDK paypal, I have the IPN that works nice, now I was trying to do the first request, instead of the form client side, the call server side, to be more safe.
I have put in my bin folder Paypal.dll and Newtonsoft.Json.dll then I have configurated the web.config
This is what I have read when I downloaded the Paypal nuget from Visual.
ATTENTION: This package replaces the RestApiSDK package (https://www.nuget.org/packages/restapisdk). You do not need to include the RestApiSdk package in your project if you are using this, the PayPal .NET SDK, package.
The PayPal REST API uses HTTP verbs and a RESTful endpoint structure. OAuth2.0 is used as the API Authorization framework. Request and response payloads are formatted as JSON.
I usually dont use editor, I have downloaded Visual just to get out these dll.
Then I have copied them inside my Web ASP.NET application.
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="live" />
<add name="connectionTimeout" value="360000"/>
<add name="requestRetries" value="1"/>
<add name="clientId" value="xxx" />
<add name="clientSecret" value="yyy" />
</settings>
</paypal>
And then I have translated the c#.net script sample to vb.net, this is the code
<%# Page Language="VB" Debug="true" aspcompat=true%>
<%# Import Namespace="MySql.Data.MySqlClient" %>
<%# Import Namespace="PayPal.Api" %>
<%
' Initialize an APIContext object with a fresh access token.
' The config will be populated with values set in the Web.config file.
Dim config = ConfigManager.Instance.GetProperties()
Dim accessToken = New OAuthTokenCredential(config).GetAccessToken()
Dim apiContext = New APIContext(accessToken)
Dim abc = Payment.Get(apiContext, "6N135681R73257100")
%>
I have put the ID of the transaction and I have this kind of error
PayPal.HttpException: The remote server returned an error: (404) Not Found.
If I try to do a payment so to do like this
<%# Page Language="VB" Debug="true" aspcompat=true%>
<%# Import Namespace="MySql.Data.MySqlClient" %>
<%# Import Namespace="PayPal.Api" %>
<%
' Initialize an APIContext object with a fresh access token.
' The config will be populated with values set in the Web.config file.
Dim config = ConfigManager.Instance.GetProperties()
Dim accessToken = New OAuthTokenCredential(config).GetAccessToken()
Dim apiContext = New APIContext(accessToken)
' Initialize Payout object
Dim payout = New Payout() With { _
.sender_batch_header = New PayoutSenderBatchHeader() With { _
.sender_batch_id = "batch_" + System.Guid.NewGuid().ToString().Substring(0, 8), _
.email_subject = "You have a payment" _
}, _
.items = New List(Of PayoutItem)({ _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "0.99", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-one#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_1" _
}, _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "0.90", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-two#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_2" _
}, _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "2.00", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-three#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_3" _
} _
}) _
}
' Create the payout
Dim createdPayout = payout.Create(apiContext, False)
%>
I have this kind of error, Did I forgot to copy inside my project anything? How could I fix it? Thank you very much
PayPal.HttpException: The remote server returned an error: (403) Forbidden.

Related

What's wrong with my ASP.NET / Visual Basic code?

I'm new to ASP.NET / Visual basic. I'm trying to create a simple get request to get the data from the database. But whenever the page loads, I get a generic 500 server error code in the console. Here is my ASP.NET code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
var dataSource = new kendo.data.DataSource({ transport: {
read: {
url: "/webservices/alertService.asmx/GetAlert",
dataType: "json"
},
update: {
url: "/webservices/alertService.asmx/UpdateAlert",
dataType: "json"
}
}});
var alertObj = dataSource.read();
console.log("alertObj: ", alertObj);
var pageBody = document.getElementById('page-body');
pageBody.innerHTML = "<h1>Website alert page is currently being built...</h1><br/>" +
"<p>" + alertObj.alert_title + "</p><br/>" +
"<p>" + alertObj.alert_body + "</p><br/>"
</script>
<div id="page-body"></div>
</asp:content>
Here is my Visual Basic code:
<%# WebService Language="VB" Class="MapService" %>
Imports System
Imports System.IO
Imports System.Security
Imports System.Configuration
Imports System.Xml
Imports System.Web
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Xml.Serialization
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Collections.Generic
Imports Newtonsoft.Json
Imports System.Net.Http
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class MapService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Sub GetAlert()
Dim xmlString As String = ""
Try
Dim sConnString As String = ConfigurationManager.ConnectionStrings("WebApp").ConnectionString
Dim odbcConn As OdbcConnection = New OdbcConnection(sConnString)
Dim sQueryString As String = "SELECT * FROM tblalert WHERE alert_id = 1"
Dim DBCommand As New OdbcCommand(sQueryString, odbcConn)
odbcConn.Open()
Try
Dim odbcReader As OdbcDataReader = DBCommand.ExecuteReader(CommandBehavior.CloseConnection)
While odbcReader.Read()
xmlString += "{"
xmlString += """alert_id"":""" & Convert.ToInt16(odbcReader("alert_id")) & ""","
xmlString += """alert_title"":""" & Trim(odbcReader("alert_title").ToString) & ""","
xmlString += """alert_body"":""" & Trim(odbcReader("alert_body").ToString) & ""","
xmlString += """show_alert"":""" & Convert.ToInt16(odbcReader("show_alert")) & ""","
xmlString += "}"
End While
odbcReader.Close()
Catch ex As Exception
odbcConn.Close()
End Try
odbcConn.Close()
Catch ex As Exception
End Try
'xmlString = xmlString.Trim().Substring(0, xmlString.Length - 1)
'xmlString = "[" & xmlString & "]"
HttpContext.Current.Response.BufferOutput = True
HttpContext.Current.Response.ContentType = "application/x-javascript"
HttpContext.Current.Response.Write(xmlString)
HttpContext.Current.Response.Flush()
End Sub
What is wrong with my code? Why is the "dataSource.read()" function not getting the data from the VB file?
According to this web-site http://net-informations.com/q/mis/500.html the problem is on your server side. Something isn't configured correctly. Double check the connection string you are using to make sure it is connecting to the right server and then check to make sure the server is running and accessible.

Creating a webservice that accepts XML as a string

I have been trying to create a webservice that needs to allow the client to send thru 3 parameters being Username, Password and XML_In all 3 of type string. This then sends the variables to a Stored procedure which processes the data and returns an XML string which is then returned to the client.
The Stored procedure works 100% but I'm getting an error with the XML being sent thru as a string. From reading up most gave the suggestion of adding <httpRuntime requestValidationMode="2.0"/> and <pages validateRequest="false"> to my web.config which works but that would then apply to my entire site which I dont want at all.
The other suggestion was to place it in the #Page part but that does not apply to a web service as it has no user defined layout. Please see my code below and help. I'm still quite a newbie to .Net thus the reason I'm doing 90% of it in SQL.
The error That gets returned is :
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (XML_In="<senddata><settings ...").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.ValidateHttpValueCollection(HttpValueCollection collection, RequestValidationSource requestCollection)
at System.Web.HttpRequest.get_Form()
at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
here's the code:
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Xml
Imports JumpStart.Framework.Database
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://mydomainname.co.za/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class LeadProcessor
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & XML_In.ToString & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
I agree with CodeCaster comment (new projects - WCF or WebApi).
But if you can't change it now, consider use a XMLDocument as parameter, or an XElemento, or directly, do a Base64 transform of the text, in order to avoid that errors.
Code for your service' client:
your_proxy.Lead_Processing(sUserName, sPassWord, Convert.ToBase64String(Encoding.UTF8.GetBytes(sXML))
Then, in your service, do this
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim oData As Byte() = Convert.FromBase64String(XML_In)
Dim sDecodedXML As String = System.Text.Encoding.UTF8.GetString(oData)
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & sDecodedXML & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
Hope it helps
Edit:
Your service with base64.
We're telling that Asmx it's almost a legacy tech. New projects may use WCF tech (I can't teach you WCF in a few lines).
You can put that code into your asmx service. You can use that code in the way I edited my answer.

ASP Syntax Not Working

I'm very new to ASP and am trying to figure out how to use some code I found on a site. The code is here:
http://msdn.microsoft.com/en-us/library/bb387090.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
and is used to convert CSV values into an XML file. I've created an ASP file and copy and pasted the VB script into the file in between <% and %> tags but I get an error when I pull the page up (the page doesn't actually load).
I must be missing some simple syntax? Are those underscores supposed to be at the end of some of the lines? Here is the code that I am referring to:
' Create the text file.
Dim csvString As String = "GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA" & vbCrLf & _
"HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA" & vbCrLf & _
"LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA" & vbCrLf & _
"LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA"
File.WriteAllText("cust.csv", csvString)
' Read into an array of strings.
Dim source As String() = File.ReadAllLines("cust.csv")
Dim cust As XElement = _
<Root>
<%= From strs In source _
Let fields = Split(strs, ",") _
Select _
<Customer CustomerID=<%= fields(0) %>>
<CompanyName><%= fields(1) %></CompanyName>
<ContactName><%= fields(2) %></ContactName>
<ContactTitle><%= fields(3) %></ContactTitle>
<Phone><%= fields(4) %></Phone>
<FullAddress>
<Address><%= fields(5) %></Address>
<City><%= fields(6) %></City>
<Region><%= fields(7) %></Region>
<PostalCode><%= fields(8) %></PostalCode>
<Country><%= fields(9) %></Country>
</FullAddress>
</Customer> _
%>
</Root>
Console.WriteLine(cust)
I wrapped that in those ASP tags but it didn't work. This is copy and pasted directly from that site because I want to get it working before customizing it for my own use. Thanks for your help!
The code you copied is for a console application. You'll need to do some more (little) work to get it to render in a web page.
The sample is written in VB and takes advantage of xml literals support. The code is written that way to distinguish "in line" code and literals (<%= ...%>). If you check the C# version it'll be apparent.
Trivial Example:
Create your aspx page (vb - so you can still do xml literals)
<%# Page Language="VB" AutoEventWireup="false" CodeFile="csvtoxml.aspx.vb" Inherits="csvtoxml" %>
...boiler plate aspx/web forms HTML stuff....
<body>
<form id="form1" runat="server">
<div>
<p>This is where we will output the XML</p>
<textarea runat="server" id="theXML" cols="70" rows="60"></textarea>
</div>
</form>
In code-behind (xml literals):
Imports System.IO
Partial Class csvtoxml
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.theXML.InnerText = Me.MyFunc()
End Sub
Protected Function MyFunc() As String
Dim csvString As String = "GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA" & vbCrLf & _
"HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA" & vbCrLf & _
"LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA" & vbCrLf & _
"LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA"
Dim filePath As String = Path.Combine(MapPath("~/"), "cust.csv") 'Just adding this for debug (write permissions) in VS (local rights to file system)
File.WriteAllText(filePath, csvString) 'Note: as above you can't just write on a server filesystem - ensure proper permissions
' Read into an array of strings.
Dim source As String() = File.ReadAllLines(filePath)
Dim cust As XElement = _
<Root>
<%= From strs In source _
Let fields = Split(strs, ",") _
Select _
<Customer CustomerID=<%= fields(0) %>>
<CompanyName><%= fields(1) %></CompanyName>
<ContactName><%= fields(2) %></ContactName>
<ContactTitle><%= fields(3) %></ContactTitle>
<Phone><%= fields(4) %></Phone>
<FullAddress>
<Address><%= fields(5) %></Address>
<City><%= fields(6) %></City>
<Region><%= fields(7) %></Region>
<PostalCode><%= fields(8) %></PostalCode>
<Country><%= fields(9) %></Country>
</FullAddress>
</Customer> _
%>
</Root>
Return cust.ToString() 'Write XElement out to string
End Function
Result
<Root>
<Customer CustomerID="GREAL">
<CompanyName>Great Lakes Food Market</CompanyName>
<ContactName>Howard Snyder</ContactName>
<ContactTitle>Marketing Manager</ContactTitle>
<Phone>(503) 555-7555</Phone>
<FullAddress>
<Address>2732 Baker Blvd.</Address>
<City>Eugene</City>
<Region>OR</Region>
<PostalCode>97403</PostalCode>
<Country>USA</Country>
</FullAddress>
</Customer>
<Customer CustomerID="HUNGC">
...
</root>

VB.Net and XDocument - Group By

I have the following code which I need to amend to group by offer but I'm not sure how to add in the group by part in this query.
Any ideas?
propertyInfo = myXmlFile.Descendants("offer").Descendants("site") _
.Where(Function(f) _
f.Attributes("code").First.Value = Location.Text) _
.Select(Function(f) New With { _
.LOCATION = f.Attributes("code").First.Value, _
.TITLE = f.Parent.Attributes("title").First.Value, _
.OFFER = f.Parent.Attributes("offerid").First.Value, _
.POPUPDESC = f.Parent.Descendants("short_desc").Value
Example XML
<offers>
<offer title="Offer title" offerid="AS32">
<short_desc><![CDATA[
<div>Your HTML's body <a href='dfgdfgdfgdfg.html'>Offer title</a>
</div>
]]></short_desc>
<site code="CO">
<year_week_start>201344</year_week_start>
<year_week_end>201414</year_week_end>
</site>
<site code="FH">
<year_week_start>201446</year_week_start>
<year_week_end>201450</year_week_end>
</site>
</offer>
</offers>
I think you need to be a little more specific in what you want after you group. It's pretty easy to group, but then you get an enumerable of groups:
propertyInfo = myXmlFile.Descendants("offer").Descendants("site") _
.Where(Function(f) _
f.Attributes("code").First.Value = Location.Text) _
.Select(Function(f) New With { _
.LOCATION = f.Attributes("code").First.Value, _
.TITLE = f.Parent.Attributes("title").First.Value, _
.OFFER = f.Parent.Attributes("offerid").First.Value, _
.POPUPDESC = f.Parent.Descendants("short_desc").Value) _
.GroupBy(Function(f) f.OFFER)

Server Control Error: Unknown server tag with ASP.NET

I am trying to get a custom control working in VB ASP.Net
I've read a few threads but it doesn't seem to help me much.
I have a solution including:
Website project called "SiteCI"
Class Library project called "SiteCI-classes"
The website project has a reference to the library project, and the library DLL are correctly generated inside the bin folder of the website project.
When I create a random class within the website project, I can access to my test control class called MailLink by typing:
SiteCI_classes.Controls.MailLink
It works perfectly, Visual Studio suggests it to me, so the link between the two projects are correctly set.
Please note that I clean/rebuild the project every time to see if it really works or not, so that's not a problem of incorrect DLL build.
In the Web Config file inside system.web -> pages -> controls I have added:
<add assembly="SiteCI-classes" namespace="Controls" tagPrefix="custom" />
But on a ASP.Net page when I add:
<custom:MailLink runat="server" id="test1"></custom:MailLink>
I am getting the Unknown server tag 'custom:MailLink' error.
To check if I did not make a mistake while typing in the web config file I tried to change the SiteCI-classes to SiteCI_classes and I got an error saying that it wasn't able to load the assembly, so I guess that part is OK, and then I tried to change namespace="Controls" in *namespace="SiteCI_classes.Controls"* or namespace="SiteCI-classes.Controls" and it didn't fix the unknown server tag issue.
I don't know what to do... it's supposed to work, isn't it?
Here is the MailLink.vb that is located in a folder called Controls of the Library project. It's a class I picked on a Microsoft page just for testing purpose.
I would be very grateful if anyone could give me a tip on what to check.
Namespace Controls
< _
AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
DefaultProperty("Email"), _
ParseChildren(True, "Text"), _
ToolboxData("<{0}:MailLink runat=""server""> </{0}:MailLink>") _
> _
Public Class MailLink
Inherits WebControl
< _
Bindable(True), _
Category("Appearance"), _
DefaultValue(""), _
Description("The e-mail address.") _
> _
Public Overridable Property Email() As String
Get
Dim s As String = CStr(ViewState("Email"))
If s Is Nothing Then s = String.Empty
Return s
End Get
Set(ByVal value As String)
ViewState("Email") = value
End Set
End Property
< _
Bindable(True), _
Category("Appearance"), _
DefaultValue(""), _
Description("The text to display on the link."), _
Localizable(True), _
PersistenceMode(PersistenceMode.InnerDefaultProperty) _
> _
Public Overridable Property Text() As String
Get
Dim s As String = CStr(ViewState("Text"))
If s Is Nothing Then s = String.Empty
Return s
End Get
Set(ByVal value As String)
ViewState("Text") = value
End Set
End Property
Protected Overrides ReadOnly Property TagKey() _
As HtmlTextWriterTag
Get
Return HtmlTextWriterTag.A
End Get
End Property
Protected Overrides Sub AddAttributesToRender( _
ByVal writer As HtmlTextWriter)
MyBase.AddAttributesToRender(writer)
writer.AddAttribute(HtmlTextWriterAttribute.Href, _
"mailto:" & Email)
End Sub
Protected Overrides Sub RenderContents( _
ByVal writer As HtmlTextWriter)
If (Text = String.Empty) Then
Text = Email
End If
writer.WriteEncodedText(Text)
End Sub
End Class
End Namespace
I found the problem which seem to have ONLY been caused by the dash ("-") in the name of the Project.
The name of the project is still "SiteCI-Classes" BUT the final code of the WebConfig is different:
<add assembly="SiteCIClasses" namespace="SiteCI2KClasses.Controls" tagPrefix="cc1" />
Note the difference between the two. ASP.Net 3.5 will not recognize a dash in the name of a project and seem to remove it: if you try to set it to SiteCI-Classes it will end up with an error like assembly not found.

Resources