how to refund partial amount in paypal adaptive payment - paypal

I am working on paypal adaptive payment & i need to refund with API , i am able to refund full amount but i also need to refund partial amount
reference url which i am using:https://developer.paypal.com/docs/classic/api/adaptive-payments/Refund_API_Operation/
eg- total amount made at time of payment is 100 & i need to refund only 50.00
i try following code/api parameters
-H "X-PAYPAL-SECURITY-PASSWORD: api_password"
-H "X-PAYPAL-SECURITY-SIGNATURE: api_signature"
-H "X-PAYPAL-REQUEST-DATA-FORMAT: NV"
-H "X-PAYPAL-RESPONSE-DATA-FORMAT: NV"
-H "X-PAYPAL-APPLICATION-ID: your_app_id " https://svcs.sandbox.paypal.com/AdaptivePayments/Refund -d
"requestEnvelope.errorLanguage=en_US
&transactionId=AP-95V43510SV018561T0"
& try these inputs to set refund amount
&amount = 50.0
&
&amount = XS:50.0
but none of these working just refund the full amount

A little correction on your request payload, "AP-95V43510SV018561T0" is a pay-key value (obtained from the Pay api response), the name pair should be
payKey = AP-95V43510SV018561T0
A partial refund payload with minimum parameters would be like this, say if you have just made a $100 transaction and is about to do a $50 refund:
requestEnvelope.errorLanguage = en_US
detailLevel = ReturnAll
payKey = AP-95V43510SV018561T0
receiverList.receiver(0).email = receiver#paypal.com
receiverList.receiver(0).amount = 50.00
currencyCode = USD
And the API response:
responseEnvelope.timestamp=2015-08-06T07:39:08.861-07:00
responseEnvelope.ack=Success
responseEnvelope.correlationId=2e7007b68f85b
responseEnvelope.build=17603431
currencyCode=USD
refundInfoList.refundInfo(0).receiver.amount=50.00
refundInfoList.refundInfo(0).receiver.email=receiver#paypal.com
refundInfoList.refundInfo(0).refundStatus=REFUNDED
refundInfoList.refundInfo(0).refundNetAmount=48.05
refundInfoList.refundInfo(0).refundFeeAmount=1.95
refundInfoList.refundInfo(0).refundGrossAmount=50.00
refundInfoList.refundInfo(0).totalOfAllRefunds=50.00
refundInfoList.refundInfo(0).refundHasBecomeFull=false
refundInfoList.refundInfo(0).encryptedRefundTransactionId=96U15993F0258151X
refundInfoList.refundInfo(0).refundTransactionStatus=COMPLETED

Related

IMAP UID FETCH Command - Return two sequence numbers by one UID request

In very rare cases server returns a second sequence number.
Example log:
C: A0020 UID FETCH 304244 (BODY[HEADER.FIELDS (SUBJECT FROM TO CC REPLYTO MESSAGEID DATE SIZE REFERENCES)] UID FLAGS INTERNALDATE RFC822.SIZE ENVELOPE RFC822.HEADER)
S: * 9 FETCH (BODY[HEADER.FIELDS (SUBJECT FROM TO CC REPLYTO MESSAGEID DATE SIZE REFERENCES)] {262}
S: Date: Thu, 29 Dec 2022 00:00:00 +0000\r\nFrom: Name <email#domain.com>\r\nSubject: Subject\r\nTo: <email#domain.com>\r\nCC:\r\n\r\n
S: UID 304244 FLAGS (\\Seen) INTERNALDATE \"29-Dec-2022 01:00:00 +0100\" RFC822.SIZE 226713 ENVELOPE (ENVELOPE DATA) RFC822.HEADER {7754}
S: MIME-Version: 1.0\r\nReceived: from ... email data
S: FLAGS (\\Seen))
S: * 11 FETCH (FLAGS (\\Seen \\Deleted))
S: A0020 OK FETCH completed.
Client request UID FETCH by UID "304244". The server responded that the email is "9" sequence number. At the end before "OK FETCH completed." the server returns another sequence number "11" with information about the flags.
I tried to find in https://www.rfc-editor.org/rfc/rfc3501#section-6.4.5 , https://www.rfc-editor.org/rfc/rfc3501#section-6.4.8 and elsewhere some information on such responses from the server, but found nothing. Does anyone know why the server in the "UID FETCH" command response returns another sequence number with information about the flags and what it can mean?
UPDATE:
Today I have got this case:
C: A0051 UID FETCH 305421 (BODY[HEADER.FIELDS (SUBJECT FROM TO CC REPLYTO MESSAGEID DATE SIZE REFERENCES)] UID FLAGS INTERNALDATE RFC822.SIZE ENVELOPE RFC822.HEADER)
S: * 40 FETCH (BODY[HEADER.FIELDS (SUBJECT FROM TO CC REPLYTO MESSAGEID DATE SIZE REFERENCES)] {209}
S: To: email#domain.com\r\nSubject: Subject\r\nDate: Tue, 03 Jan 2023 00:07:15 +0200\r\nFrom: <email#domain.com>\r\n\r\n
S: UID 305421 FLAGS (\\Seen) INTERNALDATE \"02-Jan-2023 23:07:20 +0100\" RFC822.SIZE 158940 ENVELOPE (ENVELOPE DATA) RFC822.HEADER {8278}
S: MIME-Version: 1.0\r\nReceived: from ... email data
S: FLAGS (\\Seen))
S: * 3 FETCH (FLAGS (\\Seen \\Deleted))
S: * 4 FETCH (FLAGS (\\Seen \\Deleted))
S: * 5 FETCH (FLAGS (\\Seen \\Deleted))
S: * 6 FETCH (FLAGS (\\Seen \\Deleted))
S: * 7 FETCH (FLAGS (\\Seen \\Deleted))
S: * 8 FETCH (FLAGS (\\Seen \\Deleted))
S: A0051 OK FETCH completed.
So, if I understood the answer below correctly. While the server run "UID FETCH" the email from the server, someone in another session change this and other emails. In begin of "UID FETCH" the sequence number was "40". But during command execution the sequence number changed several times: 40 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8. That is why the server sends me these "* number FETCH (FLAGS ...)" lines. Did I understand correctly?
What you want is described in IMAP-speak as: Your FETCH command directs the server to send an untagged FETCH command before the server concludes processing the FETCH command, and return a tagged response with the result (usually just OK).
Note the verb directs. Other things can also direct the server to send untagged responses, even at the same time as you direct it. For example, when new mail arrives, that directs the server to send an untagged EXISTS response as soon as possible.
Your example is a bit strange, but the server is allowed to do it.
The simplest way to deal with it is to maintain a cache of messages clientside, update the relevant message in the cache whenever you get a FETCH response, and when you receive a tagged OK, you can trust that the information you wanted is now present in the cache.
Make sure to test what happens if a message is deleted just as you request it. The server's untagged responses should cause your cache to contain something like 'this message has been deleted'.

Write mysql custom query in query builder of grafana

I made a time-series graph screenshot attached and the generated query is
SELECT
UNIX_TIMESTAMP(date_of_sign_up) DIV 600 * 600 AS "time",
status AS "borrower_status",
count(id) AS "Number Of Borrowers"
FROM borrowers
WHERE
date_of_sign_up BETWEEN FROM_UNIXTIME(1631158800) AND FROM_UNIXTIME(1643881661) AND
status IN ('APPROVED','INACTIVE','BASIC') AND
client_id = 130454654
GROUP BY 1, status
ORDER BY UNIX_TIMESTAMP(date_of_sign_up) DIV 600 * 600
Now i want to pass from and to from url in mysql query builder, below is the query i tried to write but it did not work
SELECT
$__timeGroupAlias(date_of_sign_up,10m),
status AS "borrower_status",
count(id) AS "Number Of Borrowers"
FROM borrowers
WHERE
date_of_signup between $from AND $to AND
status IN (${BorrowerStatus}) AND
client_id = [[tenant]]
GROUP BY 1, status
ORDER BY $__timeGroup(date_of_sign_up,10m)
What is the correct way of passing &from and &to from URL params in MySQL query builder date_of_signup between
date_of_signup between $__timeFrom() AND $__timeTo()

How to fetch doctype eg: address or tax rule

