国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

目錄
Paypal Checkout JS 支付模式
RESTful API 支付模式
首頁 後端開發(fā) C#.Net教程 Paypal 支付功能的 C# .NET / JS 實現(xiàn)

Paypal 支付功能的 C# .NET / JS 實現(xiàn)

Aug 10, 2018 pm 05:11 PM

說明

最近用到了 Paypal 支付功能,英語一般般的我也不得不硬著頭皮踩一踩這樣的坑。經(jīng)過近乎半個月的作,終于實現(xiàn)了簡單的支付功能,那么首先就說說使用 Paypal 必定要知道的幾點(當(dāng)前日期 2018年08月07日):

1. 你應(yīng)該知道 Paypal 支付功能是支持銀聯(lián)卡的,但是不支持中國買家賬號支付給中國賣家賬號

2. Paypal 接口有兩套,切記,產(chǎn)品環(huán)境和 sandbox 測試環(huán)境不同

3. 測試賬號同樣不能使用中國賬號給中國賬號付款

4. 如果你僅僅想具有固定金額的支付按鈕,用你的 Paypal 商家賬號登錄官網(wǎng),配置頁里面完全可以配置出固定的支付按鈕,然后 Copy 對應(yīng)的 Html 到你的頁面就 OK 了,也就沒有必要通過更復(fù)雜的方式去支付了

Paypal 支付功能的 C# .NET / JS 實現(xiàn)

5. 如果你必須動態(tài)價格和商品信息、或者你要學(xué)習(xí)基本的 Paypal 接口的話,那么就請靜靜的往下看吧

6. 真實環(huán)境支付 Paypal 每一筆都需要收取商家賬號手續(xù)費的,并且手續(xù)費不低,如果你用真實環(huán)境測試,那么一定要記得每一筆都申請退款吧,退款很方便,商家后臺就能直接發(fā)起,退款幾乎是實時的。

Paypal 費用說明:https://www.paypal.com/businesswallet/fees/paypal-fees

Paypal 支付功能的 C# .NET / JS 實現(xiàn)

Paypal 支付功能的 C# .NET / JS 實現(xiàn)

?相關(guān)資料

Paypal 官方地址:https://www.paypal.com/

Paypal 官方測試地址:https://www.sandbox.paypal.com

Paypal 開發(fā)者中心:https://developer.paypal.com/

Paypal API:?https://api.paypal.com

Paypal sandbox API:?https://api.sandbox.paypal.com

Paypal Checkout JS 支付模式

模式圖片:

?Paypal 支付功能的 C# .NET / JS 實現(xiàn)

模式說明:

Checkout JS 模式是一種前端實現(xiàn),使用官方提供的 Checkout.js SDK 實現(xiàn)支付,不需要自己寫直接調(diào)用接口的代碼,相對而言也挺簡單,但是如果你想檢測支付是否成功,你應(yīng)當(dāng)通過調(diào)用接口的方式驗證了。

支付部分代碼:

