【微信公众号】将微信公众号消息里的FromUserName即OpenID转成UnionID

最近在调试微信公众号开发者模式,处理公众号消息,收到如下回调消息内容

<xml><ToUserName><![CDATA[gh_29********21]]></ToUserName>
<FromUserName><![CDATA[o*****4-7Z**************s]]></FromUserName>
<CreateTime>1481769005</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[李建华测试]]></Content>
<MsgId>6364149417119100008</MsgId>
</xml>

转成对象如下

{
    "ToUserName":"gh_29********1",
    "FromUserName":"oy****j4-7Z**********ys",
    "CreateTime":"1481769005",
    "MsgType":"text",
    "Content":"李建华测试",
    "MsgId":"6364149417119100008"
}

因为以前的网站分享业务使用的是另一套AppID,同一个用户在不同的AppID里获取到的OpenID是不同的,但是为了业务上的统一,准备都全部采用UnionID来作为用户唯一标识,所以需要将消息体中的FromUserName,也就是OpenID转成UnionID存储记录。以下是操作步骤:

1、获取Access_Token

                    var url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + 
              AirwayKeeperModel.MPAppID + "&secret=" + AirwayKeeperModel.MPAppSecret; var getToken = KTHttpRequest._Get(url); var access_token = Newtonsoft.Json.JsonConvert.DeserializeObject<WxAccessTokenModel>(getToken); if (access_token == null) throw new JSJException("获取token返回null"); if (access_token.Errcode != 0) throw new JSJException("获取token异常,错误码:" + access_token.Errcode + ",错误信息:" + access_token.Errmsg);

2、拉取用户信息

                    url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token.AccessToken +
                           "&openid=" + req.OpenID.Trim() + "&lang=zh_CN";
                    var wxUserInfoJson = KTHttpRequest._Get(url);
                    var wxUserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WxUserModel>(wxUserInfoJson);
                    if (null == wxUserInfo)
                        throw new JSJException("拉取用户微信信息返回null");

                    if (0 != wxUserInfo.Errcode)
                        throw new JSJException("拉取用户微信信息异常,错误码:" + wxUserInfo.Errcode + ",错误信息:" + wxUserInfo.Errmsg);

                    if (wxUserInfo.Subscribe != 1)
                    {
                        resp.ViewType = 1;
                        throw new JSJException("您还没有关注空铁管家<i>长按识别关注,即可领取</i>");
                    }

最终获取到了如下数据

{"subscribe":1,"openid":"oeQDZt0n4VCZ70wykBlGpANiXqdM","nickname":"背上吉他去旅行","sex":1,"language":"zh_CN","city":"昌平",

"province":"北京","country":"中国",

"headimgurl":"http://wx.qlogo.cn/mmopen/kBwGJuwqK95jdsBeGnNrSn9GVUib491JqY8zlzEOLa920YACUUkJXLLDpVYlpMouRl2RA6vv9ibVUEpgFE90LH3b3uj7AYRjZP/0",

"subscribe_time":1474964999,"unionid":"oGCG8t5SeisHItMA6sMUO0jPQTPw","remark":"","groupid":0,"tagid_list":[]}

直观查看如下:

这里我们就取到了想要的UnionID,但是回复公众号消息的时候还是需要用OpenID去回复的,所以需要将对应关系记录在数据库里,以便下次快速获取。

 搞定!

原文地址:https://www.cnblogs.com/jhli/p/6182504.html