微信小程序和公众号打通,实现用户关注公众号送优惠券

2024-04-24 21:36

本文主要是介绍微信小程序和公众号打通,实现用户关注公众号送优惠券,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前提

小程序
公众号
微信开放平台
小程序和公众号都需要绑定到同一个微信开放平台,因为要获取Unionid,unionid是什么

如果开发者拥有多个移动应用、网站应用、和公众账号(包括小程序),可通过 UnionID 来区分用户的唯一性,因为只要是同一个微信开放平台账号下的移动应用、网站应用和公众账号(包括小程序),用户的 UnionID 是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,UnionID是相同的。

微信公众号获取unionid
在这里插入图片描述

小程序获取unionid
在这里插入图片描述

获取参数

公众号appid和appsecret
在这里插入图片描述
小程序appid和appsecret
在这里插入图片描述

微信小程序关注公众号组件

https://developers.weixin.qq.com/miniprogram/dev/component/official-account.html
在这里插入图片描述
在这里插入图片描述
小程序测试需要设置场景值
在这里插入图片描述
在这里插入图片描述
这个展示有条件,不过基本能满足,如果没有关注就是显示关注,因为关注了所以显示的是查看,模拟器上没法点击,需要发布体验版去真机上使用,如果场景下不支持,则可以模拟写一个,不过功能没法实现,最终方案是通过webview跳转公众号文件引导关注

<template><view class="offical-account-container"><view class="top-text">xxx小程序关联的公众号</view><view class="content"><view class="logo"><image src="../../static/images/officalaccount/logo.png"></image></view><view class="info"><view class="name">公众号名字</view><view class="detial">公众号简介。</view></view><view class="action"><!--未关注--><view class="action-item">关注</view><!--已关注--><!-- <view class="action-item">查看</view> --></view></view></view>
</template><script>export default {name:"follow-official-account",data() {return {};}}
</script><style lang="scss" scoped>
.offical-account-container{padding: 16rpx;width: 750rpx;height: 168rpx;overflow: hidden;background-color: #fff;.top-text{color: #b2b2b2;font-size: 24rpx;height: 24rpx;line-height: 24rpx;}.content{display: flex;flex-direction: row;justify-content: space-between;align-items: center;width: 100%;margin-top:32rpx;height: 72rpx;.info{// padding-left: 20rpx;// padding-right: 20rpx;height: 80rpx;max-width: 474rpx;.name{font-size: 32rpx;color: #303133;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;}.detial{font-size: 24rpx;color: #7f7f7f;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;}}.logo{width: 80rpx;height: 80rpx;min-width: 80rpx;image{width: 100%;height: 100%;}}.action{// margin-right: 24rpx;padding-right: 8rpx;display: flex;align-items: center;justify-content: center;width: 130rpx;height: 80rpx;.action-item{width: 130rpx;height:56rpx;border:2rpx solid #1aad19;color: #1aad19;text-align: center;line-height: 56rpx;font-size: 28rpx;border-radius: 6rpx;}}}
}
</style>

后端需要安装SKIT.FlurlHttpClient.Wechat.Api组件
在这里插入图片描述

后端初始化client

小程序

/// <summary>
/// 客户端
/// </summary>
private WechatApiClient client;public WeChatMiniProgramClient(IOptions<xxx> config)
{var options = new WechatApiClientOptions(){AppId = config.Value.AppId,AppSecret = config.Value.AppSecret,ImmeDeliveryAppKey = "",ImmeDeliveryAppSecret = "",VirtualPaymentAppKey = "",MidasOfferId = "",MidasAppKey = "",MidasOfferIdV2 = "",MidasAppKeyV2 = ""};client = WechatApiClientBuilder.Create(options).Build();
}

公众号

/// <summary>
/// 客户端
/// </summary>
private WechatApiClient client;/// <summary>
/// 构造函数注入
/// </summary>
public OfficalAccountClient(IOptions<xxxx> config)
{var options = new WechatApiClientOptions(){AppId = config.Value.AppId,AppSecret = config.Value.AppSecret,ImmeDeliveryAppKey = "",ImmeDeliveryAppSecret = "",VirtualPaymentAppKey = "",MidasOfferId = "",MidasAppKey = "",MidasOfferIdV2 = "",MidasAppKeyV2 = "",PushToken = config.Value.Token,PushEncodingAESKey  =config.Value.EncodingAesKey};client = WechatApiClientBuilder.Create(options).Build();
}

小程序获取unionid

uni-app和小程序获取wx.login下的code