<p id="paypal-button"></p>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script type="text/javascript">
    paypal.Button.render({
        env: &#39;production&#39;, // production or sandbox 表示產(chǎn)品環(huán)境還是測試環(huán)境
        client: {
            production: &#39;&#39;, // 產(chǎn)品環(huán)境,值為字符串,配置實際商家號的 ClientId
            // sandbox: &#39;&#39;, // 測試環(huán)境,值為字符串,配置商家測試號的 ClientId
        },
        style: {
            size: &#39;medium&#39;,
            color: &#39;black&#39;,
            shape: &#39;pill&#39;,
            label: &#39;paypal&#39;,
            tagline: &#39;false&#39;,
            fundingicons: &#39;true&#39;
        },
        commit: true,
        payment: function (data, actions) {
            return actions.payment.create({
                transactions: [
                    {
                        amount: {
                            total: "0.01",
                            currency: "USD"
                        },
                        description: "測試商品描述",
                        custom: "X00002"
                    }
                ],
                redirect_urls: {
                    return_url: &#39;http://localhost:4478/Success.aspx?type=js&#39;,
                    cancel_url: &#39;http://localhost:4478/Cancel.aspx&#39;
                }
            });
        },
        onAuthorize: function (data, actions) {
            return actions.payment.execute()
                .then(function () {
                    actions.redirect();
                });
        },
        onCancel: function (data, actions) {
            actions.redirect();
        }
    }, &#39;#paypal-button&#39;);
</script>

如果你需要在支付跳轉(zhuǎn)的成功頁再次驗證一下是否支付成功,你需要自己調(diào)用官方提供的 RESTful API,參見下文的 RESTful API 支付模式

RESTful API 支付模式

說明

接口的方式很常見,和支付寶的接口類似,只是使用了 RESTful API 的模式,采用了 Basic Auth 的加密方式。使用接口的模式很常規(guī),我們在頁面點擊按鈕調(diào)用支付接口,彈出支付頁,支付成功跳轉(zhuǎn)到成功頁面,成功頁面再調(diào)用確認(rèn)支付接口確認(rèn)結(jié)果。

支付接口調(diào)用:

using System;
using System.Text;
using System.Web.Script.Serialization;
using cn.lovelong.Paypal.Config;
using cn.lovelong.Paypal.Enums;
using cn.lovelong.Paypal.Model;

namespace cn.lovelong.Paypal.Paypal
{
    /// <summary>
    /// CreatePayment 的摘要說明
    /// </summary>
    public class CreatePayment
    {
        public CreatePayment()
        {
        }

        public PaymentResult Pay(string json)
        {
            var jsonResult = HttpHelper.PostJson(
                UrlConfig.CreatePaymentUrl, 
                AccountConfig.ClientId, AccountConfig.Secret, json,
                Encoding.UTF8);
            var result = new JavaScriptSerializer().Deserialize<PaymentResult>(jsonResult);
            return result;
        }

        public PaymentResult Pay(PaymentParam param)
        {
            var json = GetPayParams(param);
            return Pay(json);
        }
        
        public string GetPayParams(PaymentParam param)
        {
            var total = param.Total.ToString("N");
            var currency = Enum.GetName(typeof (PaypalCurrency), param.Currency);
            var payParams = new
            {
                intent = "sale",
                redirect_urls = new
                {
                    return_url = param.ReturnUrl,
                    cancel_url = param.CancelUrl,
                },
                payer = new
                {
                    payment_method = "paypal"
                },
                transactions = new dynamic[]
                {
                    new
                    {
                        amount = new
                        {
                            total = total,
                            currency = currency
                        },
                        description = param.Description,
                        custom = param.Code,
                        item_list = new
                        {
                            items = new dynamic[]
                            {
                                new
                                {
                                    name = param.Name,
                                    //description = param.Name,
                                    quantity = "1",
                                    price = total,
                                    //tax = "0.01",
                                    //sku = "1",
                                    currency = currency
                                }
                            }
                        }
                    }
                }
            };
            var json = new JavaScriptSerializer().Serialize(payParams);
            return json;
        }

        public string GetFullPayParams(decimal total, PaypalCurrency currency, string returnUrl, string cancelUrl)
        {
            var payParams = new
            {
                intent = "sale",
                redirect_urls = new
                {
                    return_url = returnUrl,
                    cancel_url = cancelUrl,
                },
                payer = new
                {
                    payment_method = "paypal"
                },
                transactions = new dynamic[]
                {
                    new
                    {
                        amount = new
                        {
                            total = total.ToString("N"),
                            currency = Enum.GetName(typeof(PaypalCurrency),currency),
                            details = new
                            {
                                subtotal = "30.00",
                                tax = "0.07",
                                shipping = "0.03",
                                handling_fee = "1.00",
                                shipping_discount = "-1.00",
                                insurance = "0.01"
                            }
                        },
                        description = "",
                        custom = "EBAY_EMS_90048630024435",
                        invoice_number = "48787589673",
                        payment_options = new
                        {
                            allowed_payment_method = "INSTANT_FUNDING_SOURCE"
                        },
                        soft_descriptor = "ECHI5786786",
                        item_list = new
                        {
                            items = new dynamic[]
                            {
                                new
                                {
                                    name = "hat",
                                    description = "Brown hat.",
                                    quantity = "5",
                                    price = "3",
                                    tax = "0.01",
                                    sku = "1",
                                    currency = "USD"
                                }
                            },
                            shipping_address = new
                            {
                                recipient_name = "Brian Robinson",
                                line1 = "4th Floor",
                                line2 = "Unit #34",
                                city = "San Jose",
                                country_code = "US",
                                postal_code = "95131",
                                phone = "011862212345678",
                                state = "CA"
                            },
                        }
                    }
                }
            };
            var json = new JavaScriptSerializer().Serialize(payParams);
            return json;
        }
    }
}

確認(rèn)支付接口:

using System.Text;
using System.Web.Script.Serialization;
using cn.lovelong.Paypal.Config;
using cn.lovelong.Paypal.Model;

namespace cn.lovelong.Paypal.Paypal
{
    /// <summary>
    /// Approved 的摘要說明
    /// </summary>
    public class Approved
    {
        public PaymentResult DoJson(string paymentId, dynamic json)
        {
            var jsonResult = HttpHelper.PostJson(string.Format(UrlConfig.ApprovedUrl, paymentId), 
                AccountConfig.ClientId, AccountConfig.Secret, json, Encoding.UTF8);
            var result = new JavaScriptSerializer().Deserialize<PaymentResult>(jsonResult);
            return result;
        }

        public PaymentResult Do(string paymentId, string payerId)
        {
            var json = GetPayParams(payerId);
            return DoJson(paymentId, json);
        }

        public string GetPayParams(string payerId)
        {
            var payParams = new
            {
                payer_id = payerId
            };
            var json = new JavaScriptSerializer().Serialize(payParams);
            return json;
        }
    }
}

查詢支付結(jié)果接口調(diào)用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using cn.lovelong.Paypal.Config;
using cn.lovelong.Paypal.Model;

namespace cn.lovelong.Paypal.Paypal
{
    public class ShowPaymentDetails
    {
        public PaymentResult Do(string paymentId)
        {
            var json = HttpHelper.Get(
                string.Format(UrlConfig.ShowPaymentDetailsUrl, paymentId), 
                AccountConfig.ClientId, AccountConfig.Secret,
                Encoding.UTF8);
            var result = new JavaScriptSerializer().Deserialize<PaymentResult>(json);
            return result;
        }
    }
}

最容易出問題的反而是通用類 HttpHelper:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace cn.lovelong.Paypal
{
    public class HttpHelper
    {
        public static string PostForm(string url, string userName, string password, Dictionary<string,object> dic, Encoding encoding)
        {
            var param = string.Empty;
            foreach (var o in dic)
            {
                if (string.IsNullOrEmpty(param))
                    param += o.Key + "=" + o.Value;
                else
                    param += "&" + o.Key + "=" + o.Value;
            }
            byte[] byteArray = encoding.GetBytes(param);

            //處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創(chuàng)建 SSL/TLS 安全通道。)
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(encoding.GetBytes(userName + ":" + password)));
            request.PreAuthenticate = true;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            //寫入?yún)?shù)
            Stream newStream = request.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if(stream != null)
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
            return string.Empty;
        }

        public static string PostJson(string url, string userName, string password, string json, Encoding encoding)
        {
            byte[] byteArray = encoding.GetBytes(json);

            //處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創(chuàng)建 SSL/TLS 安全通道。)
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 |
                                                    SecurityProtocolType.Tls;

            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(encoding.GetBytes(userName + ":" + password)));
            request.PreAuthenticate = true;

            request.Method = "POST";
            request.Headers.Add("Cache-Control", "no-cache");
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;

            //寫入?yún)?shù)
            Stream newStream = request.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                        using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                        {
                            return sr.ReadToEnd();
                        }
                }
            }
            return string.Empty;
        }
        
        public static string Get(string url, string userName, string password, Encoding encoding)
        {
            //處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創(chuàng)建 SSL/TLS 安全通道。)
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 |
                                                    SecurityProtocolType.Tls;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(encoding.GetBytes(userName + ":" + password)));
            request.PreAuthenticate = true;

            request.Method = "GET";
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                        using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                        {
                            return sr.ReadToEnd();
                        }
                }
            }
            return string.Empty;
        }
    }
}
主要的功能都已經(jīng)實現(xiàn)了!看看演示 Demo 吧!
1. 支付頁面
2. Checkout JS 方式(如果你的頁面點擊登錄之后一直在第二個頁面轉(zhuǎn)圈的話,那只能說明你的登錄賬號不能支付你的商家賬號,或者你的賬號如果登錄之后顯示添加銀行卡的提示,說明你的商家賬號和你的賬號都是中國賬號,那你只能添加多幣種卡支付,不能用銀聯(lián)支付了):
付款就好了!
3. 接口方式我就沒有使用彈出頁面了,最簡單的方式(接口會直接在調(diào)用接口的頁面觸發(fā)支付跳轉(zhuǎn)),點擊接口支付
我就不支付了,我用的商家賬號是自己的新加坡的賬號, 按照今天的匯率 $0.01 = ¥0.068,你至少需要支付 0.07 元才能完成支付,而文章開頭也說了,商家需要付稅,也就是說你支付的 0.07 都會變成給 Paypal 的稅,商家一分錢也拿不到,也就是說,你至少支付 3.5元人民幣($0.51 = ¥3.481)商家才能得到微額的款項。
下面給出 Demo 源碼,源碼中配置的商家號是我自己的,請自行修改,為了方便大家沒有商家賬號的朋友做測試我就不刪除了,朋友們也不要真的支付測試,你的測試只會讓 Paypal 賺錢而已!
我的開發(fā)環(huán)境是 VS2015 + C# 6.0 + JS ,代碼僅供參考,請自行修改擴展學(xué)習(xí)使用!

