亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development WeChat payment development-Senparc.Weixin.MP detailed explanation

WeChat payment development-Senparc.Weixin.MP detailed explanation

Feb 13, 2017 pm 01:14 PM
WeChat development

Official account + WeChat payment SDK: Senparc.Weixin.MP.dll

Enterprise account SDK: Senparc.Weixin.QY.dll

Open platform SDK: Senparc.Weixin.Open. dll

Official address: http://weixin.senparc.com/

Of course, if we want to complete the development of the WeChat payment function of the official account, we need to use the DLL Senparc.Weixin.MP.dll , I checked the official DEMO and tutorials, but there are no instructions related to WeChat payment. I have no choice. Now that I have the source code, I can find it myself.

Open Senparc.Weixin.MP.sln. Based on the classification of the English folder names, it can be initially judged that WeChat payment is encapsulated in the TenPayLib folder, but I also found that there is a name called "TenPayLibV3" " folder, how to choose? After searching online, I came to this conclusion: those applied before September 10, 2014 are version v2, and those applied after that are version v3. The service account I used to test WeChat Pay was just applied for in 2016 and passed the verification, so just use V3 decisively.

Open the TenPayLibV3 folder:

微信支付開(kāi)發(fā)-Senparc.Weixin.MP詳解

Multiple class libraries are found here. What does each one do? We will not describe them one by one here. Interested friends can download and take a look. The file header of each category has function instructions and descriptions. According to the official payment instructions of WeChat, we will start the payment directly.

Enter the WeChat official account, click WeChat Payment in the function menu: and click Tutorial-Official Account Payment accordingly

微信支付開(kāi)發(fā)-Senparc.Weixin.MP詳解 微信支付開(kāi)發(fā)-Senparc.Weixin.MP詳解

Quickly review the document content Review and browse to find the corresponding functions in Senparc.Weixin.MP.dll.

微信支付開(kāi)發(fā)-Senparc.Weixin.MP詳解

First configure the payment authorization directory and add a payment test whitelist. Only three payment directories are supported, and the domain name must be ICP registered. The function of the authorization directory is that if you want to initiate a WeChat payment request, the requested link address must be in the authorization directory. Otherwise, the identity is invalid and the payment cannot be successful. Only the personal WeChat ID added to the test whitelist can complete the test of payment in the WeChat payment test directory. If a person who is not in the whitelist initiates a payment application, the payment will not be successful.

After the configuration is completed, how to call it? Let’s continue to look at the official description: H5 call up payment API.

“Open the H5 web page in WeChat browser and execute JS to call up payment. The input and output data format of the interface is JSON.

Note: WeixinJSBridge Built-in objects are not valid in other browsers.

The parameter names in the list are size-sensitive, and signature verification will fail if the case is incorrect. "

OK, here are a few things to explain, the first must be. WeChat browser; secondly, parameters are case-sensitive; thirdly, the data format is JSON.

Official description: As long as the following script is called on the page, the WeChat payment function can be enabled:

function onBridgeReady(){
   WeixinJSBridge.invoke(
       'getBrandWCPayRequest', {
           "appId" : "wx2421b1c4370ec43b",     //公眾號(hào)名稱(chēng),由商戶(hù)傳入     
           "timeStamp":" 1395712654",         //時(shí)間戳,自1970年以來(lái)的秒數(shù)     
           "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //隨機(jī)串     
           "package" : "prepay_id=u802345jgfjsdfgsdg888",     
           "signType" : "MD5",         //微信簽名方式:     
           "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信簽名 
       },
       function(res){     
           if(res.err_msg == "get_brand_wcpay_request:ok" ) {}     // 使用以上方式判斷前端返回,微信團(tuán)隊(duì)鄭重提示:res.err_msg將在用戶(hù)支付成功后返回    ok,但并不保證它絕對(duì)可靠。 
       }
   ); 
}
if (typeof WeixinJSBridge == "undefined"){
   if( document.addEventListener ){
       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
   }else if (document.attachEvent){
       document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
   }
}else{
   onBridgeReady();
}

