创建微信开放平台账号,然后创建网页应用
获取appid和appsecret
前端使用的vue,安装插件vue-wxlogin
调用代码
<wxlogin :appid="appId" :scope="scope" :redirect_uri="redirect_uri"></wxlogin>
<script>
import wxlogin from "vue-wxlogin";
const appId = ref("wx开头的appid");
const scope = ref("snsapi_login");
const redirect_uri = ref("跳转的URL,需要URL编码");//比如原来是http://www.baidu.com需要填写http%3A%2F%2Fwww.baidu.com,使用encodeURIComponent即可实现
</script>
这样就能出来二维码了,微信扫码之后有一个codehttps://www.xxxx.com/?code=011UQe100NJMTR1tsG100BNvo93UQe1n&state=
前端需要返回code给后台,后台解析
安装Nuget包https://github.com/fudiwei/DotNetCore.SKIT.FlurlHttpClient.Wechat
实现解密code,需要读取appid和appsecret,这两个参数都放到appsettings.json中
"OpenWeixin": {
"OpenWechatAppId": "",
"OpenWechatAppSecret": ""
}
OpenWeixinOptions
services.AddConfigurableOptions<OpenWeixinOptions>();
public class OpenWeixinOptions : IConfigurableOptions
{
/// <summary>
/// 微信开放平台appid
/// </summary>
public string OpenWechatAppId { get; set; }
/// <summary>
/// 微信开放平台appsecret
/// </summary>
public string OpenWechatAppSecret { get; set; }
}
编写帮助类OpenWechatHelper
using Furion;
using Furion.DependencyInjection;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
/// <summary>
/// 微信开放平台帮助类
/// </summary>
public class OpenWechatHelper : ISingleton
{
private WechatApiClient client;
/// <summary>
/// 构造函数注入
/// </summary>
public OpenWechatHelper()
{
var wechatConfig = App.GetOptions<OpenWeixinOptions>();
var options = new WechatApiClientOptions()
{
AppId = wechatConfig.OpenWechatAppId,
AppSecret = wechatConfig.OpenWechatAppSecret,
};
client = new WechatApiClient(options);
}
/// <summary>
/// 根据code获取某个应用下的微信用户id
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public async Task<string> GetOpenId(string code)
{
var request = new SnsOAuth2AccessTokenRequest();
request.Code = code;
var tokenResponse = await client.ExecuteSnsOAuth2AccessTokenAsync(request);
if (!tokenResponse.IsSuccessful())
{
return string.Empty;
}
return tokenResponse.OpenId;
}
}
剩下的按照业务逻辑处理即可