相關(guān)推薦:

調(diào)用支付寶PHP接口API實現(xiàn)在線即時支付功能

.Net實現(xiàn)微信JS-SDK分享功能代碼展示-C#.Net教程

以上是Paypal 支付功能的 C# .NET / JS 實現(xiàn)的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

C#中產(chǎn)量關(guān)鍵字對創(chuàng)建迭代器的意義是什麼? C#中產(chǎn)量關(guān)鍵字對創(chuàng)建迭代器的意義是什麼? Jun 19, 2025 am 12:17 AM

healieldKeyWordinc#簡化了creationeratoratorabyautomationalingaseratingastatemachinethatemachinathablesLazyEvaluation.1.ItallowSreturningReturningInturningItemSoneatAtiMeTimeYielderturn,pausingexecutionBeteachieneachIneachIneachIneachIneachIneachIneachIneachItem,whoisidealforlargeordeNemicSequences.2.yieldBreakcanbeus.2.yieldBreakcanbeus

什麼是依賴性注入(DI),如何在C#中實現(xiàn)(例如,在ASP.NET Core中使用內(nèi)置DI)? 什麼是依賴性注入(DI),如何在C#中實現(xiàn)(例如,在ASP.NET Core中使用內(nèi)置DI)? Jun 30, 2025 am 02:06 AM

