当前位置:网站首页>Wechat payment V3 development tutorial (I): getting to know senparc.weixin.tenpayv3

Wechat payment V3 development tutorial (I): getting to know senparc.weixin.tenpayv3

2021-09-15 03:48:22 SZW

Preface

   I am here 9 It was released years ago  Senparc.Weixin SDK  The first open source version , It has been maintained up to now , Now Stras It's broken 7K, Along the way, I got .NET Positive response and support from the community , Also received a lot of valuable suggestions , Even code PR, The cumulative number of code contributors has exceeded 350 people , Thank you very much !

   We always update all kinds of wechat official interfaces at the first time , It also includes wechat payment .

   Now , For... That has been released for some time “ Wechat payment V3”, We released a completely refactored new version :Senparc.Weixin.TenPayV3.

   Even if you haven't developed the previous version of wechat payment, it doesn't matter , Because this is a completely new beginning , Let's start the development journey of the latest generation of wechat payment .

 

About wechat payment V2 and V3

   Pay from wechat V2 Start , We launched the wechat payment function for the first time , And in 2018 It was officially separated from the independent  Senparc.Weixin.TenPay  As a special class library for wechat payment .

   Wechat payment has been upgraded many times since its birth , One of the more confusing is V2 and V3 Two version numbers , Before moving on , You have to make an explanation :

  What is currently circulating in the community “ Wechat payment V3” There are actually 2  There is a version of it , One V3 In the early stage, wechat payment documents and interfaces were upgraded , At that time, the document called it V3, Later, another one came out, wechat payment official to API The version number of has been upgraded , Also known as V3.

  Latter V3 In the true sense “ Wechat payment V3”, The module released this time is also aimed at this V3 In terms of the .

  For historical reasons , In previously published Senparc.Weixin.TenPay It has also been included in V2 and V3 Naming of two versions , there V3 It's the of early documents V3, and “ Wechat payment V3" The usage of is actually quite different , But in terms of function , It basically belongs to “ Wechat payment V3” Subset .

 

Rapid development of - Get ready

   here , Let me start with a macro demonstration Senparc.Weixin.TenPayV3 The ability of , Through web presentation and unit test , Complete the simplest authentication 、 payment 、 Refund and order pull function ( These functions represent almost all forms of wechat payment internal interfaces ), The following chapters will continue to introduce the details .

   Introduction to specific interfaces and processes , We still have to be patient with the official documents :https://pay.weixin.qq.com/wiki/doc/apiv3/index.shtml, Ready for wechat payment V3 All required configurations (V3 It's a big leap over the previous documents , Doing so can basically be completed smoothly ). The following example will take 【 General merchants + WeChat official account JSAPI】 This combination is displayed , Other combined functions will be introduced later .

   Of all wechat payment forms Sample Already in open source projects , By default .NET 6 Project open :https://github.com/JeffreySu/WeiXinMPSDK/tree/master/Samples/net6-mvc, For testing purposes , You can download or clone the project directly , Model test , The corresponding code can be transplanted to your own project .

   Download the code and open the in the above directory  Senparc.Weixin.Sample.Net6.sln:

 

    among ,Controller and Views The name of , For the old version that was born before V3 distinguish , We'll temporarily name it RealV3 :

 

   You don't need to change any code , Direct operation Senparc.Weixin.Sample.NET6 project , You can open Sample home page :

 

   because Sample The official account of WeChat is integrated. 、 Applet 、 Enterprise WeChat 、 Wechat payment , And the associated cache 、 Simulation message 、 Document download and other demonstrations , So there seems to be a lot of content , There's no need to worry ,Sample With detailed notes , And the documents are classified , We just need to focus on the relevant parts .

 

 

 

The first step in development : quote Nuget package

  Sample The project has referenced the source code project , If you are a brand new project , You can quote  Senparc.Weixin.TenPayV3  package .

   Method 1 : Use VS Manager reference :

 

 

    Method 2 : Directly in .csproj Reference in file ( Attention from  Senparc.Weixin.TenPayV3  View the latest version on the web page ):

    <ItemGroup>
        <PackageReference Include="Senparc.Weixin.TenPayV3" Version="0.3.500.2-preview2" />
    </ItemGroup>

 

