how to get payer_id programmatically in my java code? - java

In my code, I am trying to send to Paypal REST API the needed information and Paypal is giving me an "APPROVED" status but in order to finalize the payment, I need to execute the payment.
payment.execute(accesstoken,paymentExecution)... but I couldn't get the payer_id from the response.
Here is my code for further information and thanks for your help in advance!
public class PaypalPaymentWithCreditCardServlet {
// private static final long serialVersionUID = 734220724945040319L;
// #Override
public void init () throws Exception {
InputStream is = PaypalPaymentWithCreditCardServlet.class.getResourceAsStream("/sdk_config.properties");
try {
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
// goto failure page. can't do anything without configuration file
e.printStackTrace();
}
}
public boolean doPost (PaymentPojo paymentpojo) throws Exception {
try {
String accessToken = GenerateAccessToken.getAccessToken();
APIContext apiContext = new APIContext(accessToken);
final Payment payment = new PaymentBuilder().setBillingAddress(paymentpojo.getBillingAddress())
.setCreditCard(paymentpojo.getCreditCard())
.setPaymentDetail(paymentpojo.getDetails())
.setTransactionAmount(paymentpojo.getAmount())
.build();
Payment createdPayment = payment.create(apiContext);
System.out.println(Payment.getLastResponse());
System.out.println(String.format("created payment with id [%s] and status=[%s]", createdPayment.getId(), createdPayment.getState()));
if(!createdPayment.getState().toLowerCase().equalsIgnoreCase(PaypalState.APPROVED.getStatus())) {
// payment is not created. throw an exception
System.out.println("Payment handshake did not go through!!!");
return false;
}
// if it is not created throw exception
// payment.execute(accessToken, paymentExecution);
return true;
} catch (PayPalRESTException e) {
}
return false;
}
}

For credit card payments, payer_id is the unique attribute (e.g email address) that you use to identify the user in your system and you would provide that for payment each time in payerID.
If you are not aware of the user's information, such as a guest checkout, you should not need to provide a payerID.
For paypal payments, payer_id always needs to be provided and is appended to redirect_url once the user approves the payment. Full docs are at https://developer.paypal.com/webapps/developer/docs/integration/web/accept-paypal-payment/

Related

Discord API (JDA) Get a user from specific Guild

try {
final JDABuilder jdaBuilder = JDABuilder.createDefault(TOKEN_ID);
jdaBuilder.addEventListeners(new DiscordListener());
_jdaBuild = jdaBuilder.build();
} catch(final LoginException e) {
}
I tried use the
_jdaBuild.getUserById(userId);
But it always return null. I also tried do a for to all Guild then to all Text Channels and then to All members but in log it only show the ID of the Bot from all Text Channels. Not the other users.
How can i get user base on his ID or Name from a Guild and send him a private?
You need to use JDA#retrieveUserById​(long) because JDA#getUserById(long) only works if the user is cached:
try {
final JDABuilder jdaBuilder = JDABuilder.createDefault(TOKEN_ID);
jdaBuilder.addEventListeners(new DiscordListener());
_jdaBuild = jdaBuilder.build();
} catch(final LoginException e) {
//...
}
//...
User user = _jdaBuild.retrieveUserById("...").complete();

what is the proper way of calling multiple services in spring boot

