前提
有个需求,需要限制小程序的抽奖只能在某个群内,需要知道谁在群里面,但是微信并没有提供谁在群里面的方法,不过提供了获取群id的方法,这样加上限制分享就能保证群里的参加,即时分享出去了,判断来源的时候也不是来自于群了,就不允许用户参与。
需要的方法
wx.login
wx.getGroupEnterInfo
加密解密数据
解密解密官方代码c++、php、node、python
没有java和c#的代码,目前需要c#代码
解密流程
需要的nuget包
skit.flurlhttpclient.wechat.api.2.35.0
实现代码
微信小程序
wxml
<view style="width: 80%;margin: 0 auto;margin-top: 30rpx;">
<text>微信群id:</text>
<text>{{groupId}}</text>
<view>
<button bind:tap="copyGroupId">复制</button>
</view>
</view>
js
// pages/wechatgroupinfo/wechatgroupinfo.js
Page({
/**
* 页面的初始数据
*/
data: {
groupId: ""
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
wx.setNavigationBarTitle({
title: '获取微信群信息',
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
let that = this;
wx.login({
success: (res) => {
if (res.errMsg == "login:ok") {
const code = res.code;
wx.getGroupEnterInfo({
success(resData) {
if (resData.errMsg === "getGroupEnterInfo:ok") {
const iv = resData.iv;
const encryptedData = resData.encryptedData;
that.getWechatGroupId(code, iv, encryptedData);
} else {
wx.showToast({
title: 'wx.getGroupEnterInfo出错',
})
}
},
fail() {
wx.showToast({
title: 'wx.getGroupEnterInfo:' + resData.errMsg,
})
}
})
} else {
wx.showToast({
title: 'wx.login:' + res.errMsg,
})
}
},
fail: () => {
wx.showToast({
title: 'wx.login出错',
})
}
})
},
/**
* 获取微信群id
* @param {String} code 登录的id
* @param {String} iv 偏移量
* @param {String} encryptData 加密的数据
* @returns 微信群id
*/
getWechatGroupId(code, iv, encryptData) {
let that = this;
wx.request({
method: "POST",
url: 'http://localhost:5000/v1/user/GetWechatGroupId',
data: JSON.stringify({
code,
iv,
encryptData
}),
success: (response) => {
console.log(response);
if (response.data && response.data.success) {
that.setData({
groupId: response.data.response
})
} else {
wx.showToast({
title: response.data.msg,
})
}
},
fail: () => {
wx.showToast({
title: '后台获取微信群id失败',
})
}
})
},
/**
* 复制微信群组
*/
copyGroupId() {
wx.setClipboardData({
data: this.data.groupId,
success(res) {
wx.showToast({
title: '复制成功',
})
}
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
C#后台
获取微信群id接口
/// <summary>
/// 获取微信的群组id
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<MessageModel<string>> GetWechatGroupId([FromBody] GetWechatGroupIdParamModel param)
{
var result = new MessageModel<string>();
var res = await weChatMiniProgramHelper.GetWechatGroupId(param.Code, param.Iv, param.EncryptData);
result.Success = !string.IsNullOrEmpty(res);
result.Msg = result.Success ? "成功" : "失败";
result.Response = res;
return result;
}
/// <summary>
/// 单例模式注入
/// </summary>
public class WeChatMiniProgramClient
{
public WechatApiClient Instance { get; private set; }
/// <summary>
/// 构造函数注入
/// </summary>
/// <param name="wechatConfig"></param>
public WeChatMiniProgramClient(IOptions<WechatConfigModel> wechatConfig)
{
var options = new WechatApiClientOptions()
{
AppId = wechatConfig.Value.MiniProgramAppId,
AppSecret = wechatConfig.Value.MiniProgramAppSecret,
MidasAppKey = "",//米大师相关服务 AppKey,不用则不填
ImmeDeliveryAppKey = "",//即时配送相关服务 AppKey,不用则不填
ImmeDeliveryAppSecret = ""//即时配送相关服务 AppSecret,不用则不填
};
Instance = new WechatApiClient(options);
}
}
//weChatMiniProgramHelper下的方法
/// <summary>
/// 获取微信群id
/// </summary>
/// <param name="code"></param>
/// <param name="iv"></param>
/// <param name="encryptData"></param>
/// <returns></returns>
public async Task<string> GetWechatGroupId(string code, string iv, string encryptData)
{
if (string.IsNullOrEmpty(iv) || iv.Length != 24)
{
return string.Empty;
}
if (string.IsNullOrEmpty(encryptData) || encryptData.Length < 1)
{
return string.Empty;
}
//WechatApiClient客户端
var client = weChatMiniProgramClient.Instance;
try
{
var userLoginRequest = new SnsJsCode2SessionRequest();
userLoginRequest.JsCode = code;
var loginInfo = await client.ExecuteSnsJsCode2SessionAsync(userLoginRequest);
if (!loginInfo.IsSuccessful())
{
return string.Empty;
}
var sessionKey = loginInfo.SessionKey;
if (string.IsNullOrEmpty(sessionKey) || sessionKey.Length != 24)
{
return string.Empty;
}
var encryptDataDecode = Convert.FromBase64String(encryptData);
var jsonStr = AESUtility.DecryptWithCBC(sessionKey, iv, encryptData);
if (string.IsNullOrEmpty(jsonStr))
{
return string.Empty;
}
var openGidDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);
return openGidDic["opengid"];
}
catch (Exception ex)
{
logger.LogError($"获取微信群id失败\r\n{ex.Message}");
throw new Exception(ex.Message, ex.InnerException);
}
}
测试
如果直接加密解密会报错Specified initialization vector (IV) does not match the block size for this algorithm
,需要先base64解码一下
AESUtility.cs源代码,来自skit.flurlhttpclient.wechat
/// <summary>
/// 基于 CBC 模式解密数据。
/// </summary>
/// <param name="keyBytes">AES 密钥字节数组。</param>
/// <param name="ivBytes">加密使用的初始化向量字节数组。</param>
/// <param name="cipherBytes">待解密数据字节数组。</param>
/// <returns>解密后的数据字节数组。</returns>
public static byte[] DecryptWithCBC(byte[] keyBytes, byte[] ivBytes, byte[] cipherBytes)
{
if (keyBytes == null) throw new ArgumentNullException(nameof(keyBytes));
if (ivBytes == null) throw new ArgumentNullException(nameof(ivBytes));
if (cipherBytes == null) throw new ArgumentNullException(nameof(cipherBytes));
using (SymmetricAlgorithm aes = Aes.Create())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = keyBytes;
aes.IV = ivBytes;
using ICryptoTransform transform = aes.CreateDecryptor();
return transform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
}
}
/// <summary>
/// 基于 CBC 模式解密数据。
/// </summary>
/// <param name="encodingKey">经 Base64 编码后的 AES 密钥。</param>
/// <param name="encodingIV">经 Base64 编码后的 AES 初始化向量。</param>
/// <param name="encodingCipherText">经 Base64 编码后的待解密数据。</param>
/// <returns>解密后的文本数据。</returns>
public static string DecryptWithCBC(string encodingKey, string encodingIV, string encodingCipherText)
{
if (encodingKey == null) throw new ArgumentNullException(nameof(encodingKey));
if (encodingCipherText == null) throw new ArgumentNullException(nameof(encodingCipherText));
byte[] plainBytes = DecryptWithCBC(
keyBytes: Convert.FromBase64String(encodingKey),
ivBytes: Convert.FromBase64String(encodingIV),
cipherBytes: Convert.FromBase64String(encodingCipherText)
);
return Encoding.UTF8.GetString(plainBytes);
}
/// <summary>
/// 基于 CBC 模式加密数据。
/// </summary>
/// <param name="keyBytes">AES 密钥字节数组。</param>
/// <param name="ivBytes">加密使用的初始化向量字节数组。</param>
/// <param name="plainBytes">待加密数据字节数组。</param>
/// <returns>加密后的数据字节数组。</returns>
public static byte[] EncryptWithCBC(byte[] keyBytes, byte[] ivBytes, byte[] plainBytes)
{
if (keyBytes == null) throw new ArgumentNullException(nameof(keyBytes));
if (ivBytes == null) throw new ArgumentNullException(nameof(ivBytes));
if (plainBytes == null) throw new ArgumentNullException(nameof(plainBytes));
using (SymmetricAlgorithm aes = Aes.Create())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = keyBytes;
aes.IV = ivBytes;
using ICryptoTransform transform = aes.CreateEncryptor();
return transform.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
}
}
/// <summary>
/// 基于 CBC 模式加密数据。
/// </summary>
/// <param name="encodingKey">经 Base64 编码后的 AES 密钥。</param>
/// <param name="encodingIV">经 Base64 编码后的 AES 初始化向量。</param>
/// <param name="plainText">待加密文本。</param>
/// <returns>经 Base64 编码的加密后的数据。</returns>
public static string EncryptWithCBC(string encodingKey, string encodingIV, string plainText)
{
if (encodingKey == null) throw new ArgumentNullException(nameof(encodingKey));
if (plainText == null) throw new ArgumentNullException(nameof(plainText));
byte[] plainBytes = EncryptWithCBC(
keyBytes: Convert.FromBase64String(encodingKey),
ivBytes: Convert.FromBase64String(encodingIV),
plainBytes: Encoding.UTF8.GetBytes(plainText)
);
return Convert.ToBase64String(plainBytes);
}