Тестовая обработка платежей Paypal для пользователя - PullRequest
0 голосов
/ 15 апреля 2019

У меня есть конечная точка, где я хотел бы отправлять пользователям денежное вознаграждение за действия с использованием PayPal.Предоставляется пользовательская модель,

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    @NotNull
    @NotEmpty
    private String name;

    @Column(name = "countryName")
    @NotNull
    @NotEmpty
    private String countryName;


    @Column(name = "currencyName")
    @NotNull
    @NotEmpty
    private String currencyName;


    /*
     * total steps is for the keepign the history of the user movement
     * */
    @Column(name = "totalSteps")
    @Min(value = 0L, message = BIGGER_OR_EQUAL_TO_ZERO)
    private int totalSteps;

    /*
     * current steps is for providing the user reward. We will need to set
     * it to zero after processing the user paymentUsingPaypal
     * */
    @Column(name = "currentSteps")
    @Min(value = 0L, message = BIGGER_OR_EQUAL_TO_ZERO)
    private int currentSteps;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Reward> rewards = new ArrayList<>();

    public User() {

    }

    public User(@NotNull @NotEmpty String name, @NotNull @NotEmpty String countryName) {
        this.name = name;
        this.countryName = countryName;
    }

    public User(@NotNull @NotEmpty String name, @NotNull @NotEmpty String countryName, @Min(value = 0L, message = "The value must be positive") int totalSteps) {
        this.name = name;
        this.countryName = countryName;
        this.totalSteps = totalSteps;
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountryName() {
        return countryName;
    }

    public String getCurrencyName() {
        return currencyName;
    }

    public void setCurrencyName(String currencyName) {
        this.currencyName = currencyName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public int getTotalSteps() {
        return totalSteps;
    }

    public void setTotalSteps(int totalSteps) {
        this.totalSteps = totalSteps;
    }

    public int getCurrentSteps() {
        return currentSteps;
    }

    public void setCurrentSteps(int currentSteps) {
        this.currentSteps = currentSteps;
    }

    public List<Reward> getRewards() {
        return rewards;
    }

    public void setRewards(List<Reward> rewards) {
        this.rewards = rewards;
    }

    public void addReward(Reward reward) {

        if (this.rewards == null){
            this.rewards = new ArrayList<>();
        }

        this.rewards.add(reward);
    }

     // .....
}

Предоставляется конечная точка API,

    @PostMapping("/make-paypal-payment")
    public ResponseEntity<Map<String, Object>> paymentUsingPaypal(@RequestBody User user) {

        String s = calculateReward(user.getId()).getBody();

        JSONObject obj = new JSONObject(s);

        /**
         * we get the reward amount in the local currency
         */
        try {

            String reward = obj.get("reward").toString();
            payPalClient.createPayment(reward, user.getCurrencyName());
        } catch (Exception ex) {

            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }

        /*
         * create an unique payment ID for processing the reward payment to our users
         * */
        String paymentId = (java.util.UUID.randomUUID()).toString();
        Map<String, Object> paymentCompletion = payPalClient.completePayment(paymentId);

        /*
        * the payment processing is not successful
        * */
     // this is the code I added later as the paymanet is processing
        // if(paymentCompletion.size() == 0){
          //  return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        //}

        return ResponseEntity.status(HttpStatus.CREATED).contentType(MediaType.APPLICATION_JSON_UTF8).body(paymentCompletion);
    }

У меня есть класс, который я использую для платежа с использованием PayPal,

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class PayPalClient {


    /**
     * create the payment using the reward amount and currency name
     * for our users
     *
     * @param sum
     * @param currencyName
     * @return
     */
    public Map<String, Object> createPayment(String sum, String currencyName) {

        Map<String, Object> response = new HashMap<>();
        Amount amount = new Amount();

        amount.setCurrency(currencyName);
        amount.setTotal(sum);

        Transaction transaction = new Transaction();
        transaction.setAmount(amount);

        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod("paypal");

        Payment payment = new Payment();
        payment.setIntent("buy");
        payment.setPayer(payer);
        payment.setTransactions(transactions);

        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl("http://localhost:4200/cancel");
        redirectUrls.setReturnUrl("http://localhost:4200/");

        payment.setRedirectUrls(redirectUrls);
        Payment createdPayment;

        try {

            String redirectUrl = "";
            APIContext context = new APIContext(CLIENT_ID, SECRET, "sandbox");
            createdPayment = payment.create(context);

            if (createdPayment != null) {

                List<Links> links = createdPayment.getLinks();

                for (Links link : links) {
                    if (link.getRel().equals("approval_url")) {
                        redirectUrl = link.getHref();
                        break;
                    }
                }
                response.put("status", "success");
                response.put("redirect_url", redirectUrl);
            }
        } catch (PayPalRESTException e) {
            System.out.println("Error happened during paymentUsingPaypal creation!");
        }

        return response;
    }


    /**
     * complete the payment to our users using an unique payment ID
     * and return the response code for the success (or faliure)
     *
     * @param paymentId
     * @return
     */
    public Map<String, Object> completePayment(String paymentId) {

        Map<String, Object> response = new HashMap();

        Payment payment = new Payment();
        payment.setId(paymentId);

        PaymentExecution paymentExecution = new PaymentExecution();
        paymentExecution.setPayerId("eTherapists");

        try {

            APIContext context = new APIContext(CLIENT_ID, SECRET, "sandbox");
            Payment createdPayment = payment.execute(context, paymentExecution);

            if (createdPayment != null) {

                response.put("status", "success");
                response.put("payment", createdPayment);
            }

        } catch (PayPalRESTException e) {
            System.err.println(e.getDetails());
        }

        return response;
    }
}

Когда я выполняю запрос cURL,

$ curl -i -X POST -H "Content-Type:application/json" -d "{ \"id\": \"1\", \"name\": \"Maria\", \"countryName\": \"Philippine \", \"currencyName\": \"PHP\"}" http://localhost:8080/api/v1/users//make-paypal-payment

я получаю ответ,

HTTP/1.1 201 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 15 Apr 2019 11:54:05 GMT

Это то, что я понял из кода (ниже)из сеанса отладки,

        catch (PayPalRESTException e) {
            System.err.println(e.getDetails());
        }

Вывод отладки,

response-code: 404  details: name: INVALID_RESOURCE_ID  message: Requested resource ID was not found.   details: null   debug-id: db7821c6c369a information-link: https://developer.paypal.com/docs/api/payments/#errors

Ошибка ясно, что пользователь не существует INVALID_RESOURCE_ID.Как мне написать код, чтобы я мог его внутренне протестировать?У меня нет пользовательского банкомата, а просто развиваюсь.

Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...