DependencyInjection(DI)inC#isadesignpatternthatenhancesmodularity,testability,andmaintainabilitybyallowingclassestoreceivedependenciesexternally.1.DIpromotesloosecouplingbydecouplingobjectcreationfromusage.2.Itsimplifiestestingthroughmockobjectinject

IDisposable接口和C#中的使用語句的目的是什麼? IDisposable接口和C#中的使用語句的目的是什麼? Jun 27, 2025 am 02:18 AM

IDisposable和using在C#中的作用是高效且確定性地管理非託管資源。 1.IDisposable提供Dispose()方法,使類能明確定義如何釋放非託管資源;2.using語句確保對象超出範(fàn)圍時自動調(diào)用Dispose(),簡化資源管理並避免洩漏;3.使用時需注意對象必須實現(xiàn)IDisposable,可聲明多個對象,並應(yīng)始終對如StreamReader等類型使用using;4.常見最佳實踐包括不要依賴析構(gòu)函數(shù)清理、正確處理嵌套對象及實現(xiàn)Dispose(bool)模式。

Lambda表達(dá)式和LINQ(語言集成查詢)如何增強C#中的數(shù)據(jù)操作? Lambda表達(dá)式和LINQ(語言集成查詢)如何增強C#中的數(shù)據(jù)操作? Jun 20, 2025 am 12:16 AM

