如何在C#Winforms应用程序中发送PayPal REST API退款?
我在网上找到的关于在C#中实现PayPal REST API的文档很少 我已经通过了获取访问令牌的第一步,但我一直看到发送API调用的方法相互冲突,我尝试过的方法都不起作用 以下是我当前的代码:如何在C#Winforms应用程序中发送PayPal REST API退款?,c#,winforms,paypal,paypal-rest-sdk,C#,Winforms,Paypal,Paypal Rest Sdk,我在网上找到的关于在C#中实现PayPal REST API的文档很少 我已经通过了获取访问令牌的第一步,但我一直看到发送API调用的方法相互冲突,我尝试过的方法都不起作用 以下是我当前的代码: private async void cmdRefund_Click(object sender, EventArgs e) { //var apiContext = Configuration.GetAPIContext();
private async void cmdRefund_Click(object sender, EventArgs e)
{
//var apiContext = Configuration.GetAPIContext();
string AccessToken;
string Nonce;
string AppID;
string TokenType;
try
{
// ClientId of your Paypal app API
//This is the live ID
string APIClientId = "AZxxxx-8";
//this is the live secret Key
string APISecret = "Exxxx39";
using (var client = new HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
//this is the live url
var url = new Uri("https://api.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var resp = await webresponse.Content.ReadAsStringAsync();
MessageBox.Show(resp);
if (resp.IndexOf("access_token") == -1)
{
MessageBox.Show("PayPal Authorization Failed.");
return;
}
AccessToken = resp.Substring(resp.IndexOf("access_token") + 15);
AccessToken = AccessToken.Substring(0, AccessToken.IndexOf("\""));
Nonce = resp.Substring(resp.IndexOf("nonce") + 8);
Nonce = Nonce.Substring(0, Nonce.IndexOf("\""));
AppID = resp.Substring(resp.IndexOf("app_id") + 9);
AppID = AppID.Substring(0, AppID.IndexOf("\""));
TokenType = resp.Substring(resp.IndexOf("token_type") + 13);
TokenType = TokenType.Substring(0, TokenType.IndexOf("\""));
MessageBox.Show("Access Token: \r\n" + AccessToken + "\r\nNonce:\r\n" + Nonce + "\r\nAppID:\r\n" + AppID + "\r\nToken Type:\r\n" + TokenType);
// response will deserialized using Jsonconver
//return JsonConvert.DeserializeObject<PayPalGetTokenResponse>(resp);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
//Authorization has been achieved here - now I want to process a refund
var apiContext = new APIContext(AccessToken);
Amount refundAmount = new Amount();
refundAmount.total = "0.01";
refundAmount.currency = "USD";
Refund refund = new Refund();
refund.amount = refundAmount;
string saleId = "9XY489008U7836633";
//*************THIS NEXT LINE CAUSES AN ERROR
Refund refundforreal = Sale.Refund(apiContext, saleId, refund);
//*************
string refundId = refund.id;
}
private async void cmdreturn\u单击(对象发送方,事件参数e)
{
//var apiContext=Configuration.GetAPIContext();
字符串访问令牌;
字符串Nonce;
字符串AppID;
字符串类型;
尝试
{
//Paypal应用程序API的客户端ID
//这是现场ID
字符串APIClientId=“AZxxxx-8”;
//这是现场的秘密钥匙
字符串APISecret=“Exxxx39”;
使用(var client=new HttpClient())
{
var byteArray=Encoding.UTF8.GetBytes(APIClientId+“:”+APISecret);
client.DefaultRequestHeaders.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue(“Basic”,Convert.ToBase64String(byteArray));
//这是实时url
var url=新Uri(“https://api.paypal.com/v1/oauth2/token“,乌里金。绝对);
client.DefaultRequestHeaders.IfModifiedSince=DateTime.UtcNow;
var requestParams=新列表
{
新的KeyValuePair(“授权类型”、“客户端凭据”)
};
var content=newformurlencodedcontent(requestParams);
var webresponse=wait client.PostAsync(url、内容);
var resp=wait webresponse.Content.ReadAsStringAsync();
MessageBox.Show(resp);
if(分别为IndexOf(“访问令牌”)=-1)
{
Show(“贝宝授权失败”);
返回;
}
AccessToken=resp.Substring(resp.IndexOf(“access_token”)+15);
AccessToken=AccessToken.Substring(0,AccessToken.IndexOf(“\”);
Nonce=相应的子字符串(相应的索引(“Nonce”)+8);
Nonce=Nonce.Substring(0,Nonce.IndexOf(“\”);
AppID=相应的子字符串(相应的IndexOf(“app_id”)+9);
AppID=AppID.Substring(0,AppID.IndexOf(“\”);
令牌类型=相应的子字符串(相应的IndexOf(“令牌类型”)+13);
TokenType=TokenType.Substring(0,TokenType.IndexOf(“\”);
MessageBox.Show(“访问令牌:\r\n”+AccessToken+”\r\n一次:\r\n“+Nonce+”\r\nAppID:\r\n”+AppID+“\r\n令牌类型:\r\n”+TokenType);
//响应将使用Jsonconver反序列化
//返回JsonConvert.DeserializeObject(resp);
}
}
catch(System.Exception-ex)
{
MessageBox.Show(例如Message);
返回;
}
//授权已经在这里实现-现在我想处理退款
var apiContext=新的apiContext(AccessToken);
退款金额=新金额();
退款金额:总计=“0.01”;
退款金额。币种=“美元”;
退款=新退款();
退款金额=退款金额;
字符串saleId=“9XY489008U7836633”;
//*************下一行将导致错误
RETURN RETURNFORREAL=Sale.RETURN(apiContext、saleId、RETURN);
//*************
字符串RETURNID=RETURN.id;
}
最后一行导致错误:“PayPal.IdentityException:'远程服务器返回错误:(401)未经授权。”
据我所知,我的访问令牌是完全有效的,但这不起作用。我应该注意到,我试图获取信息和退款的交易不是通过RESTAPI进行的,而是通过我们网站上集成的常规PayPal界面进行的。我不知道这是否会引起问题,但这正是我需要做的
我正在Visual Studio 2017中使用一个用C#编写的Windows窗体应用程序,因为我正在替换一个旧的VB6程序,该程序要求用户在程序中的浏览器中登录PayPal会话,并需要将该程序替换为我们员工既可用又熟悉的程序,通过使用RESTAPI而不是在WebBrowser控件中填充字段的旧方法,更具前瞻性
***********编辑*********-我添加了以下内容作为后续:
我接受了@shamanthGowdraShankaramurthy的建议,使用了邮递员,并设法做了我想做的事情,所以谢谢你——这确实帮助我知道,至少我想做的事情是可能的
我仍然不知道如何用C语言写这篇文章。我想也许我会远离SDK中内置的“退款”对象,转而尝试以其他方式发布
我在Postman中使用的url是:
我将此作为正文发送,以对我的测试交易进行0.01美元退款:
{
“金额”:{
“总计”:“0.01”,
“货币”:“美元”
},
“发票编号”:“INV-1234567”
}"
我用我工作代码中的访问令牌向帖子添加了一个承载令牌授权
最后,在Postman中,我将主体从“Text”更改为“JSON(application/JSON)”
如何合并所有这些元素(URL、我的承载令牌、主体以及主体是json的信息)在C#winforms应用程序中的帖子中?如果其他人正在寻找,答案比我想象的要简单得多。我认为我没有使用PayPal SDK轻松获得的AccessToken,这是在搞砸自己 首先,麦
<!-- PayPal SDK settings -->
<paypal>
<settings>
//specify sandbox or live
<add name="mode" value="sandbox" />
<add name="clientId" value="insert_clientid_key_here" />
<add name="clientSecret" value="Insert_client_secret_key_here" />
</settings>
</paypal>
private void cmdRefund_Click(object sender, EventArgs e)
{
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
Amount refundAmount = new Amount();
refundAmount.total = "0.01";
refundAmount.currency = "USD";
RefundRequest refund = new RefundRefundRequest();
refund.amount = refundAmount;
string saleId = "9XY489008U7836633";
Refund refundforreal = Sale.Refund(apiContext, saleId, refund);
MessageBox.Show("Refund status:" + refundforreal.state + "\r\n" + "Txn #:" + refundforreal.id);
}