.net开发 abp框架+vue的微信公众号的微信授权

1、在进行微信开发之前你   首先你得需要一个微信公众号(具体的申请步骤省略)

2、进行微信开发的开发配置(我这里是配置一个测试账号后面的微信支付还是要走微信公众号  配置是一样的)


URL为微信开发正确响应发送Token验证的地址目录,也就是公众号里的白名单配置

Token是微信开发中用于回调微信响应的标识 根据个人需求进行配置即可

js接口安全域名 是承接微信接口以供调用的域名地址

另外微信支付还需要微信支付平台的商户号以及支付密钥的配置

3、接下来就是配置微信公众号菜单初始化了

/// <summary>
        /// 初始化公众号菜单
        /// </summary>
        /// <param name="appConfiguration"></param>
        /// <param name="logger"></param>
        public static void Init(IConfigurationRoot appConfiguration, ILogger logger)

        {

            var config = new WeChatConfig()
            {
                AppId = "wxe011bf8a07f98423",
                AppSecret = "3f8b95edefa40d149fe32a1cf9715385",
                MchId = "1502779501",
                PayNotifyUrl = "http://medical.app.stoned.vip/#/mine/pay_success",
                TenPayKey = "wlsoftnewhissong3355180meiyanfei",
                PayAppId = "wxe011bf8a07f98423"
            };
            WeChatSDKBuilder.Create()
                //设置日志记录
                .WithLoggerAction((tag, message) =>
                {
                    logger.Debug(string.Format("Tag:{0}\tMessage:{1}", tag, message));
                })
                //注册Key。不再需要各个控制注册
                .Register(WeChatFrameworkFuncTypes.GetKey, model =>
                    {
                        return "wx8370799bb85178a8";
                    }
                )
                //注册获取配置函数:根据Key获取微信配置(加载一次后续将缓存)
                .Register(WeChatFrameworkFuncTypes.Config_GetWeChatConfigByKey,
                    model =>
                    {
                        return config;
                    })
                //注册微信支付配置
               .Register(WeChatFrameworkFuncTypes.Config_GetWeChatPayConfigByKey, model =>
                    {
                        return config;
                    }
               )
                .Build();
            var menuApi = WeChatApisContext.Current.MenuApi;
            var appRootUrl = appConfiguration?["App:MenuRootUrl"];
            //从配置中获取
         var rootUrl = appRootUrl.IsNullOrEmpty() ? "http://medical.app.stoned.vip/" : appRootUrl;//配置你的响应地址目录
            var menus = new MenuInfo
            {
                Button = new List<MenuButtonBase>
                {
                    new ViewButton()
                    {
                        Name = "首页",
                        Url = $"{rootUrl}#/shouye"
                    },
                    new ViewButton()
                    {
                        Name = "就诊",
                        Url = $"{rootUrl}#/jiuzhen"
                    },
                    new ViewButton()
                    {
                       Name = "我的",
                        Url = $"{rootUrl}#/mine"
                    }
                }
            };
            var result = menuApi.Create(menus);
            if (result.IsSuccess())
                logger.Debug("菜单初始化成功!");
            else

                logger.Error("菜单初始化失败:" + result.GetFriendlyMessage());

具体根据你的sdk提供的方法进行代码的编写

4、然后对于微信授权可以有很多调用的方法,对于一般的前后端分离的架构设计来说对微信接口进行封装然后通过自己的接口调用访问是比较常用的方式

/// <summary>
        /// 获取授权地址
        /// </summary>
        /// <param name="url"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [AbpAllowAnonymous]
        [HttpGet("GetWeChatAuthUrl")]
        public Task<string> GetWeChatAuthUrl(string url, string state = "")
        {
            WeChat.SDK.Apis.Token.OAuthApi oauthApi = new WeChat.SDK.Apis.Token.OAuthApi();
            string result = oauthApi.GetAuthorizeUrl(url, state);
            return Task.FromResult(result);

        }

这是调用自己封装的微信接口的接口调用代码

封装代码如下:

/// <summary>
        ///     获取网页授权链接
        /// </summary>
        /// <param name="redirectUrl">授权后重定向的回调链接地址,请使用urlencode对链接进行处理</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节</param>
        /// <param name="scope">
        ///     应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo
        ///     (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
        /// </param>
        /// <returns></returns>
        public string GetAuthorizeUrl(string redirectUrl, string state, OAuthScopes scope = OAuthScopes.snsapi_userinfo)
        {
            return string.Format(
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                AppConfig.AppId, redirectUrl.UrlEncode(), "code", scope, state);

        }

通过该接口调用生成定向的微信访问链接,输入自己前端需要重定向url输出定向微信的地址

5、前端定向微信地址:

//访问授权
getopenid:function(){
this.$http.get('/api/Users/GetWeChatAuthUrl',{
params: {
url:"http://medical.app.stoned.vip/#/mine"
}
}).then((response)=>{
if (response && response.data.success == true) {
window.location.href=response.data.result;
}
})
},

vue js代码调用接口然后定向到微信地址

6、点击确定授权后接口会重定向到你输入的重定向url 并将返回参数拼接在你的路径url上如下所示


7、使用返回参数code调用接口获取用户信息

//获取授权用户信息
getuser:function(){
var urlCode=(window.location.href.split('&')[0]).split('=')[1];
this.$http.get('/api/Users/GetWeChatUser',{
params: {
code:urlCode,
}
}).then((response)=>{
if (response && response.data.success == true) {
sessionStorage.setItem("openid",response.data.result.openid);
sessionStorage.setItem("username",response.data.result.nickname);
sessionStorage.setItem("userimage",response.data.result.headimgurl);

this.mine_name=sessionStorage.getItem("username");
this.imageurl=sessionStorage.getItem("userimage");
this.getuserid();
}
})
},

前端调用接口

后台接口:

/// <summary>
        /// 获取微信用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [AbpAllowAnonymous]
        [HttpGet("GetWeChatUser")]
        public async Task<GetUserInfoApiResult> GetWeChatUser(string code)
        {
            WeChat.SDK.Apis.Token.OAuthApi oauthApi = new WeChat.SDK.Apis.Token.OAuthApi();
            var token = oauthApi.Get(code);
            if (!token.IsSuccess())
            {
                return null;
            }
            //拉取用户信息(需scope为 snsapi_userinfo)
            var weUser = oauthApi.GetUserInfo(token.AccessToken, token.OpenId);
            return weUser;

        }

sdk封装代码:

 /// <summary>
        ///     拉取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        /// <param name="oauthAccessToken">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
        /// <param name="openId">用户的唯一标识</param>
        /// <param name="lang">返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语</param>
        /// <returns></returns>
        public GetUserInfoApiResult GetUserInfo(string oauthAccessToken, string openId, string lang = "zh_CN")
        {
            var url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang={2}",
                oauthAccessToken, openId, lang);
            var result = Get<GetUserInfoApiResult>(url);
            return result;

        }

