PayPal REST开发

  PayPal REST是PayPal提供的新的集成接口,现在来看看怎么集成REST。  

  1>Register with PayPal and get your credentials。

    登录网站https://developer.paypal.com/

    

 

    

    

    

    

    获取到了Credentials,看下怎么集成REST,网址https://developer.paypal.com/webapps/developer/docs/api/

    下载实例代码:

    

    

    按实例代码开发,解压下载文件。

    配置web.config,paypal节点放在configSections后面,修改ClientID和ClientSecret     

<configSections>
    <section name="paypal" type="PayPal.Manager.SDKConfigHandler, PayPalCoreSDK"/>
  </configSections>     

 <!-- PayPal SDK config -->
  <paypal>
    <settings>
      <add name="endpoint" value="https://api.sandbox.paypal.com/"/>
      <add name="oauth.EndPoint" value="https://api.sandbox.paypal.com/"/>
      <add name="connectionTimeout" value="360000"/>
      <!-- The number of times a request must be retried if the API endpoint is unresponsive -->
      <add name="requestRetries" value="1"/>
      <add name="ClientID" value="EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM"/>
      <add name="ClientSecret" value="EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"/>
    </settings>
  </paypal>

   添加引用:

    

    

 PayPal账户支付      

    复制代码到自己的action,做些许修改。实例如下:      

 public ActionResult PayPalREST()
        {
            Payment pymnt = null;

            //根据ClientID 和  ClientSecret 获取accessToken
            string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

            //根据accessToken获取 API 上下文
            APIContext apiContext = new APIContext(accessToken);


            //如果PayerID不为null,是从PayPal跳转回来的,执行支付
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                PaymentExecution pymntExecution = new PaymentExecution();
                pymntExecution.payer_id = Request.Params["PayerID"];

                Payment executedPayment = pymnt.Execute(apiContext,pymntExecution);
                
            }

            //否则,创建支付,跳转到PayPal去
            else
            {
                //Payer
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                //会跳地址
                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + Url.Action("PayPalREST", "PayPal");
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "?guid=" + guid;
                redirUrls.return_url = baseURI + "?guid=" + guid;

                // Details
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

                //Amount
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "100";
                amnt.details = details;

                //Transaction
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;

                transactionList.Add(tran);

                //Payment
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                // The return object contains the status;
                Payment createdPayment = pymnt.Create(apiContext);
                var links = createdPayment.links.GetEnumerator();

                while (links.MoveNext())
                {
                    Links lnk = links.Current;
                    if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        Session.Add(guid, createdPayment.id);
                        return Redirect(lnk.href);
                    }
                }
                
            }
            return View();
        
        }

    这里有两个需要注意的地方,第一是回跳地址,要写仔细,稍微不同都会出错。第二是跳转之前的Session.Add,这里如果忘记添加的话,在从PayPal跳转回来,就会出错,无法完成支付。

 信用卡支付

    信用卡支付与账户支付大同小异,找到信用卡支付的代码,做些修改就好了。实例代码如下:    

public ActionResult PayPalRESTREST()
        {
            // ###Address
            Address billingAddress = new Address();
            billingAddress.city = "Johnstown";
            billingAddress.country_code = "US";
            billingAddress.line1 = "52 N Main ST";
            billingAddress.postal_code = "43210";
            billingAddress.state = "OH";

            // ###CreditCard
            CreditCard crdtCard = new CreditCard();
            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2 = "874";
            crdtCard.expire_month = 11;
            crdtCard.expire_year = 2018;
            crdtCard.first_name = "Joe";
            crdtCard.last_name = "Shopper";
            crdtCard.number = "4417119669820331";
            crdtCard.type = "visa";

            // ###Details
            Details details = new Details();
            details.shipping = "1";
            details.subtotal = "5";
            details.tax = "1";

            // ###Amount
            Amount amnt = new Amount();
            amnt.currency = "USD";
            // Total must be equal to sum of shipping, tax and subtotal.
            amnt.total = "7";
            amnt.details = details;

            // ###Transaction
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "This is the payment transaction description.";

            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);

            // ###FundingInstrument
            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;

            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // ###Payment
            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

                // ###AccessToken
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                // ### Api Context
                APIContext apiContext = new APIContext(accessToken);
                Payment createdPayment = pymnt.Create(apiContext);

                return View();
        }

退款    

      public ActionResult RestRefund()
            {
                // ###AccessToken
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                Sale sale = Sale.Get(accessToken, "5UB84317A9854725P");
               
                Amount amount = new Amount();
                amount.total = "10";
                amount.currency = "USD";            
                 

                Refund refund = new Refund();
                refund.amount = amount;
Refund newRefund
= sale.Refund(accessToken, refund); return View(); }

    这里需要一个transactionId和退款金额,在信用卡付款和PayPal账户付款执行完的那个对象可以找到,要存下来,具体地方是executedPayment.transactions[0].related_resources[0].sale.id;

 

 

posted @ 2013-07-09 11:29  小飞的DD  阅读(7824)  评论(1编辑  收藏  举报