uni.login({provider:'weixin',success: function(res) {console.log(res);if (res.code) {console.log(res.code);} else {//login成功,但是没有取到code_this.$refs.uToast.show({title: '未取得code,请重试',type: 'error',})}},fail: function(res) {_this.$refs.uToast.show({title: '获取wx.login失败,请重试',type: 'error',})}
})
wx.login({success(res) {if (res.code) {//TODO 根据code获取openid以及unionid} else {wx.showToast({icon: "none",title: '获取信息失败',})}}
})

后端解析

/// <summary>
/// jscode获取openid
/// </summary>
/// <param name="jsCode"></param>
/// <returns></returns>
public async Task<(string openId,string unionId)> WeChatLogin(string jsCode)
{try{var userLoginRequest = new SnsJsCode2SessionRequest();userLoginRequest.JsCode = jsCode;var loginInfo = await client.ExecuteSnsJsCode2SessionAsync(userLoginRequest);if (loginInfo.IsSuccessful()){return (loginInfo.OpenId,loginInfo.UnionId ?? "");}return (string.Empty,string.Empty);}catch (Exception ex){return (string.Empty,string.Empty);}
}

公众号获取unionid

根据openid获取unionid

/// <summary>
/// 获取关注公众号的用户详情
/// </summary>
/// <param name="openId"></param>
public async Task<(bool isSub,string errMsg,string openId,string unionId,string remark)> GetOfficalAccountFollowUserInfo(string openId)
{var accessToken = await WeChatGetOfficalAccountToken();var response = await _officalAccountClient.GetOfficalFllowAccountUserInfo(accessToken, openId);if (!response.IsSuccessful()){if (response.ErrorCode == 42001){accessToken = await WeChatGetOfficalAccountToken(true);response = await _officalAccountClient.GetOfficalFllowAccountUserInfo(accessToken, openId);if (!response.IsSuccessful()){return (false,response.ErrorMessage, string.Empty, string.Empty,string.Empty);}}else{return (false,response.ErrorMessage, string.Empty, string.Empty,string.Empty);}}return (response.IsSubscribed, string.Empty, response.OpenId,response.UnionId,response.Remark);
}/// <summary>
/// 获取关注公众号的多个用户详情
/// </summary>
/// <param name="openIds"></param>
public async Task<(bool isSuccess,string errMsg,List<CgibinUserInfoBatchGetResponse.Types.User> list)> GetOfficalAccountFollowUsersInfo(List<string> openIds)
{var accessToken = await WeChatGetOfficalAccountToken();var response = await _officalAccountClient.GetOfficalFllowAccountUsersInfo(accessToken, openIds);if (!response.IsSuccessful()){if (response.ErrorCode == 42001){accessToken = await WeChatGetOfficalAccountToken(true);response = await _officalAccountClient.GetOfficalFllowAccountUsersInfo(accessToken, openIds);if (!response.IsSuccessful()){return (false,response.ErrorMessage,null);}}else{return (false,response.ErrorMessage,null);}}return (true,response.ErrorMessage,response.UserList.ToList());
}

在这里插入图片描述
在这里插入图片描述

用户关注/取消关注公众号监听

申请测试号,主要是提前写好接口
在这里插入图片描述
接入指南
在这里插入图片描述

/// <summary>
/// 微信公众号服务器传递过来的消息验证
/// </summary>
/// <returns></returns>
public bool ValidateMsg(string timestamp,string nonce,string signature)
{/* 验证微信服务器 */bool ret = client.VerifyEventSignatureForEcho(webhookTimestamp: timestamp,webhookNonce: nonce,webhookSignature: signature);return ret;
}class XXXParamModel 
{/// <summary>/// 微信加密签名,signature/// 结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。/// </summary>public string Signature { get; set; }/// <summary>/// 时间戳/// </summary>public string Timestamp { get; set; }/// <summary>/// 随机数/// </summary>public string Nonce { get; set; }/// <summary>/// 随机字符串/// </summary>public string Echostr { get; set; }
}/// <summary>
/// 微信公众号验证
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
[HttpGet]
public IActionResult OfficalAccountValidate([FromQuery]XXXParamModel param)
{var isValid = _officalAccountWechatHelper.ValidateMsg(param.Timestamp, param.Nonce, param.Nonce);if (isValid){//返回随机字符串则表示验证通过return Content(param.Echostr);}return Content("");
}

本地测试做好内网穿透

点击提交即可,验证通过即可
在这里插入图片描述
通过之后可以点击启用
在这里插入图片描述
需要处理菜单
在这里插入图片描述
在这里插入图片描述

//允许多次读取
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{//允许body重用app.Use(next => context =>{context.Request.EnableBuffering();return next(context);})
}/// <summary>
/// 微信公众号消息处理
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> OfficalAccountMessageHandler([FromQuery]XXXParamModel param)
{var isValid = _officalAccountWechatHelper.ValidateMsg(param.Timestamp, param.Nonce, param.Signature);if (!isValid){return Content("验证失败");}//过滤器或者中间件中调用var body = Request.Body;if (body.CanSeek){body.Seek(0L, SeekOrigin.Begin);}string bodyData = string.Empty;bodyData =await new StreamReader(body, Encoding.UTF8).ReadToEndAsync();Console.WriteLine(bodyData);return Content("");
}

在这里插入图片描述
解密

/// <summary>
/// 解密xml数据
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public WechatApiEvent DecryptXmlData(string xmlData)
{var xml = client.DeserializeEventFromXml(xmlData);return xml;
}

消息处理的完整的代码

/// <summary>
/// 微信公众号消息处理
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> OfficalAccountMessageHandler(
[FromQuery] OfficalAccountMessageHandlerParamModel param)
{
string responseData = string.Empty;
var isValid = _officalAccountWechatHelper.ValidateMsg(param.Timestamp, param.Nonce, param.Signature);
if (!isValid)
{return Content("验证失败");
}//过滤器或者中间件中调用
var body = Request.Body;
if (body.CanSeek)
{body.Seek(0L, SeekOrigin.Begin);
}
string bodyData = string.Empty;
bodyData = await new StreamReader(body, Encoding.UTF8).ReadToEndAsync();
var decryptXmlData = _officalAccountWechatHelper.DecryptXmlData(bodyData);
switch (decryptXmlData.MessageType.ToLower())
{case RequestMsgType.Text:break;case RequestMsgType.Location:break;case RequestMsgType.Image:break;case RequestMsgType.Voice:break;case RequestMsgType.Video:break;case RequestMsgType.ShortVideo:break;case RequestMsgType.Link:break;case RequestMsgType.MessageEvent:var eventType = decryptXmlData.Event;var openId = decryptXmlData.FromUserName;if (!string.IsNullOrEmpty(eventType)){switch (eventType){//关注case EventType.Subscribe://TODO 关注之后的处理//发送被动回复消息responseData =_officalAccountWechatHelper.SendTxtMsg("欢迎关注~~", openId, decryptXmlData.ToUserName);Console.WriteLine(responseData);break;//取消关注case EventType.Unsubscribe://TODO 取消关注之后的处理break;case EventType.Localtion:break;default:break;}}break;default:break;
}
return Content(responseData);
}

已有数据如何处理

公众号有获取关注的列表,根据列表中的openid获取unionid,小程序也有保存unionid,根据unionid关联起来就能实现之前数据的处理,不过没有登陆过的客户应该没法处理了,需要再客户登陆的时候获取unionid然后进行判定

公众号获取关注的列表

/// <summary>
/// 获取关注的用户列表
/// </summary>
/// <param name="token"></param>
/// <param name="nextOpenid"></param>
public async Task<CgibinUserGetResponse> GetOfficalAccountFollowUserList(string token,string nextOpenid="")
{var request = new CgibinUserGetRequest();request.AccessToken = token;if (!string.IsNullOrEmpty(nextOpenid)){request.NextOpenId = nextOpenid;}var userGetResponse = await client.ExecuteCgibinUserGetAsync(request);return userGetResponse;
}

关注公众号之后给用户发送消息

在这里插入图片描述
进行xml拼接加密处理,然后在微信调用关注的事件通知的时候返回即可

/// <summary>
/// 获取unix时间戳,扩展方法
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static long GetUnixTimeStampSeconds(this DateTime dt)
{long unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();return unixTime;
}/// <summary>
/// 解密文本的xml数据
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public string SendTxtMsg(string content, string toOpenId, string fromOpenId)
{var replyModel = new SKIT.FlurlHttpClient.Wechat.Api.Events.TextMessageReply(){ToUserName = toOpenId,FromUserName = fromOpenId,MessageType = "text",Content = content,CreateTimestamp = DateTime.Now.GetUnixTimeStampSeconds()};string replyXml = client.SerializeEventToXml(replyModel);return replyXml;
}

参考
uni-app使用微信小程序原生组件

这篇关于微信小程序和公众号打通,实现用户关注公众号送优惠券的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/932906

相关文章

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库

linux下shell脚本启动jar包实现过程

《linux下shell脚本启动jar包实现过程》确保APP_NAME和LOG_FILE位于目录内,首次启动前需手动创建log文件夹,否则报错,此为个人经验,供参考,欢迎支持脚本之家... 目录linux下shell脚本启动jar包样例1样例2总结linux下shell脚本启动jar包样例1#!/bin

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到