这样就完成了授权  并获取了用户信息





在使用 **.NET + ABP (ASP.NET Boilerplate)** 框架开发项目时,更新数据库通常指的是将实体模型(Entity)的变更同步到数据库中。ABP 基于 Entity Framework Core(EF Core)进行数据访问,因此数据库更新主要通过 **EF Core 的迁移(Migration)机制**来实现。 以下是详细的步骤和代码示例,说明如何在 .NET + ABP 框架中更新数据库: --- ### ✅ 步骤 1:确保项目结构正确 典型的 ABP 项目结构中: - `YourProject.EntityFrameworkCore` 项目包含 DbContext 和 EF Core 配置。 - 数据库上下文通常继承自 `AbpDbContext<T>` 或 `AbpZeroCoreDbContext`。 例如: ```csharp public class YourProjectDbContext : AbpDbContext<YourProjectDbContext> { public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } public YourProjectDbContext(DbContextOptions<YourProjectDbContext> options) : base(options) { } } ``` --- ### ✅ 步骤 2:修改实体类(如添加新字段) 假设你要为 `Product` 实体添加一个新属性: ```csharp public class Product : Entity<int> { public string Name { get; set; } public decimal Price { get; set; } // 新增字段 public string Description { get; set; } } ``` --- ### ✅ 步骤 3:添加 EF Core 迁移 打开命令行工具(如 Visual Studio 的 **Package Manager Console** 或 .NET CLI),切换到 `EntityFrameworkCore` 项目目录,运行以下命令: #### 使用 .NET CLI(推荐) ```bash dotnet ef migrations add AddDescriptionToProduct --project src/YourProject.EntityFrameworkCore --startup-project src/YourProject.Web.Mvc ``` > 注意: > - `--project`:指定包含 DbContext 的项目。 > - `--startup-project`:指定启动项目(包含 `appsettings.json` 和程序入口)。 这会生成一个新的迁移文件,如: ```csharp public partial class AddDescriptionToProduct : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Description", table: "Products", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Description", table: "Products"); } } ``` --- ### ✅ 步骤 4:应用迁移更新数据库 运行以下命令将更改应用到数据库: ```bash dotnet ef database update --project src/YourProject.EntityFrameworkCore --startup-project src/YourProject.Web.Mvc ``` 执行后,EF Core 会检查当前数据库状态,并运行所有未应用的迁移脚本。 --- ### ✅ 补充:自动迁移(不推荐用于生产) 你也可以在 `OnModelCreating` 后启用自动应用迁移(仅建议开发环境): ```csharp public class YourProjectDbContext : AbpDbContext<YourProjectDbContext> { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 可以在这里配置更多模型... } public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) { return await base.SaveChangesAsync(cancellationToken); } } ``` 然后在 `Program.cs` 或 `Startup.cs` 中添加: ```csharp using (var scope = host.Services.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<YourProjectDbContext>(); context.Database.Migrate(); // 自动应用待定迁移 } ``` > ⚠️ 生产环境建议手动控制迁移,避免意外修改数据库。 --- ### ✅ 常见问题排查 | 问题 | 解决方案 | |------|----------| | 找不到 `dotnet-ef` | 安装 EF Core 工具:`dotnet tool install --global dotnet-ef` | | 提示无法连接数据库 | 检查 `appsettings.json` 中的连接字符串是否正确 | | 多个 DbContext 冲突 | 明确指定 `--context YourProjectDbContext` 参数 | --- ### ✅ 总结流程 1. 修改实体类; 2. 添加 Migration; 3. 更新数据库; 4. (可选)在启动时自动迁移。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值