DEV Community

Isaac Tonyloi
Isaac Tonyloi

Posted on

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

Top comments (0)