DEV Community

Isaac Tonyloi
Isaac Tonyloi

Posted on

2

I tried using the Daraja API with Springboot

<dependency>
  <groupId>com.mpesa</groupId>
  <artifactId>daraja</artifactId>
  <version>1.0.0</version>
</dependency>

Enter fullscreen mode Exit fullscreen mode
import com.mpesa.Daraja;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DarajaConfig {

  private String consumerKey = "your-consumer-key";
  private String consumerSecret = "your-consumer-secret";
  private String shortCode = "your-shortcode";
  private String passkey = "your-passkey";
  private String testUsername = "test-username";
  private String testAmount = "1";

  @Bean
  public Daraja daraja() {
    return new Daraja(consumerKey, consumerSecret, shortCode, passkey, testUsername, testAmount);
  }
}

Enter fullscreen mode Exit fullscreen mode

Initiating a Payment

import com.mpesa.Daraja;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/payments")
public class PaymentController {

  @Autowired
  private Daraja daraja;

  @GetMapping("/initiate")
  public String initiatePayment(@RequestParam String phoneNumber) {
    return daraja.initiatePayment(phoneNumber);
  }

}

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay