将微信开放平台下的小程序应用与公众号通过openid进行关联操作
公司做的是第三方开放平台,为了使用户的小程序信息与公众号信息关联起来(通过openid关联)
不考虑使用将公众号与小程序绑定在同一个开放平台下,通过获取UnionID 机制(开放平台下可绑定账号受限,只有50个),不适应公司几千商户的应用场景
前提:用户得将小程序和公众号分别授权给我们的开放平台
第一步 在小程序里使用 web-view 来嵌套H5授权地址,得把小程序openid加在授权页面
<web-view src='{{web_url}}'> </web-view>
/**
* 页面的初始数据
*/
data: {
web_url: ''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
this.setData({
web_url: app.globalData.wxgh_oauth_url + '/Wxgh/Index?openid=' + app.globalData.openid
});
console.log(this.data.web_url);
},
第二步 处理第一步的页面路径,将页面参数拼接好,再去调用C# 写的拼接授权路径,
<body> <input type="hidden" id="hiddenBaseUrl" value="@ViewBag.BaseUrl" /> <div class="error"> </div> <div class="go-wxapp"> <button type="button" id="btn" class="go-wxapp-btn"> 返回老板助手</button> </div> </body> </html> <script> $(function () { $('.go-wxapp').hide(); getAuthorizeUrl(); }) $('#btn').click(function () { wx.miniProgram.switchTab({ url: '/pages/index/index' }); }); function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r != null) return unescape(r[2]); return null; //返回参数值 } function getAuthorizeUrl() { var url = $('#hiddenBaseUrl').val(); $.ajax({ type: 'get', url: url + '/api/services/app/WxghService/GetAuthorizeUrl?wxapp_openid=' + getUrlParam('openid'), data: {}, success: (res) => { console.log('获取授权链接'); console.log(res); if (res.success) { var _result = res.result; if (_result.success) { if (_result.code == 2000) {//已关注 wx.miniProgram.switchTab({ url: '/pages/index/index' }); } else { window.location.href = _result.data; } } else { $('.error').html("异常,因为:" + _result.message); $('.go-wxapp').show(); } // window.location.href = res.result; } else { alert("授权异常,请返回"); } } }); } </script>
C# 提供接口获取公众号授权地址
代码中 OAuthApi.GetAuthorizeUrl 方法是对下面地址的封装
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
#region 拼接授权链接地址 public async Task<Result> GetAuthorizeUrl(string wxapp_openid) { var _result = new Result(); try { if (string.IsNullOrWhiteSpace(wxapp_openid)) { _result.success = false; _result.message = "关联小程序参数为空"; return _result; } var user = await _wxappUserRepository.GetAllListAsync(a => a.openid == wxapp_openid.Trim()); if (user.Count == 0) { _result.success = false; _result.message = "请从小程序进入"; return _result; } var wxghUserRelation = await _wxghUserRelationRepository.FirstOrDefaultAsync(a => a.wxapp_openid == wxapp_openid.Trim()); if (wxghUserRelation != null) { _result.success = true; _result.message = "已关联公众号"; _result.code = (int)ResultCodeEnum.已关联公众号; return _result; } var redirectUrl = base_url + "Wxgh/WxAuthorize?wxapp_openid=" + wxapp_openid.Trim(); _result.data = OAuthApi.GetAuthorizeUrl(wxghAppid, redirectUrl, "boss", OAuthScope.snsapi_base); _result.success = true; } catch (Exception ex) { _result.success = false; _result.message = ex.Message; } return _result; } #endregion
code换取openid,并将小程序openid与公众号openid绑定
<head> <meta name="viewport" content="width=device-width" /> <meta charset="UTF-8"> <!-- for HTML5 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="~/JavaScript/jquery-3.4.1.min.js"></script> <script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script> <title>绑定公众号</title> </head> <body> <div class="error"> @_result </div> @if (!string.IsNullOrWhiteSpace(_result)) { <div class="go-wxapp"> <button type="button" id="btn" class="go-wxapp-btn"> 返回老板助手</button> </div> } </body> </html> <script> $('#btn').click(function () { wx.miniProgram.switchTab({ url: '/pages/index/index' }); }); </script>
public IActionResult WxAuthorize(string code, string state, string wxapp_openid) { Logger.ErrorFormat("code={0} state={1} wxapp_openid={2}", code, state, wxapp_openid); try { if (string.IsNullOrWhiteSpace(code)) { ViewBag.Result = "异常,参数CODE为空,请点击返回老板助手"; return View(); } code = code.Trim(); if (string.IsNullOrWhiteSpace(state)) { ViewBag.Result = "异常,参数STATE为空,请点击返回老板助手"; return View(); } state = state.Trim(); if (string.IsNullOrWhiteSpace(wxapp_openid)) { ViewBag.Result = "异常,参数小程序ID为空,请点击返回老板助手"; return View(); } wxapp_openid = wxapp_openid.Trim(); var accessToken = Senparc.Weixin.MP.AdvancedAPIs.OAuthApi.GetAccessToken(wxghAppid, wxghAppSecret, code); if (accessToken.errcode != 0) { ViewBag.Result = "错误代码:" + accessToken.errcode + " 说明:" + accessToken.errmsg + ",请点击返回老板助手"; return View(); } var wxghUser = _wxghUserRelationRepository.FirstOrDefault(a => a.wxapp_openid == wxapp_openid); if (wxghUser != null) { ViewBag.Result = "已关联公众号,请点击返回老板助手"; return View(); } wxghUser = _wxghUserRelationRepository.FirstOrDefault(a => a.wxgh_openid == accessToken.openid); if (wxghUser != null) { ViewBag.Result = "您已关联公众号,请点击返回老板助手"; return View(); } wxghUser = new wxgh_user_relation() { access_token = accessToken.access_token, bind_date = DateTime.Now, expires_in = DateTime.Now.AddSeconds(accessToken.expires_in), refresh_token = accessToken.refresh_token, wxapp_openid = wxapp_openid, wxgh_openid = accessToken.openid }; _wxghUserRelationRepository.Insert(wxghUser); CurrentUnitOfWork.SaveChanges(); ViewBag.Result = "绑定成功,请点击返回老板助手"; return View(); } catch (Exception ex) { ViewBag.Result = "异常," + ex.Message + ",请点击返回老板助手"; return View(); } }
代码里使用了.NET ABP 、盛派公司的 盛派微信SDK