I want to fetch the doctype. How do I do this? I want to add a separate column which will give doctype such as sales order, purchase order etc. The first line gives me error what query should be fired. Please help I am new to ERP Next.
SELECT
AD.ref_doctype AS “Doctype:Link/User:120”,
AD.name AS “Doc#:Link/Doctype:120”,
AD.owner AS “Created By:Link/User:120”,
AD.modified AS “Modified On:Date:120”
FROM tabAddress AS AD
WHERE
DATEDIFF(now(),AD.modified) BETWEEN 1 AND 30
UNION ALL
SELECT
TR.name AS “Doc#:Link/Doctype:120”,
TR.owner AS “Created By:Link/User:120”,
TR.modified AS “Modified On:Date:120”
FROM tabTax Rule AS TR
WHERE
DATEDIFF(now(),TR.modified) BETWEEN 1 AND 30
UNION ALL
SELECT
IT.name AS “Doc#:Link/Doctype:120”,
IT.owner AS “Created By:Link/User:120”,
IT.modified AS “Modified On:Date:120”
FROM tabItem AS IT
WHERE
DATEDIFF(now(),IT.modified) BETWEEN 1 AND 30
It isn't completely clear to me what you mean by docType field.
Are you wanting a result like this?
Doctype:Link/User:120|Doc#:Link/Doctype:120|Created By:Link/User:120|Modified On:Date:120|
---------------------|---------------------|------------------------|--------------------|
Email Account |Jobs |Administrator | 2019-12-04 06:07:55|
Email Account |Notifications |Administrator | 2019-12-01 05:25:53|
Email Account |Replies |Administrator | 2019-12-01 05:25:53|
Email Account |Sales |Administrator | 2019-12-04 06:07:55|
Email Account |Support |Administrator | 2019-12-04 06:07:55|
Here's the select :
set #docType = "Email Account";
SELECT
#tabDocType AS `Doctype:Link/User:120`,
AD.name AS `Doc#:Link/Doctype:120`,
AD.owner AS `Created By:Link/User:120`,
AD.modified AS `Modified On:Date:120`
FROM `tabEmail Account` AS AD
Note the backticks on the field aliases! All these have different meanings in SQL:
"
'
`
The last one, backtick, is used to refer to database entities. You were trying to use “Doctype:Link/User:120” with double quotes, which declare plain text. Using backtick converts the alias into a db entity which can be referred to from elsewhere.
MariaDb doesn't allow the use of variables as table names directly, but you can do it using prepared statements, like this:
set #docType = "Email Account";
set #tabDocType = CONCAT('tab', #docType);
SET #sql_text = concat('
SELECT
"', #docType, '" AS `Doctype:Link/User:120`
, AD.name AS `Doc#:Link/Doctype:120`
, AD.owner AS `Created By:Link/User:120`
, AD.modified AS `Modified On:Date:120`
FROM `', #tabDocType, '` as AD;
');
PREPARE stmt FROM #sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
The table name is now also specified by a variable, created from concatenation of 'tab' with the docType declared before.
You get the same result as above but -- you avoid accidentally changing the table name in one place but not in the other when editing some time in the future.
to fetch doctype name you have to give the linked doctype name, For example,
select
IT.name as "IT No:Link/IT:120"

Is there pagination for transaction search?