My calling code: Because I want to call WeChat payment after clicking the button to confirm the payment. Carry out subsequent operations and put the official code into the method

function onBridgeReady() {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": $('#APPID').val(),     //公眾號(hào)名稱(chēng),由商戶(hù)傳入     
                    "timeStamp": $('#Timestamp').val(),         //時(shí)間戳,自1970年以來(lái)的秒數(shù)     
                    "nonceStr": $('#Noncestr').val(), //隨機(jī)串     
                    "package": $('#package').val(),
                    "signType": "MD5",         //微信簽名方式:     
                    "paySign": $('#paySign').val() //微信簽名 
                },
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        //支付成功,后續(xù)自行處理
                        
                    }
                    else
                    {
                        //支付取消,或者其他錯(cuò)誤,自行處理
                    }
                }
            );
        }

Okay, so where do these parameters come from and what are they? Let’s analyze them one by one:

appId: Everyone who develops WeChat should know this. The official account can be found in the developer menu

timeStamp: timestamp, the official description is “since 1970” "Seconds", don't worry, you can definitely find

from the payment library. nonceStr: The official explanation is the random string "e61463f8efa94090b1f366cccfbbb444". What does it mean? See the random number generation algorithm for details. It turns out to be a set of encryption rules and algorithms. Friends who have done URL request interfaces should know that some companies’ JSON string signature methods are similar to this.

Package: Prepayment ID, which can be obtained by calling the official API unified ordering interface

SignType: String "MD5"

paySign: The official explanation is the WeChat signature "70EA570631E4BB79628FBCA90534C63FF7FADD89" , Okay, I endured it, and I took a look at the signature generation algorithm. It seems to be like a random string

At this point, the official interface description has been understood very clearly, so the next step is to solve the problem of calling WeChat How should I use these payment parameters through Senparc.Weixin.MP.dll? Since we need to first call the unified ordering interface to obtain the prepaid order ID, well, let's first study how to obtain this ID.

  官方給出了詳細(xì)說(shuō)明,我們不在贅述,各參數(shù)研究按照上述接口的方式自行研究解決,唯一區(qū)別在于,調(diào)用官方接口需要傳入一個(gè)XML,那很好辦,拼接一下就可以了,預(yù)支付調(diào)用方法如下:

