I use PayPal-NET-SDK for interact with PayPal system (sanbox). I have next code:
static void Main(string[] args)
{
try
{
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var payment = Payment.Create(apiContext, new Payment
{
intent = "order",
payer = new Payer
{
payment_method = "paypal"
},
transactions = new List<Transaction>
{
new Transaction
{
description = "Transaction description.",
invoice_number = "002",
amount = new Amount
{
currency = "USD",
total = "15.00",
},
payee = new Payee
{
email = "test1#gmail.com"
}
}
},
redirect_urls = new RedirectUrls
{
return_url = "site for redirect", // in my code there is normal url
cancel_url = "site for redirect""
}
});
var approval = payment.GetTokenFromApprovalUrl();
var url = payment.GetApprovalUrl();
payment.token = approval;
var response = payment.Execute(apiContext, new PaymentExecution {payer_id = "C598R54Q6P39G" });
}
catch (PaymentsException e)
{
Console.WriteLine(e.Response);
}
}
After executing this code i receive bad request error from PayPal ("Payer has not approved payment"). If go to link in url in debug, i get to PayPal confirm page, and after push continue button, payment executing withoue exceptions (but funds still same, money is not sending). How i can send money to other paypal wallet without redirect to PayPal aproving page?
Resolved by using payout (as i uderstand, payments use for client to merchant transfer).
static void Main(string[] args)
{
try
{
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var payout = Payout.Create(apiContext, new Payout
{
sender_batch_header = new PayoutSenderBatchHeader
{
email_subject = "Hello payout",
sender_batch_id = "ilab_Payout002",
recipient_type = PayoutRecipientType.EMAIL
},
items = new List<PayoutItem>
{
new PayoutItem
{
amount = new Currency
{
currency = "USD",
value = "17.5"
},
note = "Exchange is done!",
receiver = "ilab-test1#gmail.com",
recipient_type = PayoutRecipientType.EMAIL,
sender_item_id = "121341"
}
},
});
}
catch (PaymentsException e)
{
Console.WriteLine(e.Response);
}
}
}
Related
I want to integrate Stripe into my ASP.NET MVC application.
So, As the first step, I'm trying to do it with simple code.
This is my simple code below,
var customers = new CustomerService();
var charges = new ChargeService();
var publishableKey = "pk_test_51KseuBH1Mw1tyjglBiJls20038FcgbHr";
StripeConfiguration.SetApiKey(publishableKey);
StripeConfiguration.ApiKey = "sk_test_51KseuRqoYQ6YGD7TNzPp0051boOPvQ";
var customer = customers.Create(new CustomerCreateOptions
{
Email = "isanka.ad#gmail.com",
Source = publishableKey
});
var charge = charges.Create(new ChargeCreateOptions
{
Amount = 500,
Description = "Sample Charge",
Currency = "usd",
Customer = customer.Id
});
I have tried different codes on forams. But it always returns the same error below,
No such token: 'pk_test_51KseuBHaMw1tyjglBiJls20038FcgbHr'
This is my Stripe keys,
Did I define secret key and publishable key incorrectly?
The publishable key must not be used in your backend code. It is for your client-side code, as described in the documentation: https://stripe.com/docs/keys. Moreover, the Source property on the customer describes the payment method: https://stripe.com/docs/api/customers/create?lang=dotnet. I can recommend getting started with Stripe with the quick start guide: https://stripe.com/docs/payments/quickstart.
It seems you copied only the first line of the API Key.
Please make sure that you are using the complete API Key in your application, and you don't need to use publishable key in your backend integration.
The source value only accepts payment source created via the Token or Sources APIs.
When creating a customer in your sample code, the Source was assigned with publishableKey which is invalid and that's probably why "No such token" was returned.
If you do not have any source created upfront, then Source should be removed from your customer creation request.
I was missing creating the card and token
generate. Above I have assigned the publishable token as the source value, not generated token.
Here is the full working code.
public async Task<ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest)
{
var processPaymentResult = new ProcessPaymentResult();
try
{
var customers = new CustomerService();
var charges = new ChargeService();
var options = new RequestOptions
{
ApiKey = // your Secret Key
};
#region Card payment checkout
var creditCardType = processPaymentRequest.CreditCardType.ToString();
var optionToken = new TokenCreateOptions
{
Card = new TokenCardOptions
{
Number = processPaymentRequest.CreditCardNumber,
ExpMonth = processPaymentRequest.CreditCardExpireMonth,
ExpYear = processPaymentRequest.CreditCardExpireYear,
Cvc = processPaymentRequest.CreditCardCvv2,
Name = processPaymentRequest.CreditCardName,
Currency = _workContext.WorkingCurrency.CurrencyCode
},
};
var tokenService = new TokenService();
Token paymentToken = await tokenService.CreateAsync(optionToken, options);
#endregion
#region Stripe Customer
var customer = new Customer();
var customerEmail = processPaymentRequest.CustomValues["CustomerEmail"].ToString();
// Search customer in Stripe
var stripeCustomer = await customers.ListAsync(new CustomerListOptions
{
Email = customerEmail,
Limit = 1
}, options);
if (stripeCustomer.Data.Count==0)
{
// create new customer
customer = await customers.CreateAsync(new CustomerCreateOptions
{
Source = paymentToken.Id,
Phone = processPaymentRequest.CustomValues["Phone"].ToString(),
Name = processPaymentRequest.CustomValues["CustomerName"].ToString(),
Email = customerEmail,
Description = $" { processPaymentRequest.CustomValues["RegisteredEmail"]};{ processPaymentRequest.CustomValues["CustomerName"] }",
}, options);
}
else
{
// use existing customer
customer = stripeCustomer.FirstOrDefault();
}
#endregion
#region Stripe charges
var charge = await charges.CreateAsync(new ChargeCreateOptions
{
Source = paymentToken.Id,//Customer = customer.Id,
Amount = (int)(Math.Round(processPaymentRequest.OrderTotal, 2) * 100),
Currency = _workContext.WorkingCurrency.CurrencyCode,
ReceiptEmail = customer.Email,
Description = $" { processPaymentRequest.CustomValues["RegisteredEmail"]};{ processPaymentRequest.CustomValues["CustomerName"] }",
}, options);
if (charge.Status.ToLower().Equals("succeeded"))
{
processPaymentResult.NewPaymentStatus = PaymentStatus.Paid;
processPaymentResult.CaptureTransactionId = charge.Id;
}
else
{
processPaymentResult.AddError("Error processing payment." + charge.FailureMessage);
}
#endregion
}
catch (Exception ex)
{
processPaymentResult.AddError(ex.Message);
}
return processPaymentResult;
}
You need to add secretKey in the setapikey function.
// StripeConfiguration.SetApiKey(publishableKey);
StripeConfiguration.SetApiKey(secretKey);
Hi im working on stripe subscription based session. I have created a Product on Stripe Dashboard and on session creating im passing hardcoded priceid and connected account id in the session but i m receiving bad request exception on creating the same session.
Here is my sample code as directed by this link https://stripe.com/docs/payments/checkout/migration in connect plateform and marketplaces After Section
StripeConfiguration.ApiKey = "{ApiKey}";
var options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
Price = "{price_...}", //pricing id copied from dashboard
},
},
Mode = "subscription",
PaymentIntentData = new SessionPaymentIntentDataOptions
{
ApplicationFeeAmount = 20,
},
SuccessUrl = "https://example.com/success",
CancelUrl = "https://example.com/cancel",
};
var requestOptions = new RequestOptions
{
StripeAccount = "acct_...", // activated connected account id copied from dashboard
};
var service = new SessionService();
Session session = service.Create(options, requestOptions); // exception no such price found bad request
I'm using PeopleService in order to create contacts straight into my G Suit Account. I followed the security steps about getting the key for a type of Service Account. My Application will create contacts so that there's no need to request a specific user permission. It has its own key and credentials.
My code seems to work except because the CreateContactRequest provides me ResourceName with value "people/c171255166120767303". And every time I request I got a different resourceName like this "people/c9013378989213012841".
The problem is, where the hell that goes? At my G Suite account, I can’t see the created contact anywhere.
But the resulting Person object seems to be ok.
How can I check if this works? Where the contact was created?
The code is as bellow:
private static string _clientId = "1........1";
private static string _clienteScret = "i******************_";
private static string _serviceAccountId = "aaaa#bbbb.iam.gserviceaccount.com";
public static void Cadastrar(Models.SignupRequest message)
{
var chave =
#"D:\********.p12";
var certificate = new X509Certificate2(chave, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(_serviceAccountId)
{
Scopes = new[] {
PeopleService.Scope.Contacts,
PeopleService.Scope.ContactsReadonly,
"https://www.google.com/m8/feeds"
}
}.FromCertificate(certificate));
var service = new PeopleService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Client for www",
});
var contactToCreate = new Person();
var names = new List<Name> {new Name() {GivenName = message.name, FamilyName = "Doe"}};
contactToCreate.Names = names;
contactToCreate.EmailAddresses = new List<EmailAddress>
{
new EmailAddress()
{
DisplayName = message.name,
Value = message.email
}
};
contactToCreate.Organizations = new List<Organization>
{
new Organization()
{
Current = true,
Name = message.nome_fantasia,
}
};
contactToCreate.Biographies = new List<Biography>
{
new Biography()
{
Value = message.ToString()
}
};
contactToCreate.PhoneNumbers = new List<PhoneNumber>
{
new PhoneNumber()
{
Type = "mobile",
Value = message.celular
},
new PhoneNumber()
{
Type = "work",
Value = message.telefone
}
};
var request = new Google.Apis.PeopleService.v1.PeopleResource.CreateContactRequest(service, contactToCreate);
var createdContact = request.Execute();
}
If you want to create contact for user with 'email#yourdomain.com' through a service account you need:
Use "setServiceAccountUser(userEmail)" to impersonate the user
Enable impersonation on your G-Suite for People API service. For this point:
See section "Delegating domain wide access" here
Get client-id from your credential account
Use "https://www.googleapis.com/auth/contacts" as scope.
I am trying to make a paypal handler. You type a money amount into an input, than you press donate button, you will be forwarded to the paypal page, you can login and than press continue button... The problem after I press the continue button its forward me back to the https://www.example.org/Account/PayPalHandler/ page, and thats it all. What is missing from my code to complete the paypal transaction?
[HttpPost]
public ActionResult DoPaymentPaypall(UserModel User_)
{
ResultModel<ManageAccountListModel> res_ = new ResultModel<ManageAccountListModel>();
res_.DataSelect = new ManageAccountListModel();
if (SessionManagement.LoginnedUser != null)
{
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
string moneyCount_ = User_.moneycount.ToString();
var payment = Payment.Create(apiContext, new Payment
{
intent = "sale",
payer = new Payer
{
payment_method = "paypal"
},
transactions = new List<Transaction>
{
new Transaction
{
description = "Donation",
invoice_number = "001",
amount = new Amount
{
currency = "USD",
total = moneyCount_,
details = new Details
{
tax = "0",
shipping = "0",
subtotal = moneyCount_
}
},
item_list = new ItemList
{
items = new List<Item>
{
new Item
{
name = "Donation",
currency = "USD",
price = moneyCount_,
quantity = "1",
sku = "Custom Package"
}
}
}
}
},
redirect_urls = new RedirectUrls
{
return_url = "https://www.example.org/Account/PayPalHandler/",
cancel_url = "https://www.example.org/"
}
});
res_.SuccessMessage = payment.links.ToList()[1].href;
}
res_.Success = true;
return new JsonResult { Data = res_, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Your code above seems to only show the initial/start of the process...so assuming you mean after the user has approved your request to use Paypal for payment (don't confuse this as "the payment" - this step only indicates that the user as agreed to use Paypal for payment) you'll need to Execute the payment.
The link shows the full flow
Create payment (this is what your code above maps to) - you'll get a payment id in this step
redirect user to Paypal approval_url for approval (of the details in the Create above) using the id you recieved
Paypal sends user back to your site with info on how to Execute payment (if user approves)
Execute payment (this is done at your site/app)
Hth
I am using the PayPal sandbox in ASP.Net C# 4.0. I added the following web references:
https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
When I run this code:
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq req = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutRequestType()
{
Version = Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
// query PayPal and get token
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutResponseType resp = BuildPayPalSandboxWebservice().SetExpressCheckout(req);
In my resp object, the error message says:
Security header is not valid
I was told to give it correct API credentials. I signed up on developer.paypal.com and i'm assuming the email address and password i used are my valid credentials. How and where do I give it my API credentials? Thanks
Did you check the endpoint addresses in your web.config file
Those should be referenced to following url's
For API Certificate => SOAP https://api.sandbox.paypal.com/2.0/
For API Signature => SOAP https://api-3t.sandbox.paypal.com/2.0/
If you are using Signature then use the following code
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"], //Not paypal login username
Password = ConfigurationManager.AppSettings["PayPalPassword"], //not login password
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
To get Paypal signature follow the link
For more info click here
Update:
Please check the following code it is working for me
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"],
Password = ConfigurationManager.AppSettings["PayPalPassword"],
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
PaymentDetailsItemType[] pdItem = new PaymentDetailsItemType[1];
pdItem[0] = new PaymentDetailsItemType()
{
Amount = new BasicAmountType(){currencyID = CurrencyCodeType.USD,Value = ItemPrice},
Name = ItemName,
Number = ItemNumber,
Description = ItemDescription,
ItemURL = ItemUrl
};
SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
sdt.NoShipping = "1";
PaymentDetailsType pdt = new PaymentDetailsType()
{
OrderDescription = OrderDesc,
PaymentDetailsItem = pdItem,
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = ItemPrice
}
};
sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
sdt.CancelURL = "http://localhost:62744/PaymentGateway/PaymentFailure.aspx";
sdt.ReturnURL = "http://localhost:62744/PaymentGateway/ExpressCheckoutSuccess.aspx";
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
SetExpressCheckoutRequestDetails = sdt,
Version = "92.0"
}
};
var paypalAAInt = new PayPalAPIAAInterfaceClient();
var resp = paypalAAInt.SetExpressCheckout(ref type, req);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
ConfigurationManager.AppSettings["PayPalOriginalUrl"], resp.Token));