/// <summary> /// Serializes the given document as XML. /// </summary> /// <param name="bySquareDocument">The by square document.</param> public string SerializeAsXml(BySquareDocument bySquareDocument) { using var ms = new MemoryStream(); using (var xtw = XmlWriter.Create(ms, new XmlWriterSettings() { ConformanceLevel = ConformanceLevel.Auto, CloseOutput = false, Indent = true, IndentChars = " ", OmitXmlDeclaration = true, })) { var ds = new XmlSerializer(bySquareDocument.GetType()); ds.Serialize(xtw, bySquareDocument); xtw.Flush(); } ms.Position = 0; using var sr = new StreamReader(ms); { return(sr.ReadToEnd()); } }
/// <summary> /// Serializes given document as a QR string. /// </summary> /// <param name="document">A BySquareDocument instance.</param> /// <returns> /// QR string. /// </returns> /// <remarks> /// Sample response: /// <StringSetOfCodes> /// <PayBySquare>00048000BEH98QN092PSOB1EKLG0V9OQ0L0QAK2M303J09BRUEOSHJHRN8UH0JUEAVQLBQQ9L88MHK264TTJLOHE056AM3MCD3PB600</PayBySquare> /// <ItemsBySquare /> /// </StringSetOfCodes> /// </remarks> public string Encode(BySquareDocument document) { // wrap in BySquareXmlDocuments object var url = this.Configuration.Url; var documents = new BySquareXmlDocuments(document) { Username = this.Configuration.Username, Password = this.Configuration.Password, ServiceId = this.Configuration.ServiceId, ServiceUserId = this.Configuration.ServiceUserId, }; // send to bysquare.com web api generator var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(this.Serializer.SerializeAsXml(documents), Encoding.UTF8, "text/xml") }; try { using var client = new HttpClient(); var response = client.SendAsync(request, HttpCompletionOption.ResponseContentRead).Result; var responseString = response.Content.ReadAsStringAsync().Result; var setOfCodes = this.Serializer.DeserializeSetOfCodes(responseString); return(setOfCodes.PayBySquare); } catch (Exception ex) { this.Logger?.LogError(ex, "bysquare.com Web API error"); return(null); } }
/// <summary> /// Encodes given document as QR string. /// </summary> /// <param name="document">The document.</param> /// <returns>QR string</returns> /// <exception cref="NotSupportedException">Unknown type of BySquareDocument.</exception> /// <exception cref="InvalidDataException">PayBySquare limit is 550 utf-8 characters.</exception> public string Encode(BySquareDocument document) { string serializedDocument = document switch { Pay pay => this.Encode(pay), Invoice invoice => this.Encode(invoice), _ => throw new NotSupportedException("Unknown type of BySquareDocument."), }; if (serializedDocument.Length > MaxLength) { throw new InvalidDataException("PayBySquare limit is 550 utf-8 characters."); } var payload = Encoding.UTF8.GetBytes(serializedDocument); return(this.EncodeBytes(payload)); }