.net6+fruit+sqlsugar+senparcsdk develop wechat official account series 3: access to official account

1, Access overview

To access wechat public platform development, developers need to follow the following steps:

1. Fill in server configuration

2. Verify the validity of the server address

3. Implement business logic according to interface documents

2, Fill in server configuration

Fill in your own server configuration with wechat official account

III. compiling API

Delete test service in scaffold

New global CS for global references

 Global. The global reference of shengpai sdk in CS makes it unnecessary for every class to reference What's new in NET6

global using Senparc.NeuChar.Entities;
global using Senparc.Weixin;
global using Senparc.Weixin.MP;
global using Senparc.Weixin.MP.Entities;
global using Senparc.Weixin.MP.Entities.Request;
global using Senparc.Weixin.MP.MessageContexts;
global using Senparc.Weixin.MP.MessageHandlers;
global using Furion.DynamicApiController;
global using Microsoft.AspNetCore.Mvc;
global using System;
global using System.IO;
global using System.Threading.Tasks;
global using Microsoft.AspNetCore.Http;
global using System.Threading;
global using WeiXinApi.Application.Handler;
global using WeiXinApi.Application.Services;
namespace WeiXinApi.Application
{
    internal class Global
    {

    }
}

Create new folders and files as shown in the figure

Introduce Nuget package senparc Weixin. MP and senparc Weixin. AspNet

Create a new API. The routing address is the address followed by the domain name filled in our server configuration. Mine is wx. I use a dynamic API here, so I'm not an inherited controller

using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.MP.Entities.Request;

namespace WeiXinApi.Application.Services
{
    public class WeiXinService : IDynamicApiController
    {
        [HttpGet("/wx")]
        public string Index([FromQuery] PostModel postModel, string echostr)
        {
            System.Console.WriteLine(echostr);
            return echostr;
        }
    }
}

Test the interface, no problem

IV. publish to ECs and debug by attaching to the process

Because only domain names can be filled in the server configuration, we need to publish the project to the ECS. I upload it through ftp. Debug by attaching processes, or debug programs by internal and external penetration. Here I directly attach processes for debugging. 

 WeiXinApi. Web. Enter the number of folders that can be published

<SatelliteResourceLanguages>en-US</SatelliteResourceLanguages>

Direct server startup project

Attach to process

Select hosting

Official account page test request

 

Breakpoint hit successfully

V. use shengpai SDK to verify the request

The above code directly returns to echostr. In fact, we need to verify it to judge whether it is legal. Here we can directly take it from shengpai demo. First, configure it according to the requirements in shengpai demo in the configuration file. I put it in applicationsettings json

   //CO2NET set up
  "SenparcSetting": {
    //The following is CO2NET of SenparcSetting Global configuration, please do not modify key,Do not delete any items

    "IsDebug": true,
    "DefaultCacheNamespace": "DefaultCache",

    //Distributed cache
    "Cache_Redis_Configuration": "#{Cache_Redis_Configuration}#", //Redis to configure
    //"Cache_Redis_Configuration": "localhost:6379",//Do not include password
    //"Cache_Redis_Configuration": "localhost:6379,password=senparc,connectTimeout=1000,connectRetry=2,syncTimeout=10000,defaultDatabase=3",//Password and other configurations
    "Cache_Memcached_Configuration": "#{Cache_Memcached_Configuration}#", //Memcached to configure
    "SenparcUnionAgentKey": "#{SenparcUnionAgentKey}#" //SenparcUnionAgentKey
  },
  //Senparc.Weixin SDK set up
  "SenparcWeixinSetting": {
    //The following is Senparc.Weixin of SenparcWeixinSetting Wechat configuration
    //Note: all string values may be used for dictionary index, so please do not leave empty string (but you can delete the corresponding whole setting as needed)!

    //Wechat Global
    "IsDebug": true,

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

    //official account
    "Token": "jinwandalaohu", //Description: both sides of the string#and{}Symbol is Azure DevOps The default placeholder format. If you have clear text information, please delete the same placeholder and modify the overall string without retaining it#And {}, such as: {"Token": "MyFullToken"}
    "EncodingAESKey": "xxx",
    "WeixinAppId": "xxx",
    "WeixinAppSecret": "xxx",
    //Extension and proxy parameters
    "AgentUrl": "AgentUrl",
    "AgentToken": "AgentToken",
    "SenparcWechatAgentKey": "SenparcWechatAgentKey"
  }

