You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否集成Paytm网关/API实现钱包间转账?求Asp.net Core+Angular集成指引

Can I integrate Paytm Gateway/API for wallet-to-wallet transfers with ASP.NET Core Web API + Angular?

Great question! The short answer is yes — Paytm provides dedicated APIs for wallet-to-wallet transfers, which works perfectly with your ASP.NET Core backend and Angular frontend stack. Let’s walk through a step-by-step integration guide tailored to your setup.

Feasibility Confirmation

Paytm’s Merchant Wallet Transfer API is designed specifically for facilitating peer-to-peer or merchant-to-user wallet transfers. It supports both sandbox (testing) and production environments, so you can safely iterate before going live.


Integration Guide

Backend (ASP.NET Core Web API)

Follow these steps to build the backend logic:

  1. Set up Paytm Merchant Credentials
    First, get your unique MID (Merchant ID) and Merchant Key from the Paytm Merchant Dashboard. Store these securely in your appsettings.json:

    "PaytmSettings": {
      "MID": "YOUR_MERCHANT_ID",
      "MerchantKey": "YOUR_MERCHANT_SECRET_KEY",
      "Environment": "Sandbox" // Switch to "Production" once ready
    }
    
  2. Create Transfer Request Models
    Define a model to map the transfer data, matching Paytm’s API requirements:

    public class PaytmTransferRequest
    {
        public string SenderWalletId { get; set; } // Or use user's linked Paytm wallet ID
        public string ReceiverWalletId { get; set; }
        public decimal Amount { get; set; }
        public string TransactionId { get; set; } // Unique ID generated by your system
        public string Timestamp { get; set; } = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
    }
    
  3. Generate Request Signature
    Paytm requires all API requests to be signed with HMAC-SHA256 for security. Create a helper method to generate the signature:

    private string GeneratePaytmSignature(Dictionary<string, string> parameters, string merchantKey)
    {
        // Sort parameters alphabetically (required by Paytm)
        var sortedParams = parameters.OrderBy(k => k.Key).ToDictionary(k => k.Key, v => v.Value);
        var signatureString = string.Join("|", sortedParams.Values) + "|" + merchantKey;
        
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(merchantKey));
        var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(signatureString));
        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }
    
  4. Call Paytm Transfer API
    Use HttpClient to send the signed request to Paytm’s gateway. Validate the response signature to ensure authenticity:

    public async Task<IActionResult> InitiateTransfer([FromBody] TransferRequestDto frontendRequest)
    {
        // Map frontend data to Paytm request model
        var paytmRequest = new PaytmTransferRequest
        {
            SenderWalletId = frontendRequest.SenderWallet,
            ReceiverWalletId = frontendRequest.ReceiverWallet,
            Amount = frontendRequest.Amount,
            TransactionId = Guid.NewGuid().ToString()
        };
    
        // Convert request to parameters dictionary
        var paramsDict = new Dictionary<string, string>
        {
            { "MID", _paytmSettings.MID },
            { "TRANSACTION_ID", paytmRequest.TransactionId },
            { "SENDER_WALLET_ID", paytmRequest.SenderWalletId },
            { "RECEIVER_WALLET_ID", paytmRequest.ReceiverWalletId },
            { "AMOUNT", paytmRequest.Amount.ToString("F2") },
            { "TIMESTAMP", paytmRequest.Timestamp }
        };
    
        // Generate signature and add to params
        paramsDict.Add("SIGNATURE", GeneratePaytmSignature(paramsDict, _paytmSettings.MerchantKey));
    
        // Send request to Paytm gateway
        var httpClient = _httpClientFactory.CreateClient();
        var response = await httpClient.PostAsync(
            _paytmSettings.Environment == "Sandbox" 
                ? "https://sandbox.paytm.com/wallet/transfer" 
                : "https://secure.paytm.com/wallet/transfer",
            new FormUrlEncodedContent(paramsDict)
        );
    
        // Parse and validate response signature
        var responseContent = await response.Content.ReadFromJsonAsync<PaytmTransferResponse>();
        if (ValidateResponseSignature(responseContent, _paytmSettings.MerchantKey))
        {
            return Ok(new { Status = responseContent.Status, Message = responseContent.Message });
        }
        else
        {
            return BadRequest("Invalid response signature from Paytm");
        }
    }
    
  5. Expose API Endpoint
    Create a controller endpoint for your Angular frontend to call:

    [ApiController]
    [Route("api/paytm")]
    public class PaytmController : ControllerBase
    {
        // Inject IOptions<PaytmSettings> and IHttpClientFactory
        public async Task<IActionResult> Transfer([FromBody] TransferRequestDto request)
        {
            // Call the initiate transfer logic above
        }
    }
    

Frontend (Angular)

Integrate the transfer flow into your Angular app:

  1. Create Transfer Form Component
    Build a reactive form to collect user input:

    <form [formGroup]="transferForm" (ngSubmit)="onSubmit()">
      <div>
        <label>Receiver Wallet ID:</label>
        <input formControlName="receiverWallet" type="text" required>
      </div>
      <div>
        <label>Amount (₹):</label>
        <input formControlName="amount" type="number" min="1" step="0.01" required>
      </div>
      <button type="submit" [disabled]="transferForm.invalid">Initiate Transfer</button>
    </form>
    
  2. Implement API Call
    Use Angular’s HttpClient to send the form data to your backend:

    import { HttpClient } from '@angular/common/http';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    @Component({ /* Component metadata */ })
    export class WalletTransferComponent {
      transferForm: FormGroup;
    
      constructor(private fb: FormBuilder, private http: HttpClient) {
        this.transferForm = this.fb.group({
          receiverWallet: ['', Validators.required],
          amount: ['', [Validators.required, Validators.min(1)]]
        });
      }
    
      onSubmit() {
        if (this.transferForm.valid) {
          this.http.post('/api/paytm/transfer', this.transferForm.value)
            .subscribe({
              next: (res: any) => {
                alert(`Transfer ${res.Status}: ${res.Message}`);
                this.transferForm.reset();
              },
              error: (err) => {
                alert(`Transfer failed: ${err.error.Message || 'Unknown error'}`);
              }
            });
        }
      }
    }
    

Key Things to Remember

  • Test in Sandbox First: Always use Paytm’s sandbox environment to test transfers without real money. You can create test wallets in the merchant dashboard.
  • Signature Validation is Non-Negotiable: Both outgoing requests and incoming responses must have valid signatures to prevent fraud.
  • Error Handling: Paytm returns specific error codes (e.g., INSUFFICIENT_BALANCE, INVALID_WALLET_ID) — map these to user-friendly messages in your frontend.
  • Logging: Log all transaction details (request, response, timestamps) for audit and troubleshooting purposes.

内容的提问来源于stack exchange,提问作者Weddy Go

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:17:44