前端通过调用地址获取到code,
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${user_appid}& redirect_uri=${encodeURIComponent('http://192.168.3.189/h5/pages/login/loginByAccount/getUserAccount')}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`;
然后我提交code提到到服务端获取openid
后端服务代码
public static string GetOpenIdUrl(string appId, string secret, string code, string grantType = "authorization_code")
{
object[] args = new object[] { appId, secret, code, grantType };
var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type={3}",args);
return url;
}
/// <summary>
/// 获取openid
/// </summary>
/// <param name="appId"></param>
/// <param name="secret"></param>
/// <param name="code"></param>
/// <param name="grantType"></param>
/// <returns></returns>
public static string GetOpenid(string appId, string secret, string code, string grantType = "authorization_code")
{
string requestUri = GetOpenIdUrl(appId, secret, code, grantType);
var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
string openid = string.Empty;
if (!obj.TryGetValue("openid", out openid))
{
//Log.Info($"获取openid失败appId={appId},secret={secret},code={code}");
}
return openid;
}
但我后端反回40029错误代码,请问要怎么才能得到正确的结果?
你好,查看一下appId与Appsecret是否匹配。。看下后端是否改了。