LambdaexpressionsandLINQsimplifydatamanipulationinC#byenablingconcise,readable,andefficientcode.1.Lambdaexpressionsallowinlinefunctiondefinitions,makingiteasiertopasslogicasargumentsforfiltering,transforming,sorting,andaggregatingdatadirectlywithinme

C#8中的可無效參考類型(NRT)是什麼,它們?nèi)绾螏椭乐筃ullReferenceException? C#8中的可無效參考類型(NRT)是什麼,它們?nèi)绾螏椭乐筃ullReferenceException? Jun 21, 2025 am 12:36 AM

Nullablereferencetypes(NRTs)inC#8 helpcatchNullReferenceExceptionerrorsatcompiletimebymakingreferencetypesnon-nullablebydefault,requiringexplicitdeclarationfornullability.NRTsmustbeenabledeitherinthe.csprojfilewithenableoratthetopofa.csfileusing#null

如何在C#中使用跨度和內(nèi)存來優(yōu)化內(nèi)存使用情況並減少分配? 如何在C#中使用跨度和內(nèi)存來優(yōu)化內(nèi)存使用情況並減少分配? Jun 18, 2025 am 12:11 AM

Span和Memory通過減少內(nèi)存分配提升C#性能。 1.Span避免數(shù)組複製,提供對現(xiàn)有內(nèi)存的輕量引用,適用於解析二進制協(xié)議、字符串操作及高性能緩衝區(qū)管理;2.Memory支持跨異步方法傳遞內(nèi)存切片,適用於需要更靈活生命週期的場景;3.二者降低GC壓力,通過重用緩衝區(qū)、避免臨時拷貝優(yōu)化性能;4.Span受限於棧上使用,不可存儲於類或用於異步方法,需注意避免調(diào)用.ToArray()等導(dǎo)致重新分配的操作。

使用C#開發(fā)時,有哪些常見的陷阱或反圖案可以避免? 使用C#開發(fā)時,有哪些常見的陷阱或反圖案可以避免? Jun 23, 2025 am 12:05 AM

C#開發(fā)中常見四大“反模式”問題需避免。一是不合理使用async/await導(dǎo)致死鎖或性能下降,應(yīng)堅持全異步原則、配置ConfigureAwait(false)并規(guī)范命名;二是過度依賴var影響可讀性,應(yīng)在類型不明確時顯式聲明并統(tǒng)一團隊規(guī)范;三是錯誤使用Dispose和資源管理引發(fā)泄漏,應(yīng)正確使用using語句及實現(xiàn)IDisposable標(biāo)準(zhǔn)模式;四是濫用靜態(tài)類或單例造成測試?yán)щy,應(yīng)優(yōu)先依賴注入、保持無狀態(tài)或由容器管理生命周期。避開這些誤區(qū)可顯著提升代碼質(zhì)量與維護性。

您能在面向?qū)ο蟮脑O(shè)計中解釋可靠的原理及其應(yīng)用嗎? 您能在面向?qū)ο蟮脑O(shè)計中解釋可靠的原理及其應(yīng)用嗎? Jun 25, 2025 am 12:47 AM

SOLID原則是面向?qū)ο缶幊讨刑嵘a可維護性和擴展性的五項設(shè)計原則,它們分別是:1.單一職責(zé)原則(SRP)要求類只承擔(dān)一個職責(zé),如將報告生成與郵件發(fā)送分離;2.開閉原則(OCP)強調(diào)通過接口或抽像類支持?jǐn)U展而不修改原有代碼,如使用IShape接口實現(xiàn)不同圖形的面積計算;3.里氏替換原則(LSP)要求子類能替換父類而不破壞邏輯,如Square不應(yīng)錯誤繼承Rectangle導(dǎo)致行為異常;4.接口隔離原則(ISP)主張定義細(xì)粒度接口,如拆分打印與掃描功能避免冗餘依賴;5.依賴倒置原則(DIP)提倡依

See all articles