【Golang】golang开发微信公众号网页授权功能

基本流程

微信公众号服务号的网页授权功能开发,主要是通过js跳转到一个微信提供的url

然后微信会弹出获取昵称头像的按钮

允许获取后,会回跳到我们的网址上,并且带着一个code参数

 

我们拿到code参数,调用接口获取到获取到昵称头像、以及openid。这样就拿到了微信客户的主要信息

我们数据库会存储一个对应关系,微信openid对应的我们用户的唯一标识,这样就能直接登录到系统了。

 

实际案例

比如我的唯一在线客服系统,客服人员点击模板消息的时候,就是访问以下网址

http://127.0.0.1:8081/wechatTransfer?ent_id=xxxxxx

这个页面什么也没干,就是把ent_id下客户的微信公众号APP_ID以及配置的跳转HOST拼接到下面的url,然后直接跳转

这里注意一下,我们自己的回跳的地址,如果是带着参数的,需要urlencode编码一下

                var url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APP_ID
                    +"&redirect_uri="+HOST
                    +"%2FwechatKefu%3Fent_id%3D"+ENT_ID
                    +"%26kefu_name%3D"+KEFU_NAME
                    +"&response_type=code&scope=snsapi_userinfo#wechat_redirect"
                document.location.href=url;

 

用户点击允许获取信息后,会带着code回跳到

http://127.0.0.1:8081/wechatKefu?ent_id=xxxx&kefu_name=xxxxx&code=xxxxxxx

 在页面中通过code获取微信openid和头像昵称

主要的逻辑代码如下,这里面的appId appSecret等信息需要使用自己的

引入的包

    "github.com/silenceper/wechat/v2"
    "github.com/silenceper/wechat/v2/cache"
    offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
    "github.com/silenceper/wechat/v2/officialaccount/oauth"

 

//获取微信用户信息
func GetWechatUserInfo(weixinCode, entId string) (oauth.UserInfo, error) {
    var userinfo oauth.UserInfo


    cfg := &offConfig.Config{
        AppID:     APP_ID,
        AppSecret: AppSecret,
        Token:     Token,
        Cache: memory,
    }
    wc := wechat.NewWechat()
    officialAccount := wc.GetOfficialAccount(cfg)
    oauth := officialAccount.GetOauth()
    accessToken, err := oauth.GetUserAccessToken(weixinCode)
    if err != nil {
        return userinfo, err
    }
    userinfo, err = oauth.GetUserInfo(accessToken.AccessToken, accessToken.OpenID, "")
    if err != nil {
        return userinfo, err
    }
    return userinfo, nil
}

拿到openId ,查出来绑定的用户,生成好对应的token信息直接跳转到自己的后台

posted @ 2022-07-22 22:39  唯一客服系统开发笔记  阅读(535)  评论(0编辑  收藏  举报