Suppose I have a service that allows users to give some points to the other user. So, to send some points to the specific user, it needs to know which account is going to send and which account is sending. Thus, I create another service responsible for finding an account by its id. Everything works fine, but I just wonder what the proper way or best practice of doing this is. I have 3 strategies on my mind.
Here is how it looks like:
Let the controller calls the account finding service and passes it to the sender service.
// a method in Controller class
#RequestMapping("/transactions")
public ResponseEntity<?> sendNuggerPoint(Long senderId, Long receiverId, Long amountOfNugger){
Optional<Account> sender = accountService.getAccountById(senderId);
Optional<Account> receiver = accountService.getAccountById(receiverId);
if(sender.isPresent()&&receiver.isPresent()){
try {
transactionService.transferNuggerPointToAccount(sender.get(), receiver.get(), amountOfNugger);
}
catch(InsufficientNuggerPointException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// a method in Service class
public void transferNuggerPointToAccount(Account senderAccount, Account receiverAccount,Long amountOfNugger) throws InsufficientNuggerPointException{
// get both account yum yum nugger
Long senderCurrentNugger = senderAccount.getNuggerPoint();
Long receiverCurrentNugger = receiverAccount.getNuggerPoint();
if(senderCurrentNugger < amountOfNugger) {
// throw exception if sender nugger is insufficient
throw new InsufficientNuggerPointException("Sorry, insufficeint nugger point.");
}
senderAccount.setNuggerPoint(senderCurrentNugger - amountOfNugger);
receiverAccount.setNuggerPoint(receiverCurrentNugger + amountOfNugger);
}
Just pass both sender and receiver Id through and let sender service calls account finding service.
// a method in Controller class
#RequestMapping("/transactions")
public ResponseEntity<?> sendNuggerPoint(Long senderId, Long receiverId, Long amountOfNugger){
if(sender.isPresent()&&receiver.isPresent()){
try {
transactionService.transferNuggerPointToAccount(senderId, receiverId, amountOfNugger);
}
catch(InsufficientNuggerPointException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// a method in Service class
public void transferNuggerPointToAccount(Long senderId, Long receiverId,Long amountOfNugger) throws InsufficientNuggerPointException{
// get both account yum yum nugger
Optional<Account> sender = accountService.getAccountById(senderId);
Optional<Account> receiver = accountService.getAccountById(receiverId);
if(sender.isPresent() && receiver.isPresent()){
Long senderCurrentNugger = sender.get().getNuggerPoint();
Long receiverCurrentNugger = receiver.get().getNuggerPoint();
if(senderCurrentNugger < amountOfNugger) {
// throw exception if sender nugger is insufficient
throw new InsufficientNuggerPointException("Sorry, insufficeint nugger point.");
}
senderAccount.setNuggerPoint(senderCurrentNugger - amountOfNugger);
receiverAccount.setNuggerPoint(receiverCurrentNugger + amountOfNugger);
}
}
Create another entity and let the user send all information within the request body
// a method in Controller class
#RequestMapping("/transactions")
public ResponseEntity<?> sendNuggerPoint(#RequestBody Transaction transaction){
try {
transactionService.transferNuggerPointToAccount(transaction.getSender(), transaction.getReceiver(), transaction.getAmoutOfNugger());
}
catch(InsufficientNuggerPointException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// a method in Service class
public void transferNuggerPointToAccount(Account senderAccount, Account receiverAccount,Long amountOfNugger) throws InsufficientNuggerPointException{
// get both account yum yum nugger
Long senderCurrentNugger = senderAccount.getNuggerPoint();
Long receiverCurrentNugger = receiverAccount.getNuggerPoint();
if(senderCurrentNugger < amountOfNugger) {
// throw exception if sender nugger is insufficient
throw new InsufficientNuggerPointException("Sorry, insufficeint nugger point.");
}
senderAccount.setNuggerPoint(senderCurrentNugger - amountOfNugger);
receiverAccount.setNuggerPoint(receiverCurrentNugger + amountOfNugger);
}

Java - How to delete an entity from Google Cloud Datastore

Architecture: I have a web application from where I'm interacting with the Datastore and a client (raspberry pi) which is calling methods from the web application using Google Cloud Endpoints.
I have to add that I'm not very familiar with web applications and I assume that something's wrong with the setConsumed() method because I can see the call of /create in the app engine dashboard but there's no entry for /setConsumed.
I'm able to add entities to the Datastore using objectify:
//client method
private static void sendSensorData(long index, String serialNumber) throws IOException {
SensorData data = new SensorData();
data.setId(index+1);
data.setSerialNumber(serialNumber);
sensor.create(data).execute();
}
//api method in the web application
#ApiMethod(name = "create", httpMethod = "post")
public SensorData create(SensorData data, User user) {
// check if user is authenticated and authorized
if (user == null) {
log.warning("User is not authenticated");
System.out.println("Trying to authenticate user...");
createUser(user);
// throw new RuntimeException("Authentication required!");
} else if (!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
log.warning("User is not authorised, email: " + user.getEmail());
throw new RuntimeException("Not authorised!");
}
data.save();
return data;
}
//method in entity class SensorData
public Key<SensorData> save() {
return ofy().save().entity(this).now();
}
However, I'm not able to delete an entity from the datastore using the following code.
EDIT: There are many logs of the create-request in Stackdriver Logging, but none of setConsumed(). So it seems like the calls don't even reach the API although both methods are in the same class.
EDIT 2: The entity gets removed when I invoke the method from the Powershell so the problem is most likely on client side.
//client method
private static void removeSensorData(long index) throws IOException {
sensor.setConsumed(index+1);
}
//api method in the web application
#ApiMethod(name = "setConsumed", httpMethod = "put")
public void setConsumed(#Named("id") Long id, User user) {
// check if user is authenticated and authorized
if (user == null) {
log.warning("User is not authenticated");
System.out.println("Trying to authenticate user...");
createUser(user);
// throw new RuntimeException("Authentication required!");
} else if (!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
log.warning("User is not authorised, email: " + user.getEmail());
throw new RuntimeException("Not authorised!");
}
Key serialKey = KeyFactory.createKey("SensorData", id);
datastore.delete(serialKey);
}
This is what I follow to delete an entity from datastore.
public boolean deleteEntity(String propertyValue) {
String entityName = "YOUR_ENTITY_NAME";
String gql = "SELECT * FROM "+entityName +" WHERE property= "+propertyValue+"";
Query<Entity> query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, gql)
.setAllowLiteral(true).build();
try{
QueryResults<Entity> results = ds.run(query);
if (results.hasNext()) {
Entity rs = results.next();
ds.delete(rs.getKey());
return true;
}
return false;
}catch(Exception e){
logger.error(e.getMessage());
return false;
}
}
If you don't want to use literals, you can also use binding as follows:
String gql = "SELECT * FROM "+entityName+" WHERE property1= #prop1 AND property2= #prop2";
Query<Entity> query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, gql)
.setBinding("prop1", propertyValue1)
.setBinding("prop2", propertyValue2)
.build();
Hope this helps.
I was able to solve it by myself finally!
The problem was just related to the data type of the index used for removeSensorData(long index) which came out of a for-loop and therefore was an Integer instead of a long.

UnboundID : How to encapsulate processBindRequest return value?

I'm building an LDAP interface for my database. When a client request bind(), it will search in the database and check if it is valid or not.
public class Main {
LDAPListener listener ;
Main() {}
public static void main(String[] args) {
Main main = new Main();
int port = main.StartServer();
try {
LDAPConnection cn = new LDAPConnection("localhost",port);
System.out.println("."+cn.isConnected()+" "+cn.getConnectedPort());
cn.bind("uid=user,ou=People,dc=example,dc=com", "pass");
cn.close();
main.StopServer();
} catch (Exception e){e.printStackTrace();
main.StopServer();}
}
public int StartServer() {
int listenPort = 0;
RequestHandler requestHandler = new RequestHandler();
LDAPListenerConfig config = new LDAPListenerConfig(listenPort, requestHandler);
listener = new LDAPListener(config);
try {
listener.startListening();
System.out.println(">port "+listener.getListenPort());
} catch (Exception e){System.out.println("e1> "+e.getMessage());}
return listener.getListenPort();
}
public void StopServer(){
System.out.println(">shutdown");
listener.shutDown(true);
}
}
Then, i modify LDAPListenerRequestHandler to communicate with the database, get the record as return value:
class RequestHandler extends LDAPListenerRequestHandler {
#Override
public LDAPMessage processBindRequest(int arg0, BindRequestProtocolOp arg1,
List<Control> arg2) {
String uid = arg1.getBindDN();
String pass = arg1.getSimplePassword();
System.out.println(">bind: "+ uid);
// Database query: SELECT * FROM user WHERE username='uid' AND password='pass'
// Get the record as return value
return null;
}
}
When i run it, i got error message from the bind line:
LDAPException(resultCode=80 (other), errorMessage='An unexpected exception was thrown while attempting to process the requested operation: NullPointerException(trace='run(LDAPListenerClientConnection.java:461)', revision=15579)', diagnosticMessage='An unexpected exception was thrown while attempting to process the requested operation: NullPointerException(trace='run(LDAPListenerClientConnection.java:461)', revision=15579)')
at com.unboundid.ldap.sdk.LDAPConnection.bind(LDAPConnection.java:1881)
at com.unboundid.ldap.sdk.LDAPConnection.bind(LDAPConnection.java:1799)
I think, it is caused by processBindRequest() that return null. How to encapsulate my database record as LDAPMessage in that process?
You are correct that the processBindRequest method must return a non-null response.
If the bind is successful (the user exists, is allowed to authenticate, and has provided the correct credentials) then you can create a successful response with code like:
#Override()
public LDAPMessage processBindRequest(final int messageID,
final BindRequestProtocolOp request,
final List<Control> controls)
{
return new LDAPMessage(messageID,
new BindResponseProtocolOp(ResultCode.SUCCESS_INT_VALUE,
null, // No matched DN is needed
null, // No diagnostic message is needed
null, // No referral URLs are needed
null), // No server SASL credentials are needed
Collections.<Control>emptyList()); // Add empty list to return
}
If the authentication is not successful, then you should probably return a response with a result code of INVALID_CREDENTIALS rather than SUCCESS, and if you want to provide a message to the client with information about why the bind failed, you can put that in the diagnostic message element.

getFailedLoginAttempts() function doesn't make any sense in appfoundation in Vaadin

How to get failed login attempts using appfoundation? It has a function getFailedLoginAttempts() but it doesn't make any sense. I am using Vaadin 6 (6.8.12)
My code is here:
NativeButton login = new NativeButton(Lang.getMessage("login"), new ClickListener() {
private static final long serialVersionUID = -5577423546946890721L;
public void buttonClick(ClickEvent event) {
username = (String) usernameField.getValue();
String password = (String) passwordField.getValue();
try {
AuthenticationUtil.authenticate(username, password);
startApp();
} catch (InvalidCredentialsException e) {
/* I need to get failed login attempts here but how can I do that?
I just can by doing this: AuthenticationUtil.authenticate(username, password).
getFailedLoginAttempts(), but I need to write try and catch blocks
(so try and catch blocks in catch block) for authenticate method and this
function will never work, because user won't be authenticated and all
the time you will go to the other catch block; */
feedbackLabel.setValue(Lang.getMessage("usernameOrPasswordIncorect"));
} catch (AccountLockedException e) {
feedbackLabel.setValue(Lang.getMessage("accountBlocked"));
}
}
});
I wrote all the problem in the comment. I want to print a number of failed login attempts but can't get this number. Any suggestions?
Why the code AuthenticationUtil.authenticate(username, password).
getFailedLoginAttempts() compiles is that the authenticate method returns a User object upon successful authentication and this method can then be accessed. However if an exception is throws then you do not have the User object. In their unit tests then use a FactoryFacade to retrieve the user object and check it that way. I do not know the API well so I can not tell you whether you can get the user some other way.
see https://code.google.com/p/vaadin-appfoundation/source/browse/src/org/vaadin/appfoundation/authentication/util/AuthenticationUtil.java
I wrote a function for getting user in my own class.
private User getUserForUsername(String username) {
String query = "SELECT u FROM User u WHERE u.username = :username";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("username", username);
return (User) FacadeFactory.getFacade().find(query, parameters);
}
And call this method in catch block.
try {
AuthenticationUtil.authenticate(username, password);
startApp();
} catch (InvalidCredentialsException e) {
User user = getUserForUsername(username);
feedbackLabel.setValue(Lang.getMessage("usernameOrPasswordIncorect"));
attemptsLeftLabel.setValue(Lang.getMessage("attemptsLeft", 5 - user.getFailedLoginAttempts()));
} catch (AccountLockedException e) {
feedbackLabel.setValue(Lang.getMessage("accountBlocked"));
}
All works fine.

Categories

Resources