Development step 2 : Set wechat payment information

   stay Web Under the project , find appsettings.json file , Set up WeChat official account and WeChat payment information ( Other information according to instructions , Unnecessary items can be deleted , Or leave it as it is ), Only modification is required by default SenparcWeixinSetting Node under “ official account ” and “ Wechat payment V3( new edition )” The corresponding information of :

  "SenparcWeixinSetting": {
    // Be careful : All string values can be used for dictionary indexing , Therefore, do not leave empty strings ( But you can do it as needed , Delete the corresponding whole setting )!

    // Wechat Global 
    "IsDebug": true,

    // The following unused parameters can be deleted ,key  It will be invalid after modification 

    // official account 
    "Token": " Wechat payment is not required ",
    "EncodingAESKey": " Wechat payment is not required ",
    "WeixinAppId": "MyWeixinAppId",
    "WeixinAppSecret": "MyWeixinAppSecret",

    // Wechat payment V3( new edition )
    "TenPayV3_AppId": "MyWeixinAppId( ditto )",
    "TenPayV3_AppSecret": "MyWeixinAppSecret( ditto )",
    "TenPayV3_SubAppId": "",
    "TenPayV3_SubAppSecret": "",
    "TenPayV3_MchId": "xxxxxxxx",
    "TenPayV3_SubMchId": "", // Sub merchant , No blank 
    "TenPayV3_Key": "79xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "TenPayV3_CertPath": " Leave it blank ", // Physical path of payment certificate , Such as :D:\\cert\\apiclient_cert.p12
    "TenPayV3_CertSecret": " Leave it blank ", // Payment certificate password ( Original password and  MchId  identical )
    "TenPayV3_TenpayNotify": "http://sdk.weixin.senparc.com/TenpayV3/PayNotifyUrl", //http://YourDomainName/TenpayV3/PayNotifyUrl
    "TenPayV3_PrivateKey": "MIIExxxxxxxxxxxxxxxxx", //( new ) Certificate private key 
    "TenPayV3_SerialNumber": "5Bxxxxxxxxxxxxxxxxxxxxxx", // Certificate serial number 
    "TenPayV3_ApiV3Key": "xxxxxxxxxxxxxxxxxxxxxxxx", //( new )APIv3  secret key 
    // If not set TenPayV3_WxOpenTenpayNotify, Default in  TenPayV3_TenpayNotify  Add the value of  "WxOpen"
    "TenPayV3_WxOpenTenpayNotify": "http://sdk.weixin.senparc.com/TenpayV3/PayNotifyUrlWxOpen" //http://YourDomainName/TenpayV3/PayNotifyUrlWxOpen
  }

explain :TenPayV3_CertPath and  TenPayV3_CertSecret yes “ Document version V3" Legacy of the period , In the new V3 Can be ignored in

 

Development step 3 : Develop product lists and JSAPI Payment page

  Sample Provides a very simple list of goods and payment ( details ) page :

function Controller file View file
List of goods TenPayRealV3Controller.cs / ProductList() /Views/TenPayRealV3/ProductList.cshtml

JSAPI Payment page

( Goods details )

TenPayRealV3Controller.cs / JsApi() /Views/TenPayRealV3/JsApi.cshtml

   The implementation of specific business will not be carried out here , relevant OAuth The content of authorization belongs to the category of official account development , For detailed introduction, please refer to 《Senparc.Weixin.MP SDK  Wechat public platform development course ( Twelve ):OAuth2.0 explain 》.

   Let's focus on JSAPI Payment page , For the convenience of demonstration ,Sample Zhongba JSAPI Together with the details page , In actual projects , The details page can be arranged separately , here JSAPI The page is equivalent to the order payment page .

 

  Controller:

   First look at  TenPayRealV3Controller.cs Under the JsApi() Method :

 

sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId/*10 position */, SystemTime.Now.ToString("yyyyMMddHHmmss"),
                        TenPayV3Util.BuildRandomStr(6));

   The above code is used to generate the order number ( Also called in documents out_trade_no), Order No. suggested date , Easy to sort , Then add the serial number or random number , It depends on the specific project . We must ensure uniqueness here .

 

var notifyUrl = TenPayV3Info.TenPayV3Notify.Replace("/TenpayV3/", "/TenpayRealV3/").Replace("http://", "https://");

   The above code is used to define the address of the payment callback , Use here Replace Because Sample Compatible with 2 Set payment demonstration , Set it directly in the actual development process appsettings.json The parameters in the .

 