startup. Register SDK in CS

 var config = App.Configuration;
 services.AddSenparcGlobalServices(config)//Senparc.CO2NET Global registration
          .AddSenparcWeixinServices(config);//Senparc.Weixin register

Configure SDK in configure

  var senparcSetting = App.GetOptions<SenparcSetting>();
  var senparcWeixinSetting = App.GetOptions<SenparcWeixinSetting>();

    // start-up CO2NET Global registration, required!
   var registerService = app.UseSenparcGlobal(env, senparcSetting, globalRegister =>
       {
         globalRegister.RegisterTraceLog(ConfigTraceLog);//to configure TraceLog

       }, true)
       .UseSenparcWeixin(senparcWeixinSetting, (weixinRegister, weixinSetting) =>
       {});
ConfigTraceLog is a method used to configure logs
    /// <summary>
    /// Configure wechat tracking log (demo, on demand)
    /// </summary>
    private void ConfigTraceLog()
    {
        //Set here as Debug State,/App_Data/WeixinTraceLog/A log file will be generated under the directory to record all API Request log. It is recommended to close the official release version

        //If global IsDebug(Senparc.CO2NET.Config.IsDebug)by false,It can be set separately here true,Otherwise, it is automatically true
        Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog("system log", "System startup");//Only in Senparc.Weixin.Config.IsDebug = true Effective in case of

        //Global custom logging callback
        Senparc.CO2NET.Trace.SenparcTrace.OnLogFunc = () =>
        {
            //Add each trigger Log Code to be executed after
            System.Console.WriteLine("Add each trigger Log Code to be executed after");
        };

        //When occurs based on WeixinException Triggered when an exception occurs
        WeixinTrace.OnWeixinExceptionFunc = async ex =>
        {
            //Add each trigger WeixinExceptionLog Required code after execution
            System.Console.WriteLine("Add each trigger WeixinExceptionLog Code to be executed after");
        };
    }

In the interface, obtain the token and other information through the sdk method, and directly add the following code to WeiXinService

        public static readonly string Token = Config.SenparcWeixinSetting.MpSetting.Token;//With the background of wechat public account Token The settings are consistent and case sensitive.
        public static readonly string EncodingAESKey = Config.SenparcWeixinSetting.MpSetting.EncodingAESKey;//With the background of wechat public account EncodingAESKey The settings are consistent and case sensitive.
        public static readonly string AppId = Config.SenparcWeixinSetting.MpSetting.WeixinAppId;//With the background of wechat public account AppId The settings are consistent and case sensitive.

To modify the code of the Index method, you can use the code in shengpai demo

        [HttpGet("/wx")]
        public string Index([FromQuery] PostModel postModel, string echostr)
        {
            //System.Console.WriteLine(echostr);
            //return echostr;

            if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                Console.WriteLine("adopt:" + echostr);
                return echostr; //If a random string is returned, the verification is passed
            }
            else
            {
                return ("failed:" + postModel.Signature + "," + Senparc.Weixin.MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + ". " +
                    "If you see this sentence in the browser, it means that this address can be used as the background of wechat public account Url,Please pay attention to keep Token agreement.");
            }
        }

Publish it to the server and test it. It passes

 

If the test fails again, the token is modified to indicate that the verification fails

6, Gitee address in this chapter

 https://gitee.com/huguodong520/weixinapi/tree/%E6%8E%A5%E5%85%A5%E5%85%AC%E4%BC%97%E5%8F%B7/

Posted by B0b on Wed, 25 May 2022 10:10:59 +0300