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

目次
Paypal Checkout JS 支付模式
RESTful API 支付模式

Paypal決済機能のC# .NET/JS実裝

Aug 10, 2018 pm 05:11 PM

說明

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

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

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

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

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

Paypal決済機能のC# .NET/JS実裝

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

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

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

Paypal決済機能のC# .NET/JS実裝

Paypal決済機能のC# .NET/JS実裝

?相關資料

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実裝

模式說明:

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

支付部分代碼:

<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 表示產品環(huán)境還是測試環(huán)境
        client: {
            production: &#39;&#39;, // 產品環(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>

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

RESTful API 支付模式

說明

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

支付接口調用:

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;
        }
    }
}

確認支付接口:

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;
        }
    }
}

查詢支付結果接口調用:

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;

            //寫入參數(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;

            //寫入參數(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;
        }
    }
}
主要的功能都已經實現(xiàn)了!看看演示 Demo 吧!
1. 支付頁面
2. Checkout JS 方式(如果你的頁面點擊登錄之后一直在第二個頁面轉圈的話,那只能說明你的登錄賬號不能支付你的商家賬號,或者你的賬號如果登錄之后顯示添加銀行卡的提示,說明你的商家賬號和你的賬號都是中國賬號,那你只能添加多幣種卡支付,不能用銀聯(lián)支付了):
付款就好了!
3. 接口方式我就沒有使用彈出頁面了,最簡單的方式(接口會直接在調用接口的頁面觸發(fā)支付跳轉),點擊接口支付
我就不支付了,我用的商家賬號是自己的新加坡的賬號, 按照今天的匯率 $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 ,代碼僅供參考,請自行修改擴展學習使用!

相關推薦:

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

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

以上がPaypal決済機能のC# .NET/JS実裝の詳細內容です。詳細については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

イテレータを作成するためのC#の収量キーワードの重要性は何ですか? イテレータを作成するためのC#の収量キーワードの重要性は何ですか? Jun 19, 2025 am 12:17 AM

keieldKeywordinc#simplifisitorator creation byは、astatemachinableslazyevaluation.1.itemsonisingingingingielidreturn、eachiTemを使用することを想定しています

依存関係噴射(DI)とは何ですか?また、C#でどのように実裝できますか(たとえば、ASP.NETコアに組み込みDIを使用)? 依存関係噴射(DI)とは何ですか?また、C#でどのように実裝できますか(たとえば、ASP.NETコアに組み込みDIを使用)? Jun 30, 2025 am 02:06 AM

依存関係の関心(DI)Inc#isadesignpatternthatenhancesmodularity、testability、およびmaintainability byallowingclasseStoreceivedenciesiesiesies.1.DipromotesslooseCouplingbydeapling objectcreationfromusage.2.itsimplifestestestroughtestroughjectStrughimject

IDISPOSABLEインターフェイスの目的と、リソース管理のためのC#の使用ステートメントは何ですか? IDISPOSABLEインターフェイスの目的と、リソース管理のためのC#の使用ステートメントは何ですか? Jun 27, 2025 am 02:18 AM

IDISPOSABLEの役割とC#での使用は、管理されていないリソースを効率的かつ決定論的に管理することです。 1。Idisposableは、dispose()メソッドを提供するため、クラスは管理されていないリソースをリリースする方法を明確に定義できます。 2。使用するステートメントは、オブジェクトが範囲外であるときに廃棄()が自動的に呼び出されることを保証し、リソース管理を簡素化し、漏れを回避します。 3.それを使用する場合、オブジェクトはIdisposableを実裝し、複數(shù)のオブジェクトを宣言することができ、StreamReaderなどのタイプに常に使用する必要があることに注意してください。 4.一般的なベストプラクティスには、クリーンアップするためのデストラクタに依存せず、ネストされたオブジェクトの操作を正しく処理すること、廃棄(BOOL)パターンの実裝が含まれます。

Lambda式とLINQ(言語統(tǒng)合クエリ)は、C#のデータ操作をどのように強化しますか? Lambda式とLINQ(言語統(tǒng)合クエリ)は、C#のデータ操作をどのように強化しますか? Jun 20, 2025 am 12:16 AM

