由于Stripe.Net
在PCL方面不再起作用,我们需要使用DependencyServices<>
。但是,当我试图从信用卡信息中生成令牌时,似乎......它在文档中缺失,我只是在网络上或在文档中找不到任何内容,这是正常的吗?
我想实现这样的目标:
public string CardToToken()
{
var card = new Card()
{
Number = "4242424242424242",
ExpiryMonth = 12,
ExpiryYear = 16,
CVC = 123
};
try
{
token = await Stripe.CreateToken(card);
}
catch (Exception ex)
{
return null;
}
return token;
}
那么我只需将它发送到我的服务器即可。想要实现轻松的想法吗?这是我需要完成项目的最后一点......
这个例子在我的Android端。
感谢任何帮助......
我找到了一个很好的解决方法(目前只有Android,但我会尽快更新UWP的答案)。
步骤1
Stripe.Net
,我的意思是Android,iOS,UWP,而不是PCL部分(你共享的代码)。第2步
您将获得的信息应存储在该类中,我确实喜欢这样,当然,您可以通过其他方式实现它。
在您的PCL中,申报信用卡.s:
public class CreditCard
{
public string Numbers { get; set; }
public string HolderName { get; set; }
public string Month { get; set; }
public string Year { get; set; }
public string Cvc { get; set; }
/// <summary>
/// Initializes a new instance of the CreditCard class.
/// </summary>
public CreditCard()
{
Numbers = "";
Month = "";
Year = "";
Cvc = "";
HolderName = "";
}
/// <summary>
/// Verifies the credit card info.
/// However, if the data provided aren't matching an existing card,
/// it will still return `true` since that function only checks the basic template of a credit card data.
/// </summary>
/// <returns>True if the card data match the basic card information. False otherwise</returns>
public bool VerifyCreditCardInfo()
{
if (Numbers == ""
|| Month == ""
|| Year == ""
|| Cvc == ""
|| HolderName == "")
return false;
try
{
int month = 0;
int year = 0;
int cvc = 0;
if (!Int32.TryParse(Month, out month)
|| !Int32.TryParse(Year, out year)
|| !Int32.TryParse(Year, out cvc))
return false;
if (month < 1 || month > 12)
return false;
else if (year < 1990 || year > new DateTime().Year)
return false;
else if (Cvc.Length != 3)
return false;
}
catch (Exception) { return false; }
return true;
}
}
第3步
DependencyServices<>
。所以我们在共享代码(PCL)中使用接口IStripeServices
,并在子平台中使用继承它的服务。在您的PCL中,声明一个IStripeServices
public interface IStripeServices
{
string CardToToken(CreditCard creditCard);
}
Android:像这样创建一个StripeServices类:
public class StripeServices : IStripeServices
{
public string CardToToken(CreditCard creditCard)
{
var stripeTokenCreateOptions = new StripeTokenCreateOptions
{
Card = new StripeCreditCardOptions
{
Number = creditCard.Numbers,
ExpirationMonth = Int32.Parse(creditCard.Month),
ExpirationYear = Int32.Parse(creditCard.Year),
Cvc = creditCard.Cvc,
Name = creditCard.HolderName
}
};
var tokenService = new StripeTokenService();
var stripeToken = tokenService.Create(stripeTokenCreateOptions);
return stripeToken.Id;
}
}
第4步
您现在可以使用共享代码(PCL)中的这段代码从信用卡生成Stripe令牌
if (CreditCardData.VerifyCreditCardInfo())
string cardToken = DependencyService.Get<IStripeServices>().CardToToken(CreditCardData);
else
Debug.WriteLine("The information are either missing or wrong.");
我希望这个答案会有所帮助,我会尽快在公共github repo上为那些想要测试它的人创建一个解决方案