TransactionsRequestData jsApiRequestData = new(TenPayV3Info.AppId, TenPayV3Info.MchId, name + " -  Wechat payment  V3", sp_billno, new TenpayDateTime(DateTime.Now.AddHours(1), false), null, notifyUrl, null, new() { currency = "CNY", total = price }, new(openId), null, null, null);

   The above code is used to assemble the parameters for accessing the prepayment interface .

 

var result = await _basePayApis.JsApiAsync(jsApiRequestData);

   The above code is used to call the prepayment interface , obtain prepay_id, The private variable that has been defined in the constructor _basePayApis(BasePayApis type ), It is an instantiated class that executes a series of related payment interfaces :

        public TenPayRealV3Controller()
        {
            _tenpayV3Setting = Senparc.Weixin.Config.SenparcWeixinSetting.TenpayV3Setting;
            _basePayApis = new BasePayApis(_tenpayV3Setting);
        }

 

 

                if (result.VerifySignSuccess != true)
                {
                    throw new WeixinException(" obtain  prepay_id  Result verification error !");
                }

   Get result after , Be sure to perform signature verification ( Including other interfaces )! The actual signature and verification process is complex ,SDK It's completely encapsulated , You just need to make sure  VerifySignSuccess Parameter is true that will do .

 

                var jsApiUiPackage = TenPaySignHelper.GetJsApiUiPackage(TenPayV3Info.AppId, result.prepay_id);
                ViewData["jsApiUiPackage"] = jsApiUiPackage;

   The above code is used to generate the front end UI JsSdk All the information you need , Including time stamps 、 Random string 、 Signature string, etc , Developers do not need to write their own encryption algorithm , Open the box .

  jsApiUiPackage Information stored in  ViewData["jsApiUiPackage"] in , stay View Can be called directly in . Under the actual development environment , This information can be transmitted in various ways , Include Ajax + Json.

 

  View:

   Corresponding View page (JsApi.cshtml) The key codes are described below :

        document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
        //...
        }

   The above code is listening JSAPI Ready method .

 

 1               WeixinJSBridge.invoke('getBrandWCPayRequest', {
 2                    "appId": "@jsApiUiPackage.AppId", // The name of the official account , From merchant 
 3                    "timeStamp": "@jsApiUiPackage.Timestamp", // Time stamp 
 4                    "nonceStr": "@jsApiUiPackage.NonceStr", // Random string 
 5                    "package": "@Html.Raw(jsApiUiPackage.PrepayIdPackage)",// Expansion pack, 
 6                    "signType": "RSA", // WeChat V3 Signature method :RSA
 7                    "paySign": "@Html.Raw(jsApiUiPackage.Signature)" // Wechat signature 
 8                }, function (res) {
 9 
10                    //alert(JSON.stringify(res));
11 
12                    if (res.err_msg == "get_brand_wcpay_request:ok") {
13                        if (confirm(' Successful payment ! Click on “ determine ” Enter the refund process test .')) {
14                            location.href = '@Url.Action("Refund", "TenPayRealV3")';
15                        }
16                        //console.log(JSON.stringify(res));
17                    }else{
18                        alert(JSON.stringify(res));
19                    }
20                    //  Use the above method to judge the front end return , Wechat team tips :res.err_msg Will return after the user pays successfully ok, But it's not guaranteed to be absolutely reliable .
21                    // Therefore, wechat team suggests , When I received ok return , Ask the merchant's back office whether it has received the notification of successful transaction , If notice is received , The front-end displays the successful transaction interface ; If no notice is received at this time , The merchant background actively calls the order query interface , Query the current status of the order , And feed back to the front end to show the corresponding interface .
22                });

   The above code is triggered when the user clicks the payment button , A series of verifications will be performed automatically , And evoke the wechat payment interface of the client ( For example, enter a password or fingerprint ).

   among :

  • The first 2-7 That's ok : Before injection Controller Various parameters configured in . Be careful :paySign Parameters must be added Html.Raw(), Otherwise, it may fail because the encrypted string is escaped !
  • The first 12 That's ok : Judge whether the payment is successful , And do the next step . Be careful : The success here does not necessarily mean that wechat payment is really successful , Because this information may be tampered with , Therefore, the formal environment must be PayNotifyUrl The verification results in shall prevail !

 

   Callback validation PayNotifyUrl:

   The payment success information received by wechat client always has the possibility of being tampered , therefore , Do not :

  1. Because of the client JS Received seemingly correct information , The instruction that triggers the server to complete the payment ( If one Ajax request );
  2. Even if the next instruction on the server side is triggered , Do not place orders in this instruction “ Paid ” State modification , Order status modification , Must be in  PayNotifyUrl in !

   According to the previous appsettings.json as well as JsApi() Method , The final callback address is :https://sdk.weixin.senparc.com/TenpayRealV3/PayNotifyUrl, Code in  TenPayRealV3Controller Medium PayNotifyUrl() Method , This method demonstrates the best practice of correctly verifying payment status :

 1         /// <summary>
 2          /// JS-SDK Payment callback address ( Set in the order interface  notify_url)
 3          /// </summary>
 4          /// <returns></returns>
 5          public async Task<IActionResult> PayNotifyUrl()
 6          {
 7              try
 8              {
 9                  // Get the payment notification information sent asynchronously by wechat server 
10                  var resHandler = new TenPayNotifyHandler(HttpContext);
11                  var orderReturnJson = await resHandler.AesGcmDecryptGetObjectAsync<OrderReturnJson>();
12  
13                  // Log 
14                  Senparc.Weixin.WeixinTrace.SendCustomLog("PayNotifyUrl  Message received ", orderReturnJson.ToJson(true));
15  
16                  // Presentation record  transaction_id, The actual development needs to be recorded in the database , For refund and follow-up 
17                  TradeNumberToTransactionId[orderReturnJson.out_trade_no] = orderReturnJson.transaction_id;
18  
19                  // Get payment status 
20                  string trade_state = orderReturnJson.trade_state;
21  
22                  // Verify whether the request is sent from wechat ( Security )
23                  NotifyReturnData returnData = new();
24  
25                  // Verify reliable payment status 
26                  if (orderReturnJson.VerifySignSuccess == true && trade_state == "SUCCESS")
27                  {
28                      returnData.code = "SUCCESS";// Correct order processing 
29                      /*  Tips :
30                       * 1、 Until here , To think the deal was really successful , Database operation can be carried out , But don't forget to return the message in the specified format !
31                       * 2、 The above judgment has a relatively high security , You can also access  IP  Make judgment to further strengthen safety .
32                       * 3、 The following is a demonstration of sending a successful payment template message , Not necessary .
33                       */
34  
35                      #region  Send payment success template message reminder 
36                      // A little ...
37                      #endregion
38                  }
39                  else
40                  {
41                      returnData.code = "FAILD";// Wrong order processing 
42                      returnData.message = " Validation failed ";
43  
44                      // Here you can send a payment failure prompt to the user 
45                  }
46  
47                  #region  Log ( It can also be recorded in the database audit log )
48                  // A little ...
49                  #endregion
50                
51                  return Json(returnData);
52              }
53              catch (Exception ex)
54              {
55                  WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
56                  throw;
57              }
58          }

   The notes have been more detailed , No more details here , All signature verification and other security verification information have been encapsulated in the interface , Open the box . The complete process of official requirements can be referred to the document :https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtml.

 

