Is there any sample for PayPal IPN

后端 未结 5 1187
半阙折子戏
半阙折子戏 2021-02-05 20:47

I have an Asp.Net WEB API 2 project and I would like to implement an Instant Payment Notification (IPN) listener controller.

I can\'t find any example and nuget package

5条回答
  •  不要未来只要你来
    2021-02-05 21:42

    I was also looking for a solution similar to the OP's original question Is there any IPN listener controller example? At least a PaypalIPNBindingModel to bind the Paypal query. and I got to this page. I tried the other solutions mentioned in this thread, they all worked but I really need the PayPal query-to-model solution so I googling until I stumbled on Carlos Rodriguez's Creating a PayPal IPN Web API Endpoint blogpost.

    Here's an overview on what Carlos did:

    1. Create a model. Base the properties you'll define in the model from the ipn response you'll get from PayPal.

      public class IPNBindingModel
      {
          public string PaymentStatus { get; set; }
          public string RawRequest { get; set; }
          public string CustomField { get; set; }    
      }
      
    2. Create a PayPal Validator class.

      public class PayPalValidator
      {
          public bool ValidateIPN(string body)
          {
              var paypalResponse = GetPayPalResponse(true, body);
              return paypalResponse.Equals("VERIFIED");
          }
      
          private string GetPayPalResponse(bool useSandbox, string rawRequest)
          {
              string responseState = "INVALID";
              string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/"
              : "https://www.paypal.com/";
      
              ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
              using (var client = new HttpClient())
              {
                  client.BaseAddress = new Uri(paypalUrl);
                  client.DefaultRequestHeaders.Accept.Clear();
                  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                  HttpResponseMessage response = client.PostAsJsonAsync("cgi-bin/webscr", "").Result;
                  if (response.IsSuccessStatusCode)
                  {
                      rawRequest += "&cmd=_notify-validate";
                      HttpContent content = new StringContent(rawRequest);
                      response = client.PostAsync("cgi-bin/webscr", content).Result;
                      if (response.IsSuccessStatusCode)
                      {
                          responseState = response.Content.ReadAsStringAsync().Result;
                      }
                  }
              }
              return responseState;
          }
      }
      
    3. Create your controller.

      [RoutePrefix("paypal")]
      public class PayPalController : ApiController
      {
          private PayPalValidator _validator;
      
          public PayPalController()
          {
             this._validator = new PayPalValidator();
          }
      
          [HttpPost]
          [Route("ipn")]
          public void ReceiveIPN(IPNBindingModel model)
          {
              if (!_validator.ValidateIPN(model.RawRequest)) 
                  throw new Exception("Error validating payment");
      
              switch (model.PaymentStatus)
              {
      
                  case "Completed":
                      //Business Logic
                      break;
              }
         }
      }
      
    4. Create a model binder that will define how Web Api will automatically create the model for you.

      public class IPNModelBinder : IModelBinder
      {
          public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
          {
              if (bindingContext.ModelType != typeof(IPNBindingModel))
              {
                 return false;
              }
          var postedRaw = actionContext.Request.Content.ReadAsStringAsync().Result;
      
          Dictionary postedData = ParsePaypalIPN(postedRaw);
          IPNBindingModel ipn = new IPNBindingModel
          {
              PaymentStatus = postedData["payment_status"],
              RawRequest = postedRaw,
              CustomField = postedData["custom"]
          };
      
          bindingContext.Model = ipn;
          return true;
      }
      
      private Dictionary ParsePaypalIPN(string postedRaw)
      {
          var result = new Dictionary();
          var keyValuePairs = postedRaw.Split('&');
          foreach (var kvp in keyValuePairs)
          {
              var keyvalue = kvp.Split('=');
              var key = keyvalue[0];
              var value = keyvalue[1];
              result.Add(key, value);
          }
      
          return result;
      }
      }
       }
      
    5. Register your model binder to WebApiConfig.cs. config.BindParameter(typeof(IPNBindingModel), new IPNModelBinder());

    Hope this helps somebody else. Thank you Carlos Rodriguez for your amazing code.

提交回复
热议问题