Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Yodapp/78263e2ee2e92413f0f67e9a4cebd350 to your computer and use it in GitHub Desktop.
Save Yodapp/78263e2ee2e92413f0f67e9a4cebd350 to your computer and use it in GitHub Desktop.
C# hjälp class för Swish API för e-handel, fungerande
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
namespace WebShop.Helpers
{
public class SwishAPIHelper
{
public static string StartSwishPayment(string phonenumber, int amount, string message)
{
try
{
string DataToPost = "{ \"payeePaymentReference\": \"0123456789\", " +
"\"callbackUrl\": \"https://datorbutik.se/Swish/Callback/\", " +
"\"payerAlias\": \"" + phonenumber + "\", " +
"\"payeeAlias\": \"1231181189\", " +
"\"amount\": \"" + amount + "\", " +
"\"currency\": \"SEK\", " +
"\"message\": \"" + message + "\" }";
string URL = "https://mss.swicpc.bankgirot.se/swish-cpcapi/api/v1/paymentrequests/";
//ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
//Cert Challenge URL
Uri requestURI = new Uri(URL);
//Create the Request Object
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestURI);
//Set the Request Object parameters
req.ContentType = "application/json; charset=UTF-8";
req.Method = "POST";
req.ProtocolVersion = HttpVersion.Version10;
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(DataToPost);
req.ContentLength = postBytes.Length;
string path = HttpContext.Current.Server.MapPath("~/App_Data/SwishMerchantTestCertificate1231181189.p12");
X509Certificate cert = new X509Certificate2(path, "swish", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
req.ClientCertificates.Add(cert);
Stream requestStream = req.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
try
{
WebResponse response = req.GetResponse();
String result = "";
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
HttpWebResponse httpResponse = (HttpWebResponse)response;
return "Status code: " + httpResponse.StatusCode + " - Content: " + result;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
//Log.Information("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
return "Error code: " + httpResponse.StatusCode + " - Content: " + text;
}
}
}
}
catch (Exception ex)
{
return "Exception: " + ex.ToString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment