C#版本的微信SDK,项目只需引用库RsCode.WeChat
,三步完成微信SDK的调用
一 微信配置
json
"Tencent": {
"WeChat": [
{
"Id": "gh_e1c6*",
"AppId": "wx7c82*",
"AppSecret": "5a5efeb3b0*",
"Token": "6LQyNSzUUZ*",
"EncodingAESKey": "qKgdQuc*",
"DataFormatter": "xml"
},
{
"Id": "gh_353d*",
"AppId": "wxa471d*",
"AppSecret": "a41db9dd*",
"Token": "",
"EncodingAESKey": "",
"DataFormatter": "xml"
}
]
},
WeChat节点中可以添加多个微信应用,其中DataFormatter的值根据实际的配置,它可以是xml
也可以是json
二 配置RsCode.WeChat服务与中间件
c#
services.AddHttpClient();
//微信公众号
services.AddWeChat(options=>
{
Configuration.GetSection("Tencent:WeChat").Bind(options);
});
...
app.UseWeChat();
三 应用RsCode.WeChat
注入IWeChatClient
,调用SendAsync()
获取微信用户信息实例代码
csharp
public class OAuthController : Controller
{
IWeChatClient wechat;
WeChatOptions WeChatOptions;
public OAuthController(IWeChatClient weChatClient)
{
wechat=weChatClient;
var appId="wx***"
WeChatOptions = wechat.UseAppId(appId);
}
public ActionResult UserInfo(string code,string state)
{
//用code获取accessToken
var oauthResponse = await wechat.SendAsync<OAuthTokenResponse>(new OAuthTokenRequest(WeChatOptions.AppId, WeChatOptions.AppSecret, code));
if (oauthResponse.Code == 0)
{
//获取微信用户信息
var wxUser = await wechat.SendAsync<WeChatUserBaseInfoResponse>(new WeChatUserBaseInfoRequest(oauthResponse.AccessToken,oauthResponse.OpenId));
}
....
}
}
url签名实例
注入 IWechatTokenManager
,例IWechatTokenManager tokenManager
c#
public async Task< IActionResult> OpenMp()
{
string scheme = HttpContext.Request.Scheme;
string host=HttpContext.Request.Host.ToString();
string path = HttpContext.Request.Path;
if(HttpContext.Request.IsHttps)
{
scheme = "https";
}
scheme = "https";
string url = $"{scheme}://{host}{path}";
var s = await tokenManager.UrlSignature(appId, url);
TempData["signature"] = s;
TempData["url"] = url;
return View();
}
四 其它
WeChatTool.GetNonceStr()
生成随机数 WeChatTool.GetTimeStamp()
生成时间戳
有时间再扩充内容,有问题进群交流