I need to refund payment to a customer on behalf of a third party. I have studied permission APIs how to get access token and verification code to use it in authentication API to generate signature and timestamp. But after this i am still confused as to how to use this in Refund API. Currently this is my refund paypal code
CallerServices caller = new CallerServices();
APIProfile profile = ProfileFactory.createSignatureAPIProfile();
if(Configuration.getProperty("PaypalEnvironment").equals("sandbox"))
{
profile.setAPIUsername(Configuration.getProperty("PaypalAPIUsername"));
profile.setAPIPassword(Configuration.getProperty("PaypalAPIPassword"));
profile.setSignature(Configuration.getProperty("PaypalSignature"));
profile.setEnvironment(Configuration.getProperty("PaypalEnvironment"));
caller.setAPIProfile(profile);
}
RefundTransactionRequestType pprequest = new RefundTransactionRequestType();
if ((amount != null && amount.length() > 0)
&& (refundType.equals("Partial"))) {
BasicAmountType amtType = new BasicAmountType();
amtType.set_value(amount);
amtType.setCurrencyID(CurrencyCodeType.fromString(currencyCode));
pprequest.setAmount(amtType);
}
pprequest.setVersion("63.0");
pprequest.setTransactionID(transactionId);
pprequest.setMemo(note);
pprequest.setRefundType(RefundType.fromString(refundType));
RefundTransactionResponseType ppresponse = (RefundTransactionResponseType) caller
.call("RefundTransaction", pprequest);
In this code how do i embed the signature?
For refund it is simple. Once you get the request token and verification code that's it. You don't need to pass this to refund API. All you have to above is just add this line
profile.setSubject(emailid);
and it then it gets refunded.
Related
I am having a difficult time finding halfway descent documentation or examples on how to send money to another Paypal account.
I have installed the Nuget package PaypalSDK version 1.0.4. I have read the documentation at https://developer.paypal.com/home. I have browsed and tried to implement the sample code at https://github.com/paypal/Checkout-NET-SDK.
The problem I am having is that I am having is that I am not seeing notifications of payments sent or received in my sandbox account. I can successfully execute a checkout with the Javascript button in my shopping cart view. But eventually I want to add the capability to send money from my Paypal business account to another Paypal business account, without the other Paypal Business Account owner having to be logged in to my website.
Does the money recipient have to authorize the money I send, or should it just get deposited into their account once I send it?
Here is my code:
namespace MyShoppingCart.Helpers.Paypal
{
public class CaptureOrderSample
{
static string PayPalClientID = Startup.StaticConfig.GetValue<string>("Paypal:ClientID");
static string PayPalClientSecret = Startup.StaticConfig.GetValue<string>("Paypal:ClientSecret");
public static HttpClient client()
{
// Creating a sandbox environment
PayPalEnvironment environment = new SandboxEnvironment(PayPalClientID, PayPalClientSecret);
// Creating a client for the environment
PayPalHttpClient client = new PayPalHttpClient(environment);
return client;
}
public async static Task<HttpResponse> createOrder(string Email)
{
HttpResponse response;
// Construct a request object and set desired parameters
// Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
var order = new OrderRequest()
{
CheckoutPaymentIntent = "CAPTURE",
PurchaseUnits = new List<PurchaseUnitRequest>()
{
new PurchaseUnitRequest()
{
AmountWithBreakdown = new AmountWithBreakdown()
{
CurrencyCode = "USD",
Value = "100.00"
},
Payee = new Payee
{
Email = Email // "payee#email.com"
}
}
}
//,
//ApplicationContext = new ApplicationContext()
//{
// ReturnUrl = "https://www.example.com",
// CancelUrl = "https://www.example.com"
//}
};
// Call API with your client and get a response for your call
var request = new OrdersCreateRequest();
request.Prefer("return=representation");
request.RequestBody(order);
response = await client().Execute(request);
var statusCode = response.StatusCode;
Order result = response.Result<Order>();
Debug.WriteLine($"Status: {result.Status}");
Debug.WriteLine($"Order Id: {result.Id}");
Debug.WriteLine($"Intent: {result.CheckoutPaymentIntent}");
Debug.WriteLine("Links:");
foreach (LinkDescription link in result.Links)
{
Debug.WriteLine($"\t{link.Rel}: {link.Href}\tCall Type: { link.Method}");
}
return response;
}
}
}
And this is currently called from my Orders controller when an order is completed. This is just for testing purposes.
[Authorize]
public async Task<IActionResult> CompleteOrder()
{
var items = _shoppingCart.GetShoppingCartItems();
Models.Order order = await _ordersService.StoreOrderAsync(items);
PrepareSellerEmail(items, order, "You Have a New Order!");
PrepareBuyerEmail(items, order, "Thank You for Your Order!");
await _shoppingCart.ClearShoppingCartAsync(_serviceProvider);
DeleteCartIDCookie();
//OrderRequest request = Helpers.CreateOrderSample.BuildRequestBody("USD", "100.00", "sb-r43z1e9186231#business.example.com");
//var client = Helpers.Paypal.CaptureOrderSample.client();
var result = Helpers.Paypal.CaptureOrderSample.createOrder("sb-r43z1e9186231#business.example.com");
//var response = await PayPalClient.client().execute.(request);
return View("OrderCompleted");
}
The output of the result is:
Status: CREATED
Order Id: 51577255GE4475222
Intent: CAPTURE
Links:
self: https://api.sandbox.paypal.com/v2/checkout/orders/51577255GE4475222 Call Type: GET
approve: https://www.sandbox.paypal.com/checkoutnow?token=51577255GE4475222 Call Type: GET
update: https://api.sandbox.paypal.com/v2/checkout/orders/51577255GE4475222 Call Type: PATCH
capture: https://api.sandbox.paypal.com/v2/checkout/orders/51577255GE4475222/capture Call Type: POST
This is a screen capture from my sandbox account:
Am I supposed to do something else to actually execute the transfer?
Edit: I figured out how to use the Paypal Payouts API.
First I installed the Nuget Package. It's simply called PayoutsSdk. I'm using version 1.1.1.
For the payout to execute, you need the client() method that is listed above in this post, and this CreatePayout() method listed below.
public async static Task<HttpResponse> CreatePayout()
{
var body = new CreatePayoutRequest()
{
SenderBatchHeader = new SenderBatchHeader()
{
EmailMessage = "Congrats on recieving 1$",
EmailSubject = "You recieved a payout!!"
},
Items = new List<PayoutItem>()
{
new PayoutItem()
{
RecipientType="EMAIL",
Amount=new Currency()
{
CurrencyCode="USD",
Value="1",
},
Receiver="sb-r43z1e9186231#business.example.com",
}
}
};
PayoutsPostRequest request = new PayoutsPostRequest();
request.RequestBody(body);
var response = await client().Execute(request);
var result = response.Result<CreatePayoutResponse>();
Debug.WriteLine($"Status: {result.BatchHeader.BatchStatus}");
Debug.WriteLine($"Batch Id: {result.BatchHeader.PayoutBatchId}");
Debug.WriteLine("Links:");
foreach (PayoutsSdk.Payouts.LinkDescription link in result.Links)
{
Debug.WriteLine($"\t{link.Rel}: {link.Href}\tCall Type: {link.Method}");
}
return response;
}
Of course I'll add parameters to the method for email, amount, currency code, email message, and subject.
Right now, I am calling this method from the controller method like this: var result = Helpers.Paypal.CaptureOrderSample.CreatePayout(); where Helpers.Paypal are folders that contain a class called CaptureOrderSample, which I will probably rename.
To send money from your account to another account, there are several different options:
Automate the sending with the Payouts API or Payouts Web (spreadsheet upload). For live, payouts can only be used if the live account sending the payment is approved for payouts.
Log into the account that is going to send the money in https://www.paypal.com or https://www.sandbox.paypal.com and click on the menu for Pay & Get Paid -> Send Money .
Use a PayPal Checkout integration, with or without the Orders API, and specify a payee that is to receive the money. You must log in with the paying (sending) account to approve the sending, and finally the order must be captured (via API or client side actions.order.capture()) which is what results in a PayPal transaction. If the final capture step is not performed, no money will be sent and the order will merely remain created or approved and eventually expire (72 hours after creation or 3 hours after approval)
In the sandbox, no actual emails are sent with notifications. Instead, the developer.paypal.com dashboard has a "Notifications" tab on the left, and of course activity will also be visible in each sandbox account by logging into the account. Only captured activity is likely to be visible.
Is it possible to trigger recurring payments (subscriptions / billing agreements) using checkout.js?
If so, can you please provide a working example?
Yes its possible. I just created a POC for this.
Create a BillingPlan and activate it
plan = Plan.new(PlanAttributes)
plan.create
patch = Patch.new
patch.op = "replace"
patch.path = "/";
patch.value = { :state => "ACTIVE" }
plan.update( patch )
inside the payment function of paypal.Button call your server to create a BillingAgreement. The user will then authorize the payment.
agreement = Agreement.new(agreement_attributes)
agreement.plan = Plan.new( :id => "<the_plan_id>" )
agreement.create
inside the onAuthorize function of paypal.Button call your server to execute the BillingAgreement
agreement.execute
Following the example in
Checkout https://github.com/chibeepatag/paypal_poc
I'm using the PayPal Merchant SDK for .NET (v 2.15.117) and am trying to retrieve the shipping address info, customer's email address, and phone number from the GetExpressCheckoutDetailsRequestType.GetExpressCheckoutDetailsResponseDetails call. The shipping address is populated as expected but for the life of me, I can't figure out how to get the buyer's email or phone number. At a minimum we have to have the email to communicate about the order (ie tracking emails).
I see a BuyerMarketingEmail property but it is null and I am under the impression that is an optional email the buyer can choose to provide. For phone, I see a PayerInfo.ContactPhone property but that is also null (and I'm less concerned about having that but it would be nice for customer service issues or to give to ground shippers like FedEx).
I am using the PayPal sandbox if that matters.
What am I missing?
var getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();
var getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token);
getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;
var service = new PayPalAPIInterfaceServiceService();
paypalResponse = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);
if (paypalResponse != null)
{
//Success values check for a matching PayerID to validate the token response
if (paypalResponse.Ack.ToString().Trim().ToUpper().Equals("SUCCESS") &&
PayerID == paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID)
{
checkout.ShippingInfo.ShippingName = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Name;
checkout.ShippingInfo.ShippingAddress1 = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
checkout.ShippingInfo.ShippingAddress2 = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
checkout.ShippingInfo.ShippingCity = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
checkout.ShippingInfo.ShippingState = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
checkout.ShippingInfo.ShippingZip = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
checkout.ShippingInfo.ShippingCountry = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString();
//these next two are always null
checkout.BillingInfo.Email = paypalResponse.GetExpressCheckoutDetailsResponseDetails.BuyerMarketingEmail;
checkout.ShippingInfo.PhoneNumber = paypalResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone;
}
}
Thought I'd post an answer to wrap this up -
As stated above in my comment to the original question, the email address of the buyer is PayerInfo.Payer.
Also, suddenly/magically, PayerInfo.ContactPhone began returning the phone number instead of null. I can only chalk that up to something in the Sandbox environment or my sandbox user account.
I trying the new Paypal REST API and want integrate it in sandbox mode into a simple site just to see is it possible to implement one of the following payment flows:
Flow1
1) user fills the payment form, including credit card information
2) user clicks Buy
3) browser stores credit card information in paypal vault via REST API for credit cards (card id used later).
4) browser creates payment for the purchase via REST API call.
5) browser calls app server to ensure that purchase is going on.
5) browser redirects user to url provided by paypal.
6) when user consent/approval received at paypal website, and site redirected back to welcome page,
7) under the hood the IPN callback receives the conformation of payment and marks purchase as paid
8) user obtains access to the service app provides
Flow 2
1) user fills the payment form, including credit card information
2) user clicks Buy
4) browser creates payment for the purchase via REST API call.
5) browser calls app server to ensure that purchase is going on.
5) browser redirects user to url provided by paypal.
6) when user consent/approval received at paypal website, and site redirected back to welcome page,
7) under the hood the IPN callback receives the conformation of payment and marks purchase as paid and uses a bit more pf purchase details like credit card type and last 4 digits to add this info to my purchase object.
8) user obtains the access to services the application provides
8) user obtains access to the service app provides
Reasons to implement all this in such way
Mostly I going this path because i don't want deal with all this PCI compliance, and hones;ty i don't care where customers of my app live, which exactly card numbers they used, or when the card expire, since i don't want use automated subscription like payment, i want use different model:
user gets some pats of service for free, but to use rest of service, user buys time intervals of improved access (e. g. X months or 1 year).
This is what i trying to implement without storing credit cards information or storing as less as possible (paypal credit card id is enough i guess).
Question
Can i implement all this with Paypal REST API?
What i trying to do:
PaypalAdapter.prototype.sendCreditCardPayment = function (amount, description, creditCard, success, failure) {
var ccNumberResult = this.impl.validator.validateCardNumber(creditCard.number);
if (!ccNumberResult.success) {
return this.impl.$q.reject(ccNumberResult);
}
var cardInfo = {
number: ccNumberResult.number,
type: ccNumberResult.type,
expire_month: creditCard.expireMonth,
expire_year: String(creditCard.expireYear),
cvv2: creditCard.securityCode,
first_name: creditCard.firstName,
last_name: creditCard.lastName
};
var self = this;
var defer = self.impl.$q.defer();
this.impl.storeCardAPI(cardInfo,
function cardTokenCreated(cardTokenReply) {
var paymentSettings = {
intent: self.PaymentIntents.Sale,
redirect_urls: {
return_url: self.urls.returnUrl,
cancel_url: self.urls.cancelUrl
},
payer: {
payment_method: self.PayMethods.CreditCard,
funding_instruments: [
{
credit_card_token: {
credit_card_id: cardTokenReply.id
}
}
]
},
transactions: [
{
amount: {
total: String(amount.toFixed(2)),
currency: self.currencyCode
},
description: description
}
]
};
self.impl.createPaymentAPI(paymentSettings, function paymentCreated(payment) {
defer.resolve(payment);
}, function failedToCreatePayment(pcErr) {
defer.reject(pcErr);
});
},
function failedToStoreCard(ctErr) {
defer.reject(ctErr);
});
return defer.promise.then(success, failure);
};
To keep context more clean, here some more pieces of code:
var defaultHeaders = {
Authorization: 'Bearer ' + securityContext.tokens.paypal.access_token,
Accept: 'application/json'
};
var createPaymentResource = $resource(securityContext.configuration.paypal.endPoint + 'payments/payment', {}, {
sendPayment : {
method:'POST',
headers: defaultHeaders
}
});
var saveCreditCardResource = $resource(securityContext.configuration.paypal.endPoint + "vault/credit-cards", {}, {
storeCreditCard: {
method: 'POST',
headers: defaultHeaders
}
});
function storeCardFunc(cardInfo, success, failure) {
return saveCreditCardResource.storeCreditCard(null, cardInfo, success, failure);
}
function createPaymentFunc(paymentInformation, success, failure) {
return createPaymentResource.sendPayment(null, paymentInformation, success, failure);
}
var adapter = new PaypalAdapter($q, securityContext, creditCardValidator, storeCardFunc, createPaymentFunc);
return adapter;
Current "Results"
What i getting:
1) I can store credit card into vault via REST API.
2) i getting error 500 on try to create payment whether i use plain credit card properties to fill credit card funding instrument or try to use credit card token instead.
What i'm doing wrong?
Update
My mistake is a sort of logical with a lack of knowledge.
1) The direct credit cards payments (weather user approves them manually (with intent 'order' and payment_method = 'credit_card'), or not ('sale' intent and payment method 'credit_card') are not available for my country (Republic of Georgia). This is a single reason for the error i see.
Discovered this via Paypal account pages at developer.paypal.com website... It is a frustrating thing. Especially with all this too cryptic "internal server error". I t would be VERY helpful if Paypal would provide at least an informative message "Requested feature not available for your account" with info link to that page with available/enabled features.
Also documentation s a bit broken - some fields like first_name or last_name of payer object of order/payment request are NOT expected by the /payments/payment endpoint...
Can anyone tell me how to automatically execute a delayed payment (let's say it's 5 days after the primary receiver receive the payment) in a chained payment manner? The key is automatic execution, not having to manually approve and pay the secondary receiver. Please illuminate with some sample code.
I have used "actionType" => "PAY_PRIMARY" so that primary receiver get money.
But how can I code so that secondary receiver get money?
Check this answer for the solution. Basically you just need to execute an ExecutePayment operation with the payKey within 90 days to send the payment to the secondary party.
actionType is PAY_PPRIMARY
you then trigger this payment within 90 days.
Its delayed but not time-elapsed.
https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_AdaptivePayments.pdf
well may be its too late but it will help someone in future for sure.
As we integrated paypal delayed chained payment, you can set a primary account in which all the amount will go and you can also set secondary account in which account will be transfered once they approved by primary account holder.
string endpoint = Constants_Common.endpoint + "Pay";
NVPHelper NVPRequest = new NVPHelper();
NVPRequest[SampleNVPConstant.requestEnvelopeerrorLanguage] = "en_US";
//NVPRequest[SampleNVPConstant.Pay2.actionType] = "PAY";
//the above one is for simple adoptive payment payment
NVPRequest[SampleNVPConstant.Pay2.actionType] = "PAY_PRIMARY";
//the above one for deleayed chained payment
NVPRequest[SampleNVPConstant.Pay2.currencyCode] = "USD";
NVPRequest[SampleNVPConstant.Pay2.feesPayer] = "EACHRECEIVER";
NVPRequest[SampleNVPConstant.Pay2.memo] = "XXXXXXXX";
Now we have to set primary and secondary receivers:
//primary account
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiveramount_0] = TotalAmount;
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiveremail_0] = "XXXx.xxxxx.com";
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiverprimary_0] = "true";
//secondary accounts
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiveramount_1] = (somemoney out of total amount);
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiveremail_1] = "xxxxx.xxxx.com";
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiverprimary_1] = "false";
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiveramount_2] = (somemoney out of total amount);
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiveremail_2] = x.x.com;
NVPRequest[SampleNVPConstant.Pay2.receiverListreceiverprimary_2] = "false";
Don't forget that you have to give a valid paypal account while using delayed chained payment.
Now you get your pay_key which you have to use to execute your payment whithin 90 days so that other secondary receivers get money.
Here is the working code:
String endpoint = Constants_Common.endpoint + "ExecutePayment";
NVPHelper NVPRequest = new NVPHelper();
//requestEnvelope.errorLanguage is common for all the request
NVPRequest[SampleNVPConstant.requestEnvelopeerrorLanguage] = "en_US";
NVPRequest[SampleNVPConstant.ExecutePayment.payKey] = "your pay key";
string strrequestforNvp = NVPRequest.Encode();
//calling Call method where actuall API call is made, NVP string, header value adne end point are passed as the input.
CallerServices_NVP CallerServices = new CallerServices_NVP();
string stresponsenvp = CallerServices.Call(strrequestforNvp, Constants_Common.headers(), endpoint);
//Response is send to Decoder method where it is decoded to readable hash table
NVPHelper decoder = new NVPHelper();
decoder.Decode(stresponsenvp);
if (decoder != null && decoder["responseEnvelope.ack"].Equals("Success") && decoder["paymentExecStatus"].Equals("COMPLETED"))
{
//do something
}
Hope it will help someone.