//這里通過(guò)官方的一個(gè)實(shí)體,用戶(hù)自行使用,我這里是直接讀取的CONFIG文件
private static Senparc.Weixin.MP.TenPayLibV3.TenPayV3Info tenPayV3Info = new Senparc.Weixin.MP.TenPayLibV3.TenPayV3Info(ConfigurationManager.AppSettings["corpId"], ConfigurationManager.AppSettings["corpSecret"], ConfigurationManager.AppSettings["mch_id"]
                    , ConfigurationManager.AppSettings["key"], ConfigurationManager.AppSettings["v3url"]);

        /// <summary>
        /// 微信預(yù)支付
        /// </summary>
        /// <param name="attach"></param>
        /// <param name="body"></param>
        /// <param name="openid"></param>
        /// <param name="price"></param>
        /// <param name="orderNum"></param>
        /// <returns></returns>
        public static string PayInfo(string attach, string body, string openid, string price, string orderNum = "1833431773763549")
        {
            RequestHandler requestHandler = new RequestHandler(HttpContext.Current);
            //微信分配的公眾賬號(hào)ID(企業(yè)號(hào)corpid即為此appId)
            requestHandler.SetParameter("appid", tenPayV3Info.AppId);
            //附加數(shù)據(jù),在查詢(xún)API和支付通知中原樣返回,該字段主要用于商戶(hù)攜帶訂單的自定義數(shù)據(jù)
            requestHandler.SetParameter("attach", attach);
            //商品或支付單簡(jiǎn)要描述
            requestHandler.SetParameter("body", body);
            //微信支付分配的商戶(hù)號(hào)
            requestHandler.SetParameter("mch_id", tenPayV3Info.MchId);
            //隨機(jī)字符串,不長(zhǎng)于32位。
            requestHandler.SetParameter("nonce_str", TenPayUtil.GetNoncestr());
            //接收微信支付異步通知回調(diào)地址,通知url必須為直接可訪問(wèn)的url,不能攜帶參數(shù)。
            requestHandler.SetParameter("notify_url", tenPayV3Info.TenPayV3Notify);
            //trade_type=JSAPI,此參數(shù)必傳,用戶(hù)在商戶(hù)公眾號(hào)appid下的唯一標(biāo)識(shí)。
            requestHandler.SetParameter("openid", openid);
            //商戶(hù)系統(tǒng)內(nèi)部的訂單號(hào),32個(gè)字符內(nèi)、可包含字母,自己生成
            requestHandler.SetParameter("out_trade_no", orderNum);
            //APP和網(wǎng)頁(yè)支付提交用戶(hù)端ip,Native支付填調(diào)用微信支付API的機(jī)器IP。
            requestHandler.SetParameter("spbill_create_ip", "127.0.0.1");
            //訂單總金額,單位為分,做過(guò)銀聯(lián)支付的朋友應(yīng)該知道,代表金額為12位,末位分分
            requestHandler.SetParameter("total_fee", price);
            //取值如下:JSAPI,NATIVE,APP,我們這里使用JSAPI
            requestHandler.SetParameter("trade_type", "JSAPI");
            //設(shè)置KEY
            requestHandler.SetKey(tenPayV3Info.Key);

            requestHandler.CreateMd5Sign();
            requestHandler.GetRequestURL();
            requestHandler.CreateSHA1Sign();
            string data = requestHandler.ParseXML();
            requestHandler.GetDebugInfo();

            //獲取并返回預(yù)支付XML信息
            return TenPayV3.Unifiedorder(data);
        }
    }