lambdaexpressionsandlinqsimplifydatamanipulationinc#byenablingconcise、readable、a??nd efficientcode.1.lambdaexpressionsalowinlinefunctiondefinitions、make seasiertopasslogicasarguments forfiltering、transforming、sorting、andgregationdatadirimationdatdatidiristlogicasuments

C#8のNULLABLEリファレンスタイプ(NRT)とは何ですか?また、それらはどのようにしてnullReferenceExceptionを防ぐのに役立ちますか? C#8のNULLABLEリファレンスタイプ(NRT)とは何ですか?また、それらはどのようにしてnullReferenceExceptionを防ぐのに役立ちますか? Jun 21, 2025 am 12:36 AM

nullablereferenceTypes(nrts)inc#8 helpcatchnullreferenceexceptionerterrorsAtcompiletimebymakingrecerenceTypesnon-nullablebydefault.nrtsmustbeenedabledede.csprojfilewithetthettopofaused futopofay.csfuie.csfuie.csfue.csprojtthedthe.

C#でスパンおよびメモリを使用して、メモリの使用量を最適化し、割り當てを減らすにはどうすればよいですか? C#でスパンおよびメモリを使用して、メモリの使用量を最適化し、割り當てを減らすにはどうすればよいですか? Jun 18, 2025 am 12:11 AM

スパンとメモリは、メモリの割り當てを削減することにより、C#のパフォーマンスを改善します。 1. SPANは配列のコピーを回避し、既存のメモリへの軽い參照を提供します。これは、バイナリプロトコル、文字列操作、高性能バッファ管理に適しています。 2。メモリは、より柔軟なライフサイクルが必要なシナリオに適した非同期メソッドを通過するメモリスライスを渡すことをサポートします。 3.両方とも、GC圧力を低減し、バッファーを再利用し、一時的なコピーを回避することにより、パフォーマンスを最適化します。 4。スパンはスタックでの使用に限定されており、クラスに保存したり、非同期方法で使用したりすることはできません。 calling.toarray()などの再割り當て操作を避けるように注意してください。

C#で開発する際に避けるべき一般的な落とし穴やパターンは何ですか? C#で開発する際に避けるべき一般的な落とし穴やパターンは何ですか? Jun 23, 2025 am 12:05 AM

C#開発における4つの一般的な「パターンアンチパターン」問題を避ける必要があります。第一に、Async/待ち望みの不合理な使用は、デッドロックまたはパフォーマンスの劣化につながります。完全な非同期性の原則を遵守し、configureawait(false)を構成し、命名を標準化する必要があります。第二に、VARへの過度の依存は読みやすさに影響し、タイプが不明な場合にチームの仕様を明示的に宣言および統(tǒng)合します。第三に、処分とリソース管理の誤った使用が漏れを引き起こし、使用ステートメントを正しく使用する必要があり、特徴的な標準モードを実裝する必要があります。第4に、靜的クラスまたはシングルトンの亂用はテストの困難を引き起こし、依存関係の注入、ステートレス性、またはコンテナによって管理されるライフサイクルを優(yōu)先する必要があります。これらの誤解を避けると、コードの品質とメンテナンスが大幅に向上する可能性があります。

C#オブジェクト指向のデザインでの堅実な原則とそれらのアプリケーションを説明できますか? C#オブジェクト指向のデザインでの堅実な原則とそれらのアプリケーションを説明できますか? Jun 25, 2025 am 12:47 AM

確固たる原則は、オブジェクト指向のプログラミングにおけるコードの保守性とスケーラビリティを改善するための5つの設計原則です。それらは次のとおりです。1。単一の責任原則(SRP)は、レポートの生成や電子メールの送信の分離など、クラスが1つの責任のみを想定することを要求しています。 2。オープニングとクロージングの原則(OCP)は、ISHAPEインターフェイスを使用して異なるグラフィックの領域計算を実現(xiàn)するなど、元のコードを変更することなく、インターフェイスまたは抽象クラスを通じて拡張機能がサポートされることを強調しています。 3.リヒター置換原理(LSP)は、サブクラスがロジックを破壊することなく親クラスを置き換えることを要求しています。 4.インターフェイス分離原理(ISP)は、冗長依存性を回避するための分割印刷やスキャン関數(shù)など、きめ細かいインターフェイスの定義を提唱しています。 5.依存関係反転原理(DIP)が提唱します

See all articles