Back to Others
Payment Integration

Phonepay
Integration Guide.

Author

Amruthavalli

Published

December 14, 2023

Phonepay Integration Methods

Calculate Sha256Hash12 Method
Phonepe Make Payment12 API Method
Use in model class values
Pay with phonepe123 Method
1

CalculateSha256Hash12 Method

This method calculates the SHA256 hash of a given payload. It appends the string "###1" to the final result for PhonePe's X-VERIFY header compliance.

C# Backend Integration
private static string CalculateSha256Hash(string payload)
{
    using (SHA256 sha256 = SHA256.Create())
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(payload);
        byte[] hashBytes = sha256.ComputeHash(inputBytes);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }
        sb.Append("###1");
        return sb.ToString();
    }
}
2

Phonepe Make Payment12 API Method

It constructs the API URL, sets up the request payload, and calculates the X-VERIFY header using the CalculateSha256Hash12 method.

It sends the request to the PhonePe API and processes the response, returning the redirection URL to the client.

public async Task PhonepeMakePayment([FromBody] PaymentRequestDto paymentRequest)
{
    var apiUrl = "your localhost sandbox api url";
    var client = new RestClient(apiUrl);
    var url = client.BaseUrl;
    var base64Payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(paymentRequest)));
    string saltKey = "your salt key value";
    var payload = base64Payload + "/pg/v1/pay" + saltKey;
    var verifyHeaderValue = CalculateSha256Hash(payload);
    var request = new RestRequest(Method.POST);
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("X-VERIFY", verifyHeaderValue);
    var jsonRequest = new
    {
        request = base64Payload
    };
    request.AddJsonBody(jsonRequest);
    IRestResponse response = client.Execute(request);
    
    if (response.StatusCode == HttpStatusCode.OK)
    {
        var responseBody = response.Content;
        var responseObject = JObject.Parse(responseBody);
        return Ok(responseObject);
    }
    else
    {
        var errorResponse = response.Content;
        return BadRequest(errorResponse);
    }
}
3

Use in model class values

Request DTO

public class PaymentRequestDto
{
    public string merchantId { get; set; }
    public string merchantTransactionId { get; set; }
    public string merchantUserId { get; set; }
    public decimal amount { get; set; }
    public string redirectUrl { get; set; }
    public string redirectMode { get; set; }
    public string callbackUrl { get; set; }
    public string mobileNumber { get; set; }
    public PaymentInstrumentDto paymentInstrument { get; set; }
}

Response & Redirect Info

public class PaymentResponse
{
    public bool Success { get; set; }
    public string Code { get; set; }
    public string Message { get; set; }
    public PaymentData Data { get; set; }
}

public class InstrumentResponse
{
    public string Type { get; set; }
    public RedirectInfo RedirectInfo { get; set; }
}
4

Pay with phonepe123 Method

This method is triggered when a user initiates a PhonePe payment on the frontend. It generates a unique transaction ID and handles redirection to the payment gateway.

Paywithphonepe123(Package_ID) { var d = new Date(), n = d.getTime(); this.TaxnId = n; const apiUrl = `send your api url`; const httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json', 'X-VERIFY': 'your xverify value', }); this.paymentRequest = { "merchantId": "PGTESTPAYUAT91", "merchantTransactionId": "MT7850590068188114", "merchantUserId": "MUID123", "amount": 10000, "redirectUrl": "https://webhook.site/redirect-url", "redirectMode": "POST", "callbackUrl": "https://webhook.site/callback-url", "mobileNumber": "9999999999", "paymentInstrument": { "type": "PAY_PAGE" } }; this.https.post(apiUrl, this.paymentRequest, { headers: httpHeaders }).subscribe( (response: any) => { let redirectUrl = response.data.instrumentResponse.redirectInfo.url; window.location.href = redirectUrl; localStorage.setItem("TransId", this.TaxnId); }, (error: any) => { console.error('API error:', error); } ); }