Development step 4 :Startup.cs Configure startup code in

  Senparc.Weixin.TenPayV3 be based on Senparc.Weixin SDK Integral base , At the same time by CO2NET、NeuChar And other basic libraries provide strong underlying capability support , At the same time, we need to use some code , complete appsettings.json Automatic injection of information , therefore , Need to be in Web Project startup.cs Add some code to , The following is an introduction to the key code (Sample In order to demonstrate all modules, there is more code , You can select the code below as needed ):

  ConfigureServices() Method :

 1         public void ConfigureServices(IServiceCollection services)
 2          {
 3              services.AddSession();// Use Session( Practice has proved that it is necessary to configure  Mvc  Before )
 4  
 5              var builder = services.AddControllersWithViews()
 6                                    .AddNewtonsoftJson();//  Support  NewtonsoftJson
 7  
 8              services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
 9  
10              services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
11              services.AddMemoryCache();// To use local caching, you must add 
12  
13              services.AddSenparcWeixinServices(Configuration);//Senparc.Weixin  register ( must )
14          }

   The above code is complete Web A series of registrations for the project , among :

  • The first 3 That's ok : In order to make Demo Database independent , We used Session Store personal temporary data , Not necessarily required in actual development projects , You can add... As needed .
  • The first 5-6 That's ok : register MVC and JSON Relevant capabilities , Add as needed .
  • The first 8 That's ok : Provide Cookie Support , Add as needed .
  • The first 10 That's ok : Automatic injection HttpContext Add registration , Add as needed .
  • The first 11 That's ok : Register local cache , This must be done , because SDK The running process always needs to use the local cache .
  • The first 13 That's ok : Yes Senparc.Weixin SDK To register , must .

   You can see , Minimize support Senpar.Weixin.TenPayV3, In fact, you only need to add at least 2 Line code .

 

  Configure() Method :

 1       public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
 2                IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting)
 3        {
 4            app.UseHttpsRedirection();
 5            app.UseStaticFiles();
 6            app.UseRouting();
 7 
 8            var registerService = app
 9                    // Use  Senparc.CO2NET  engine 
10                    .UseSenparcGlobal(env, senparcSetting.Value, g => { })
11                    // Use  Senparc.Weixin SDK
12                    .UseSenparcWeixin(senparcWeixinSetting.Value, weixinRegister =>
13                    {
14                        // Register the latest  TenPay V3
15                        weixinRegister.RegisterTenpayRealV3(senparcWeixinSetting.Value, "【 Shengpai network assistant 】 official account -RealV3");
16                    });
17        }

   In the above code :

  • The first 4-6 That's ok : Conventional methods .
  • The first 10 That's ok : start-up Senparc.CO2NET engine , Provide a range of basic capabilities ( Caching 、 journal 、 Line up, etc ).
  • The first 12 That's ok : start-up Senparc.Weixin SDK, The official account of WeChat can be carried out. 、 Applet 、 Enterprise WeChat 、 Registration of different modules such as wechat payment .
  • The first 15 That's ok : Registered wechat payment V3 Information about , The data source is appsettings.json. Be careful : This line of registration process can be performed anywhere before using wechat payment function , However, it is recommended to complete registration at startup . In addition to using appsetting.json Automatic injection mode , You can also construct entity classes manually , Assign and pass in .

 