I am trying to execute the TransactionSearchReq method using the PayPal SOAP API and i get the following warning:
ShortMessage: Search warning
LongMessage: The number of results were truncated. Please change your search parameters if you wish to see all your results.
ErrorCode: 11002
SeverityCode: Warning
It also says in the docs that "The maximum number of transactions that can be returned from a TransactionSearch API call is 100."
(https://developer.paypal.com/docs/classic/api/merchant/TransactionSearch_API_Operation_SOAP/)
Is there some way to paginate results so that I can get more than 100 results from multiple queries?
Here's one way you can do it in Rails. This assumes you want to search from a specific point in time until now, but you could change the end_date to specify an end date. Note that I've added the 'paypal-sdk-merchant' gem to my gemfile (see https://github.com/paypal/merchant-sdk-ruby) and followed the instructions to setup my authentication.
The two things you'll want to edit below are the start_date method (to set your own start date) and the do_something(x) method which will be whatever you want to do to each of the individual orders within your date range.
module PaypalTxnSearch
def check_for_updated_orders
begin
#paypal_order_list = get_paypal_orders_in_range(start_date, end_date)
#paypal_order_list.PaymentTransactions.each do |x|
# This is where you can call a method to process each transaction
do_something(x)
end
# TransactionSearch returns up to 100 of the most recent items.
end while txn_search_result_needs_pagination?
end
def get_paypal_orders_in_range(start_date, end_date)
#api = PayPal::SDK::Merchant::API.new
# Build Transaction Search request object
# https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/TransactionSearch_API_Operation_NVP/
#transaction_search = #api.build_transaction_search(
StartDate: start_date,
EndDate: end_date
)
# Make API call & get response
#response = #api.transaction_search(#transaction_search)
# Access Response
return_response_or_errors(#response)
end
def start_date
# In this example we look back 6 months, but you can change it
Date.today.advance(months: -6)
end
def end_date
if defined?(#paypal_order_list)
#paypal_order_list.PaymentTransactions.last.Timestamp
else
DateTime.now
end
end
def txn_search_result_needs_pagination?
##paypal_order_list.Ack == 'SuccessWithWarning' &&
##paypal_order_list.Errors.count == 1 &&
##paypal_order_list.Errors[0].ErrorCode == '11002'
end
def return_response_or_errors(response)
if response.success?
response
else
response.Errors
end
end
end

Classic ASP paypal integration with express checkout

I have a fully working Classic ASP paypal integration (yay!)
I set up my variables and call the express checkout like this:
paymentAmount = RS_OrderHeader01("PaymentAmount")
currencyCodeType = "GBP"
paymentType = "Sale"
solutionType = "Mark"
OrderDescription = "My order description"
returnURL = "http://www.myurl.co.uk/transactioncomplete.asp"
cancelURL = "http://www.myurl.co.uk/transactioncancelled.asp"
Set resArray = CallShortcutExpressCheckout (paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL)
That all works fine apart from the fact that there is no description being passed across. I would also like to add individual items from my basket to the final transaction in paypal.
The integration I am using is from a download from the Paypal site that hinges around this 'include' file:
<%
' ===================================================
' PayPal API Include file
'
' Defines all the global variables and the wrapper functions
'-----------------------------------------------------------
Dim gv_APIEndpoint
Dim gv_APIUserName
Dim gv_APIPassword
Dim gv_APISignature
Dim gv_Version
Dim gv_BNCode
Dim gv_ProxyServer
Dim gv_ProxyServerPort
Dim gv_Proxy
'----------------------------------------------------------------------------------
' Authentication Credentials for making the call to the server
'----------------------------------------------------------------------------------
SandboxFlag = true
'------------------------------------
' PayPal API Credentials
' Replace <API_USERNAME> with your API Username
' Replace <API_PASSWORD> with your API Password
' Replace <API_SIGNATURE> with your Signature
'------------------------------------
gv_APIUserName = "myusername"
gv_APIPassword = "1404738820"
gv_APISignature = "AFcWxV21CRCpSSRl31AuDrEW4a9MiULwvS8UDzCPvE28G8"
'-----------------------------------------------------
' The BN Code only applicable for partners
'----------------------------------------------------
gv_BNCode = "PP-ECWizard"
'----------------------------------------------------------------------
' Define the PayPal URLs.
' This is the URL that the buyer is first sent to do authorize payment with their paypal account
' change the URL depending if you are testing on the sandbox
' or going to the live PayPal site
'
' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token=
'------------------------------------------------------------------------
if SandboxFlag = true Then
gv_APIEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="
Else
gv_APIEndpoint = "https://api-3t.paypal.com/nvp"
PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="
End If
gv_Version = "93"
'WinObjHttp Request proxy settings.
gv_ProxyServer = "127.0.0.1"
gv_ProxyServerPort = "808"
gv_Proxy = 2 'setting for proxy activation
gv_UseProxy = False
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
' Inputs:
' paymentAmount: Total value of the shopping cart
' currencyCodeType: Currency code value the PayPal API
' paymentType: PaymentType has to be one of the following values: Sale or Order or Authorization
' returnURL: The page where buyers return to after they are done with the payment review on PayPal
' cancelURL: The page where buyers return to when they cancel the payment review on PayPal
' Returns:
' The NVP Collection object of the SetExpressCheckout call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function CallShortcutExpressCheckout( paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL)
'------------------------------------------------------------------------------------------------------------------------------------
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
'------------------------------------------------------------------------------------------------------------------------------------
nvpstr = "&" & Server.URLEncode("PAYMENTREQUEST_0_AMT") & "=" & Server.URLEncode(paymentAmount) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & _
"&" & Server.URLEncode("RETURNURL") & "=" & Server.URLEncode(returnURL) & _
"&" & Server.URLEncode("CANCELURL") & "=" & Server.URLEncode(cancelURL) & _
"&" & server.UrlEncode("PAYMENTREQUEST_0_CURRENCYCODE") & "=" & Server.URLEncode(currencyCodeType)
SESSION("currencyCodeType") = currencyCodeType
SESSION("PaymentType") = paymentType
'---------------------------------------------------------------------------------------------------------------
' Make the API call to PayPal
' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
' If an error occured, show the resulting errors
'---------------------------------------------------------------------------------------------------------------
Set resArray = hash_call("SetExpressCheckout",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("token") = resArray("TOKEN")
End If
set CallShortcutExpressCheckout = resArray
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
' Inputs:
' paymentAmount: Total value of the shopping cart
' currencyCodeType: Currency code value the PayPal API
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' returnURL: the page where buyers return to after they are done with the payment review on PayPal
' cancelURL: the page where buyers return to when they cancel the payment review on PayPal
' shipToName: the Ship to name entered on the merchant's site
' shipToStreet: the Ship to Street entered on the merchant's site
' shipToCity: the Ship to City entered on the merchant's site
' shipToState: the Ship to State entered on the merchant's site
' shipToCountryCode: the Code for Ship to Country entered on the merchant's site
' shipToZip: the Ship to ZipCode entered on the merchant's site
' shipToStreet2: the Ship to Street2 entered on the merchant's site
' phoneNum: the phoneNum entered on the merchant's site
' Returns:
' The NVP Collection object of the SetExpressCheckout call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function CallMarkExpressCheckout(paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL, shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum)
'------------------------------------------------------------------------------------------------------------------------------------
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
'------------------------------------------------------------------------------------------------------------------------------------
nvpstr = "&" & Server.URLEncode("PAYMENTREQUEST_0_AMT") & "=" & Server.URLEncode(paymentAmount) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & _
"&" & Server.URLEncode("RETURNURL") & "=" & Server.URLEncode(returnURL) & _
"&" & Server.URLEncode("CANCELURL") & "=" & Server.URLEncode(cancelURL) & _
"&" & Server.URLEncode("ADDROVERRIDE") & "=1" & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTONAME") & "=" & Server.URLEncode(shipToName) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOSTREET") & "=" & Server.URLEncode(shipToStreet) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOSTREET2") & "=" & Server.URLEncode(shipToStreet2) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOCITY") & "=" & Server.URLEncode(shipToCity) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOSTATE") & "=" & Server.URLEncode(shipToState) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE") & "=" & Server.URLEncode(shipToCountryCode) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOZIP") & "=" & Server.URLEncode(shipToZip) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_SHIPTOPHONENUM") & "=" & Server.URLEncode(phoneNum) & _
"&"& server.UrlEncode("PAYMENTREQUEST_0_CURRENCYCODE") & "=" & Server.URLEncode(currencyCodeType)
SESSION("currencyCodeType") = currencyCodeType
SESSION("PaymentType") = paymentType
'---------------------------------------------------------------------------
' Make the API call to PayPal to set the Express Checkout token
' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
' If an error occured, show the resulting errors
'---------------------------------------------------------------------------
Set resArray = hash_call("SetExpressCheckout",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("token") = resArray("TOKEN")
End If
set CallMarkExpressCheckout = resArray
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API and makes the API call.
'
' Inputs:
' token: The token value returned by the SetExpressCheckout call
' Returns:
' The NVP Collection object of the GetExpressCheckoutDetails Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function GetShippingDetails( token )
'---------------------------------------------------------------------------
' At this point, the buyer has completed authorizing the payment
' at PayPal. The function will call PayPal to obtain the details
' of the authorization, incuding any shipping information of the
' buyer. Remember, the authorization is not a completed transaction
' at this state - the buyer still needs an additional step to finalize
' the transaction
'---------------------------------------------------------------------------
'---------------------------------------------------------------------------
' Build a second API request to PayPal, using the token as the
' ID to get the details on the payment authorization
'---------------------------------------------------------------------------
nvpstr="&TOKEN=" & token
'---------------------------------------------------------------------------
' Make the API call and store the results in an array.
' If the call was a success, show the authorization details, and provide
' an action to complete the payment.
' If failed, show the error
'---------------------------------------------------------------------------
set resArray = hash_call("GetExpressCheckoutDetails",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("PAYERID") = resArray("PAYERID")
End If
set GetShippingDetails = resArray
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API and makes the call.
'
' Inputs:
' finalPaymentAmount: The final total of the shopping cart including Shipping, Handling and other fees
' Returns:
' The NVP Collection object of the DoExpressCheckoutPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function ConfirmPayment( finalPaymentAmount )
'------------------------------------------------------------------------------------------------------------------------------------
'---- Use the values stored in the session from the previous SetEC call
'------------------------------------------------------------------------------------------------------------------------------------
token = SESSION("token")
currCodeType = SESSION("currencyCodeType")
paymentType = SESSION("PaymentType")
payerID = SESSION("PayerID")
nvpstr = "&" & Server.URLEncode("TOKEN") & "=" & Server.URLEncode(token) & "&" &_
Server.URLEncode("PAYERID")&"=" &Server.URLEncode(payerID) & "&" &_
Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & "&" &_
Server.URLEncode("PAYMENTREQUEST_0_AMT") &"=" & Server.URLEncode(finalPaymentAmount) & "&" &_
Server.URLEncode("PAYMENTREQUEST_0_CURRENCYCODE")& "=" &Server.URLEncode(currCodeType)
'-------------------------------------------------------------------------------------------
' Make the call to PayPal to finalize payment
' If an error occured, show the resulting errors
'-------------------------------------------------------------------------------------------
set ConfirmPayment = hash_call("DoExpressCheckoutPayment",nvpstr)
End Function
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the DoDirectPayment API and makes the call.
'
' Inputs:
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' paymentAmount: Total value of the shopping cart
' creditCardType Credit card type has to one of the following values: Visa or MasterCard or Discover or Amex or Switch or Solo
' creditCardNumber Credit card number
' expDate Credit expiration date
' cvv2 CVV2
' firstName Customer's First Name
' lastName Customer's Last Name
' street Customer's Street Address
' city Customer's City
' state Customer's State
' zip Customer's Zip
' countryCode Customer's Country represented as a PayPal CountryCode
' currencyCode Customer's Currency represented as a PayPal CurrencyCode
'
' Returns:
' The NVP Collection object of the DoDirectPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
Function DirectPayment( paymentType, paymentAmount, creditCardType, creditCardNumber, expDate, cvv2, firstName, lastName, street, city, state, zip, countryCode, currencyCode )
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
nvpstr = "&PAYMENTACTION=" & paymentType & _
"&AMT=" & paymentAmount &_
"&CREDITCARDTYPE=" & creditCardType &_
"&ACCT=" & creditCardNumber & _
"&EXPDATE=" & expDate &_
"&CVV2=" & cvv2 &_
"&FIRSTNAME=" & firstName &_
"&LASTNAME=" & lastName &_
"&STREET=" & street &_
"&CITY=" & city &_
"&STATE=" & state &_
"&ZIP=" & zip &_
"&COUNTRYCODE=" & countryCode &_
"&CURRENCYCODE=" & currencyCode
nvpstr = URLEncode(nvpstr)
'-------------------------------------------------------------------------------------------
' Make the call to PayPal to finalize payment
' If an error occured, show the resulting errors
'-------------------------------------------------------------------------------------------
set DirectPayment = hash_call("DoDirectPayment",nvpstr)
End Function
'----------------------------------------------------------------------------------
' Purpose: Make the API call to PayPal, using API signature.
' Inputs:
' Method name to be called & NVP string to be sent with the post method
' Returns:
' NVP Collection object of Call Response.
'----------------------------------------------------------------------------------
Function hash_call ( methodName,nvpStr )
Set objHttp = Server.CreateObject("WinHTTP.WinHTTPRequest.5.1")
nvpStrComplete = "METHOD=" & Server.URLEncode(methodName) & "&VERSION=" & Server.URLEncode(gv_Version) & "&USER=" & Server.URLEncode(gv_APIUserName) & "&PWD=" & Server.URLEncode(gv_APIPassword) & "&SIGNATURE=" & Server.URLEncode(gv_APISignature) & nvpStr
nvpStrComplete = nvpStrComplete & "&BUTTONSOURCE=" & Server.URLEncode( gv_BNCode )
Set SESSION("nvpReqArray")= deformatNVP( nvpStrComplete )
objHttp.open "POST", gv_APIEndpoint, False
WinHttpRequestOption_SslErrorIgnoreFlags=4
objHttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = &H3300
If gv_UseProxy Then
'Proxy Call
objHttp.SetProxy gv_Proxy, gv_ProxyServer& ":" &gv_ProxyServerPort
End If
objHttp.Send nvpStrComplete
Set nvpResponseCollection =deformatNVP(objHttp.responseText)
Set hash_call = nvpResponseCollection
Set objHttp = Nothing
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"hash_call")
SESSION("nvpReqArray") = Null
Else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: Formats the error Messages.
' Inputs:
'
' Returns:
' Formatted Error string
'----------------------------------------------------------------------------------
Function ErrorFormatter ( errDesc, errNumber, errSource, errlocation )
ErrorFormatter ="<font color=red>" & _
"<TABLE align = left>" &_
"<TR>" &"<u>Error Occured!!!</u>" & "</TR>" &_
"<TR>" &"<TD>Error Description :</TD>" &"<TD>"&errDesc& "</TD>"& "</TR>" &_
"<TR>" &"<TD>Error number :</TD>" &"<TD>"&errNumber& "</TD>"& "</TR>" &_
"<TR>" &"<TD>Error Source :</TD>" &"<TD>"&errSource& "</TD>"& "</TR>" &_
"<TR>" &"<TD>Error Location :</TD>" &"<TD>"&errlocation& "</TD>"& "</TR>" &_
"</TABLE>" &_
"</font>"
End Function
'----------------------------------------------------------------------------------
' Purpose: Convert nvp string to Collection object.
' Inputs:
' NVP string.
' Returns:
' NVP Collection object created from deserializing the NVP string.
'----------------------------------------------------------------------------------
Function deformatNVP ( nvpstr )
On Error Resume Next
Dim AndSplitedArray,EqualtoSplitedArray,Index1,Index2,NextIndex
Set NvpCollection = Server.CreateObject("Scripting.Dictionary")
AndSplitedArray = Split(nvpstr, "&", -1, 1)
NextIndex=0
For Index1 = 0 To UBound(AndSplitedArray)
EqualtoSplitedArray=Split(AndSplitedArray(Index1), "=", -1, 1)
For Index2 = 0 To UBound(EqualtoSplitedArray)
NextIndex=Index2+1
NvpCollection.Add URLDecode(EqualtoSplitedArray(Index2)),URLDecode(EqualtoSplitedArray(NextIndex))
Index2=Index2+1
Next
Next
Set deformatNVP = NvpCollection
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"deformatNVP")
else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: URL Encodes a string
' Inputs:
' String to be url encoded.
' Returns:
' Url Encoded string.
'----------------------------------------------------------------------------------
Function URLEncode(str)
On Error Resume Next
Dim AndSplitedArray,EqualtoSplitedArray,Index1,Index2,UrlEncodeString,NvpUrlEncodeString
AndSplitedArray = Split(nvpstr, "&", -1, 1)
UrlEncodeString=""
NvpUrlEncodeString=""
For Index1 = 0 To UBound(AndSplitedArray)
EqualtoSplitedArray=Split(AndSplitedArray(Index1), "=", -1, 1)
For Index2 = 0 To UBound(EqualtoSplitedArray)
If Index2 = 0 then
UrlEncodeString=UrlEncodeString & Server.URLEncode(EqualtoSplitedArray(Index2))
Else
UrlEncodeString=UrlEncodeString &"="& Server.URLEncode(EqualtoSplitedArray(Index2))
End if
Next
If Index1 = 0 then
NvpUrlEncodeString= NvpUrlEncodeString & UrlEncodeString
Else
NvpUrlEncodeString= NvpUrlEncodeString &"&"&UrlEncodeString
End if
UrlEncodeString=""
Next
URLEncode = NvpUrlEncodeString
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"URLEncode")
else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: Decodes a URL Encoded string
' Inputs:
' A URL encoded string
' Returns:
' Decoded string.
'----------------------------------------------------------------------------------
Function URLDecode(str)
On Error Resume Next
str = Replace(str, "+", " ")
For i = 1 To Len(str)
sT = Mid(str, i, 1)
If sT = "%" Then
If i+2 < Len(str) Then
sR = sR & _
Chr(CLng("&H" & Mid(str, i+1, 2)))
i = i+2
End If
Else
sR = sR & sT
End If
Next
URLDecode = sR
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"URLDecode")
else
SESSION("Message") = Null
End If
End Function
'----------------------------------------------------------------------------------
' Purpose: It's Workaround Method for Response.Redirect
' It will redirect the page to the specified url without urlencoding
' Inputs:
' Url to redirect the page
'----------------------------------------------------------------------------------
Function ReDirectURL( token )
On Error Resume Next
payPalURL = PAYPAL_URL & token & "&useraction=commit"
response.clear
response.status="302 Object moved"
response.AddHeader "location", payPalURL
If Err.Number <> 0 Then
SESSION("Message") = ErrorFormatter(Err.Description,Err.Number,Err.Source,"ReDirectURL")
else
SESSION("Message") = Null
End If
End Function
%>
As I have a fully working implementation I am reluctant to embrace a different solution (and go through a whole load more development).
I have a sneaking suspicion that the 'CallShortcutExpressCheckout' is nothing more that a glorified call to SetExpressCheckout with some very specific parameters set and that it need modification or replacing with a direct call to SetExressCheckout?
Has anyone got some sample classic ASP code?
c
I think you can add to the nvpstr more fields.
You can add also a field like "L_PAYMENTREQUEST_0_NUMBER0" to indentify your product/service id/code the user still paying for. (just a suggestion)
I've rebuild one function, but need to be tested if is working right.
Anyway this is an idea:
Function CallShortcutExpressCheckout( title, description, paymentAmount, currencyCodeType, paymentType, returnURL, cancelURL)
'------------------------------------------------------------------------------------------------------------------------------------
' Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
'------------------------------------------------------------------------------------------------------------------------------------
nvpstr = "&" & Server.URLEncode("L_PAYMENTREQUEST_0_NAME0") & "=" & Server.URLEncode(title) & _
"&" & Server.URLEncode("L_PAYMENTREQUEST_0_DESC0") & "=" & Server.URLEncode(description) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_AMT") & "=" & Server.URLEncode(paymentAmount) & _
"&" & Server.URLEncode("PAYMENTREQUEST_0_PAYMENTACTION")&"=" & Server.URLEncode(paymentType) & _
"&" & Server.URLEncode("RETURNURL") & "=" & Server.URLEncode(returnURL) & _
"&" & Server.URLEncode("CANCELURL") & "=" & Server.URLEncode(cancelURL) & _
"&" & server.UrlEncode("PAYMENTREQUEST_0_CURRENCYCODE") & "=" & Server.URLEncode(currencyCodeType)
SESSION("currencyCodeType") = currencyCodeType
SESSION("PaymentType") = paymentType
'---------------------------------------------------------------------------------------------------------------
' Make the API call to PayPal
' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
' If an error occured, show the resulting errors
'---------------------------------------------------------------------------------------------------------------
Set resArray = hash_call("SetExpressCheckout",nvpstr)
ack = UCase(resArray("ACK"))
If ack="SUCCESS" Then
' Save the token parameter in the Session
SESSION("token") = resArray("TOKEN")
End If
set CallShortcutExpressCheckout = resArray
End Function