好的,拿到預(yù)支付訂單的返回?cái)?shù)據(jù),一切又都好辦了,根據(jù)返回參數(shù)的不同,自行解決,我們只關(guān)心調(diào)用正確的過(guò)程,操作繼續(xù),在返回的正確XML數(shù)據(jù)中,我們獲取到了 <![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>(官方示例),好的,開(kāi)始在頁(yè)面做支付吧!</p><p>這里,我封裝了一個(gè)實(shí)體,用來(lái)傳輸常用的數(shù)據(jù),當(dāng)然,各位也可以參考Senparc.Weixin.MP.dll提供的實(shí)體類(lèi)。</p><pre class='brush:php;toolbar:false;'>public class ShareInfo { string corpId = string.Empty; public string CorpId { get { return corpId; } set { corpId = value; } } string ticket = string.Empty; public string Ticket { get { return ticket; } set { ticket = value; } } string noncestr = string.Empty; public string Noncestr { get { return noncestr; } set { noncestr = value; } } string timestamp = string.Empty; public string Timestamp { get { return timestamp; } set { timestamp = value; } } private string paySign = string.Empty; public string PaySign { get { return paySign; } set { paySign = value; } } private string package = string.Empty; public string Package { get { return package; } set { package = value; } } }

我們繼續(xù),來(lái)看一下支付接口需要用到的參數(shù)如何獲?。?/p>

public static ShareInfo GetPayInfo(string prepayid)
        {
            shareInfo = new ShareInfo();
            //檢查是否已經(jīng)注冊(cè)jssdk
            if (!JsApiTicketContainer.CheckRegistered(corpId))
            {
                JsApiTicketContainer.Register(corpId, corpSecret);
            }
            JsApiTicketResult jsApiTicket = JsApiTicketContainer.GetTicketResult(corpId);
            JSSDKHelper jssdkHelper = new JSSDKHelper();
            shareInfo.Ticket = jsApiTicket.ticket;
            shareInfo.CorpId = corpId.ToLower();
            shareInfo.Noncestr = JSSDKHelper.GetNoncestr().ToLower();
            shareInfo.Timestamp = JSSDKHelper.GetTimestamp().ToLower();
            shareInfo.Package="prepay_id=" + prepayid.ToLower();

            RequestHandler requestHandler = new RequestHandler(HttpContext.Current);

            requestHandler.SetParameter("appId", shareInfo.CorpId);
            requestHandler.SetParameter("timeStamp", shareInfo.Timestamp);
            requestHandler.SetParameter("nonceStr", shareInfo.Noncestr);
            requestHandler.SetParameter("package", shareInfo.Package);
            requestHandler.SetParameter("signType", "MD5");

            requestHandler.SetKey(tenPayV3Info.Key);
            requestHandler.CreateMd5Sign();
            requestHandler.GetRequestURL();
            requestHandler.CreateSHA1Sign();
            shareInfo.PaySign = (requestHandler.GetAllParameters()["sign"]).ToString();
            return shareInfo;
        }

這樣,支付接口需要用到的參數(shù),就都封裝在ShareInfo里了,好吧,調(diào)用之后,我們回到頁(yè)面的后置代碼中,或者你采用的ORM對(duì)應(yīng)代碼中去,將參數(shù)輸出到頁(yè)面

//處理頁(yè)面支付調(diào)用信息
                    ShareInfo shareInfo = TenPayModule.GetPayInfo(prepayid);
                    System.Web.HttpContext.Current.Response.Write(string.Format("<input type=\"hidden\" id=\"Noncestr\" runat=\"server\" value=\"{0}\" />", shareInfo.Noncestr));
                    System.Web.HttpContext.Current.Response.Write(string.Format("<input type=\"hidden\" id=\"Timestamp\" runat=\"server\" value=\"{0}\" />", shareInfo.Timestamp));
                    System.Web.HttpContext.Current.Response.Write(string.Format("<input type=\"hidden\" id=\"APPID\" runat=\"server\" value=\"{0}\" />", shareInfo.CorpId));
                    System.Web.HttpContext.Current.Response.Write(string.Format("<input type=\"hidden\" id=\"paySign\" runat=\"server\" value=\"{0}\" />", shareInfo.PaySign));
                    System.Web.HttpContext.Current.Response.Write(string.Format("<input type=\"hidden\" id=\"package\" runat=\"server\" value=\"{0}\" />", shareInfo.Package));

好的,寫(xiě)到這里,大家參照上面的JS代碼,就可以完成整個(gè)的支付功能了。最后,再附送一個(gè)生成商家訂單號(hào)的方法,代碼如下:

public string GetOrderNumber()
        {
            string Number = DateTime.Now.ToString("yyMMddHHmmss");
            return Number + Next(1000, 1).ToString();
        }
        private static int Next(int numSeeds, int length)
        {
            byte[] buffer = new byte[length]; 
            System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
            Gen.GetBytes(buffer);
            uint randomResult = 0x0; 
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
            }
            return (int)(randomResult % numSeeds);
        }

更多微信支付開(kāi)發(fā)-Senparc.Weixin.MP詳解?相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

PHP WeChat development: How to implement voting function PHP WeChat development: How to implement voting function May 14, 2023 am 11:21 AM

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

Using PHP to develop WeChat mass messaging tools Using PHP to develop WeChat mass messaging tools May 13, 2023 pm 05:00 PM

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

PHP WeChat development: How to implement customer service chat window management PHP WeChat development: How to implement customer service chat window management May 13, 2023 pm 05:51 PM

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

PHP WeChat development: How to implement user tag management PHP WeChat development: How to implement user tag management May 13, 2023 pm 04:31 PM

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

PHP WeChat development: How to implement group message sending records PHP WeChat development: How to implement group message sending records May 13, 2023 pm 04:31 PM

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

Steps to implement WeChat public account development using PHP Steps to implement WeChat public account development using PHP Jun 27, 2023 pm 12:26 PM

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

How to use PHP for WeChat development? How to use PHP for WeChat development? May 21, 2023 am 08:37 AM

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform

See all articles