將微信開放平台下的小程序應用與公眾號通過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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM