Home  >  Article  >  WeChat Applet  >  WeChat public platform development: using Senparc.Weixin.MP SDK

WeChat public platform development: using Senparc.Weixin.MP SDK

高洛峰
高洛峰Original
2017-02-27 11:56:312001browse

Senparc.Weixin.MP SDK already covers all public APIs of WeChat 6.x.

The source code of the entire project and the compiled assembly can be obtained in this project: https://github.com/JeffreySu/WeiXinMPSDK

PS: Due to the WeChat API and Senparc .Weixin SDK has been continuously upgraded and updated. The latest code and Demo are subject to the source code in the github above.

We are now building an ASP.NET MVC project from scratch to see how to connect with WeChat (the principle of Webforms is the same, just replace the Action in the Controller with an .aspx page) ).

The source code of the project to be demonstrated can also be found in open source projects (because the source code has to take into account two projects and one public project, the structure is slightly different from the one shown below, but the logic is completely consistent):

MVC: https://github.com/JeffreySu/WeiXinMPSDK/tree/master/Senparc.Weixin.MP.Sample

WebForms: https://github.com/JeffreySu/WeiXinMPSDK /tree/master/Senparc.Weixin.MP.Sample.WebForms

Step one: Create an empty ASP.NET MVC (4.0) project, project Name such as Senparc.Weixin.MP.Sample

微信公众平台开发:使用Senparc.Weixin.MP SDK

Step 2: Create a Controller, such as WeixinController.cs

微信公众平台开发:使用Senparc.Weixin.MP SDK

The third step: introduce Senparc.Weixin.MP.dll

There are two ways to introduce related dll: one is to copy the dll to a certain folder of the project , and then directly add references to Senparc.Weixin.MP.dll and Senparc.Weixin.MP.MvcExtension.dll in the project (Senparc.Weixin.MP.MvcExtension.dll is only needed for MVC projects and can be ignored for WebForms projects), second This way we can use Nuget to install directly into the project.

Nuget project address: https://www.nuget.org/packages/Senparc.Weixin.MP/

The first method is simple enough, here is the second one : Open the menu [Tools] > [Library Package Manager] > [Package Manager Console], as shown below:

微信公众平台开发:使用Senparc.Weixin.MP SDK

After clicking, the program will appear Package manager console:

微信公众平台开发:使用Senparc.Weixin.MP SDK

If it is the first time to install the Senparc.Weixin.MP library, enter the command after PM>:

Install-Package Senparc.Weixin.MP

Press Enter, Senparc.Weixin.MP.dll will be automatically introduced into the project.

If you need to update to the latest version in the future, just use the Update-Package command, which will automatically update online:

Update-Package Senparc.Weixin.MP

The above operations are valid for both MVC and WebForms projects.

If it is an MVC project, in order to obtain more extension functions for MVC, we can continue to introduce Senparc.Weixin.MP.MvcExtension.dll:

Install-Package Senparc.Weixin .MP.MVC

The command window output is as follows, indicating that the installation has been successful:

微信公众平台开发:使用Senparc.Weixin.MP SDK

Let’s observe the project references assembly, these two dlls have been referenced:

微信公众平台开发:使用Senparc.Weixin.MP SDK

Step 4: Modify WeixinController.cs

We Add the following code to WeixinController.cs:

using System;
using System.IO;
using System.Web.Configuration;
using System.Web.Mvc;
using Senparc.Weixin.MP.Entities.Request;

namespace Senparc.Weixin.MP.Sample.Controllers
{
    using Senparc.Weixin.MP.MvcExtension;
    using Senparc.Weixin.MP.Sample.CommonService.CustomMessageHandler;

    public partial class WeixinController : Controller
    {
        public static readonly string Token = "YourToken";//与微信公众账号后台的Token设置保持一致,区分大小写。
        public static readonly string EncodingAESKey = "YourKey";//与微信公众账号后台的EncodingAESKey设置保持一致,区分大小写。
        public static readonly string AppId = "YourAppId";//与微信公众账号后台的AppId设置保持一致,区分大小写。

        /// <summary>
        /// 微信后台验证地址(使用Get),微信后台的“接口配置信息”的Url填写如:http://weixin.senparc.com/weixin
        /// </summary>
        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(PostModel postModel, string echostr)
        {
            if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return Content(echostr); //返回随机字符串则表示验证通过
            }
            else
            {
                return Content("failed:" + postModel.Signature + "," + MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
                    "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
            }
        }

        /// <summary>
        /// 用户发送消息后,微信平台自动Post一个请求到这里,并等待响应XML。
        /// PS:此方法为简化方法,效果与OldPost一致。
        /// v0.8之后的版本可以结合Senparc.Weixin.MP.MvcExtension扩展包,使用WeixinResult,见MiniPost方法。
        /// </summary>
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return Content("参数错误!");
            }

            postModel.Token = Token;//根据自己后台的设置保持一致
            postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致
            postModel.AppId = AppId;//根据自己后台的设置保持一致

            //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
            var messageHandler = new CustomMessageHandler(Request.InputStream, postModel);//接收消息

            messageHandler.Execute();//执行微信处理过程

            return new FixWeixinBugWeixinResult(messageHandler);//返回结果

        }
    }
}

The first Get corresponds to the request when setting the URL in the WeChat background, and the second Post is used to accept the forwarded customer request.

Among them, CustomMessageHandler is a class created by ourselves to implement MessageHandler (for a detailed introduction to MessageHandler, you can see "Senparc.Weixin.MP SDK WeChat Public Platform Development Tutorial (6): Understanding MessageHandler", you can also see here) , all core logic for processing WeChat messages is included in CustomMessageHandler for execution. In addition to undertaking the task of processing WeChat responses, MessageHandler also implements functions such as processing single user conversation context, which is very convenient.

At this point, the entire Senparc.Weixin.MP SDK has been basically developed and can be released directly and connected using "advanced functions" in the WeChat background.

For example, in the above code, fill in http://xxx/Weixin for Url and fill in weixin for Token

For more WeChat public platform development: use Senparc.Weixin.MP SDK For related articles, please pay attention to PHP Chinese website !


Statement:
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