Online demonstration

   Above Sample It can be published directly , The latest code has been released to the official online sample site :https://sdk.weixin.senparc.com/, There are two ways to enter the above JsApi Page for payment test .

   Mode one : Official account : Shengpai network assistant , Click menu

 

 

 

   Enter menu 【 More tests 】>【 Wechat payment V3】:

 

 

    Select any item , Such as 【 product 1】, Click to enter :

 

 

    Click on 【 Click submit to experience wechat payment 】 Button , Enter client payment status :

 

 

    Complete payment at the client ( Enter password or fingerprint ), The official interface of payment completion will appear :

 

 

    Click on 【 complete 】 Button , You can continue to experience the refund process ( For an introduction to development related functions, please see the next series of articles :《 Wechat payment V3 Development tutorial ( Two ): refund 》.

   Return to official account , You can see that it has passed  PayNotifyUrl  Template message sent ( At the same time, it has been safely verified ):

 

 

   

   And can be in the wechat payment message , See the official news push :

 

 

 

   Mode two : adopt  https://sdk.weixin.senparc.com/  Top menu 【 hold-all 】>【 Wechat payment V3 test (PC End )】 Get into :

 

 

    After entering, it is the same ProductList page :

 

 

    Select a product to enter , You can see PC The client provides demonstration of various payment methods , Include :H5 payment 、Native payment , And sweep payment :

 

   Tips : Because of the product Id Varies with each system start , Therefore, the above QR code is invalid when you see it , You can re-enter from the entrance , Get the latest QR code .

 

  • About H5 Please pay attention to the following articles :《 Wechat payment V3 Development tutorial ( 3、 ... and ):H5 payment 》
  • About Native Please pay attention to the following articles :《 Wechat payment V3 Development tutorial ( Four ):Native payment 》

   Current demo JsApi payment , Can be found in “ scan ” Payment method , Enter with wechat scanning code , You can open the above information on wechat “ Method 1 ” List of products described in , And experience the payment process .

  

More

   This article is about 《 Wechat payment V3 Development tutorial 》 The beginning of , Refunds will also be included later 、 Reconciliation order 、H5 payment 、Native payment 、 More interfaces such as wechat are introduced , Welcome to your attention , Thank you for your support !

 

版权声明
本文为[SZW]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/09/20210909105741701m.html

随机推荐