Use NVP/SOAP Api from PayPal

This commit is contained in:
2017-05-24 23:36:49 +02:00
parent 0aa9ac202b
commit 938159a55c
33 changed files with 2385 additions and 634 deletions

View File

@ -2,7 +2,6 @@ using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.Localization;
using PayPal.Api;
namespace Yavsc.ApiControllers
@ -20,8 +19,10 @@ namespace Yavsc.ApiControllers
using Helpers;
using Microsoft.Data.Entity;
using Models.Payment;
using Models.Relationship;
using Newtonsoft.Json;
using PayPal.PayPalAPIInterfaceService.Model;
using Yavsc.Models.Haircut.Views;
using Microsoft.AspNet.Http;
[Route("api/haircut")]
public class HairCutController : Controller
@ -67,79 +68,185 @@ namespace Yavsc.ApiControllers
{
var uid = User.GetUserId();
var now = DateTime.Now;
var result = _context.HairCutQueries.Where(
var result = _context.HairCutQueries
.Include(q => q.Prestation)
.Include(q => q.Client)
.Include(q => q.PerformerProfile)
.Include(q => q.Location)
.Where(
q => q.ClientId == uid
&& q.EventDate > now
&& ( q.EventDate > now || q.EventDate == null )
&& q.Status == QueryStatus.Inserted
);
).Select(q => new HaircutQueryClientInfo(q));
return Ok(result);
}
// GET: api/HairCutQueriesApi/5
[HttpGet("{id}", Name = "GetHairCutQuery")]
public async Task<IActionResult> GetHairCutQuery([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null)
{
return HttpNotFound();
}
return Ok(hairCutQuery);
}
// PUT: api/HairCutQueriesApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutHairCutQuery([FromRoute] long id, [FromBody] HairCutQuery hairCutQuery)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
if (id != hairCutQuery.Id)
{
return HttpBadRequest();
}
_context.Entry(hairCutQuery).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HairCutQueryExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
[HttpPost]
public IActionResult PostQuery(HairCutQuery query)
public async Task<IActionResult> PostQuery(HairCutQuery hairCutQuery)
{
var uid = User.GetUserId();
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
_context.HairCutQueries.Add(query);
_context.Update(uid);
return Ok();
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
_context.HairCutQueries.Add(hairCutQuery);
try
{
await _context.SaveChangesAsync(uid);
}
catch (DbUpdateException)
{
if (HairCutQueryExists(hairCutQuery.Id))
{
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetHairCutQuery", new { id = hairCutQuery.Id }, hairCutQuery);
}
[HttpPost("createpayment/{id}")]
public async Task<IActionResult> CreatePayment(long id)
{
APIContext apiContext = null;
HairCutQuery query = await _context.HairCutQueries.Include(q => q.Client).
Include(q => q.Client.PostalAddress).Include(q => q.Prestation).Include(q=>q.Regularisation)
.SingleAsync(q => q.Id == id);
if (query.PaymentId!=null)
return new BadRequestObjectResult(new { error = "An existing payment process already exists" });
query.SelectedProfile = _context.BrusherProfile.Single(p => p.UserId == query.PerformerId);
SetExpressCheckoutResponseType payment = null;
try {
apiContext = PayPalHelpers.CreateAPIContext();
payment = Request.CreatePayment("HairCutCommand", query, "sale", _logger);
}
catch (PayPal.IdentityException ex) {
_logger.LogError(ex.Response);
catch (Exception ex) {
_logger.LogError(ex.Message);
return new HttpStatusCodeResult(500);
}
if (apiContext==null) {
if (payment==null) {
_logger.LogError("Error doing SetExpressCheckout, aborting.");
_logger.LogError(JsonConvert.SerializeObject(Startup.PayPalSettings));
throw new Exception("No PayPal Api context");
return new HttpStatusCodeResult(500);
}
var payment = Request.CreatePayment("HairCutCommand",apiContext, query, "sale", _logger);
switch (payment.state)
switch (payment.Ack)
{
case "created":
case "approved":
case AckCodeType.SUCCESS:
case AckCodeType.SUCCESSWITHWARNING:
{
var dbinfo = new PaypalPayment
var dbinfo = new PayPalPayment
{
ExecutorId = User.GetUserId(),
PaypalPayerId = payment.payer.payer_info?.payer_id,
PaypalPaymentId = payment.id,
State = payment.state
PaypalPayerId = payment.Token,
CreationToken = null,
State = "inserted"
};
var links = payment.links.Select
(
l=> new Link {
HRef = l.href,
Rel = l.rel,
Method = l.method
});
_context.PaypalPayments.Add(dbinfo);
query.PaymentId = payment.id;
await _context.SaveChangesAsync(User.GetUserId());
}
break;
case "failed":
default:
_logger.LogError(JsonConvert.SerializeObject(payment));
return new BadRequestObjectResult(payment);
default: throw new NotImplementedException();
}
return Json(payment);
return Json(new { token = payment.Token });
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteHairCutQuery([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null)
{
return HttpNotFound();
}
_context.HairCutQueries.Remove(hairCutQuery);
await _context.SaveChangesAsync();
return Ok(hairCutQuery);
}
private bool HairCutQueryExists(long id)
{
return _context.HairCutQueries.Count(e => e.Id == id) > 0;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
}
}

View File

@ -1,173 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Haircut;
using Yavsc.Models.Haircut.Views;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/haircutquery")]
public class HairCutQueriesApiController : Controller
{
private ApplicationDbContext _context;
public HairCutQueriesApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/HairCutQueriesApi
// Get the active queries for current
// user, as a client
[HttpGet]
public async Task<IActionResult> GetHairCutQueries()
{
IEnumerable<HaircutQueryClientInfo> info = null;
await Task.Run(
() =>
{
var bi = DateTime.Now.AddDays(-15);
var uid = User.GetUserId();
var dat = _context.HairCutQueries
.Include(q => q.Prestation)
.Include(q => q.Client)
.Include(q => q.PerformerProfile)
.Include(q => q.Location)
.Where(q => q.ClientId == uid
&& (q.EventDate == null || q.EventDate > bi))
;
info = dat.ToArray().Select(q => new HaircutQueryClientInfo(q));
});
return Ok(info);
}
// GET: api/HairCutQueriesApi/5
[HttpGet("{id}", Name = "GetHairCutQuery")]
public async Task<IActionResult> GetHairCutQuery([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null)
{
return HttpNotFound();
}
return Ok(hairCutQuery);
}
// PUT: api/HairCutQueriesApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutHairCutQuery([FromRoute] long id, [FromBody] HairCutQuery hairCutQuery)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
if (id != hairCutQuery.Id)
{
return HttpBadRequest();
}
_context.Entry(hairCutQuery).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HairCutQueryExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/HairCutQueriesApi
[HttpPost]
public async Task<IActionResult> PostHairCutQuery([FromBody] HairCutQuery hairCutQuery)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
_context.HairCutQueries.Add(hairCutQuery);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (HairCutQueryExists(hairCutQuery.Id))
{
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetHairCutQuery", new { id = hairCutQuery.Id }, hairCutQuery);
}
// DELETE: api/HairCutQueriesApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteHairCutQuery([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null)
{
return HttpNotFound();
}
_context.HairCutQueries.Remove(hairCutQuery);
await _context.SaveChangesAsync();
return Ok(hairCutQuery);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool HairCutQueryExists(long id)
{
return _context.HairCutQueries.Count(e => e.Id == id) > 0;
}
}
}

View File

@ -1,14 +1,10 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using PayPal.Api;
using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Billing;
using Yavsc.ViewModels.PayPal;
namespace Yavsc.ApiControllers
{
@ -16,57 +12,23 @@ namespace Yavsc.ApiControllers
public class PaymentApiController : Controller
{
private ApplicationDbContext dbContext;
PayPalSettings paymentSettings;
private SiteSettings siteSettings;
private readonly ILogger _logger;
public PaymentApiController(
ApplicationDbContext dbContext,
IOptions<PayPalSettings> paypalSettingsReceiver,
IOptions<SiteSettings> siteSettingsReceiver,
ILoggerFactory loggerFactory)
{
this.dbContext = dbContext;
paymentSettings = paypalSettingsReceiver.Value;
siteSettings = siteSettingsReceiver.Value;
_logger = loggerFactory.CreateLogger<PaymentApiController>();
}
public async Task<IActionResult> Info(string paymentId)
public async Task<IActionResult> Info(string paymentId, string token)
{
var result = new PaymentInfo {
DbContent = await dbContext.PaypalPayments.SingleAsync(
p=>p.PaypalPaymentId==paymentId)
};
await Task.Run( () => {
var apiContext = PayPalHelpers.CreateAPIContext();
result.FromPaypal = Payment.Get(apiContext,paymentId);
});
return Ok(result);
}
[HttpPost("execute")]
public async Task<IActionResult> Execute(string paymentId, string payerId)
{
Payment result=null;
await Task.Run( () => {
var apiContext = PayPalHelpers.CreateAPIContext();
var payment = Payment.Get(apiContext,paymentId);
var execution = new PaymentExecution();
execution.payer_id = payerId;
execution.transactions = payment.transactions;
result = payment.Execute(apiContext,execution);
});
return Ok(result);
}
[HttpPost("create"),AllowAnonymous]
public IActionResult Create()
{
var apiContext = PayPalHelpers.CreateAPIContext();
Payment result= Request.CreatePayment("Command",apiContext,new Estimate());
return Ok(Payment.Create(apiContext,result));
var details = await dbContext.GetCheckoutInfo(token);
_logger.LogInformation(JsonConvert.SerializeObject(details));
return Ok(details);
}
}