微信 开发诡异的40029错误invalid code错误 443 failed to respond错误的解决办法

微信 开发诡异的40029错误invalid code错误 443 failed to respond错误的解决办法情景:使用静默授权或感知授权的方式将请求绑定到微信公众号的菜单栏上。链接如下:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 当点击菜单按钮时微信

大家好,又见面了,我是你们的朋友全栈君。

情景:使用静默授权或感知授权的方式将请求绑定到微信公众号的菜单栏上。链接如下:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 当点击菜单按钮时微信服务器会将code通过redirect_uri指定的Url传给后台,通过code换取网页授权access_token,但当使用code换取授权码是不同的报invalid cod错误,而且时灵时不灵。让人崩溃。还有报api.weixin.qq.com:443 failed to respond

 

微信服务器不稳定,当我们开发完成应用准备上公众号测试时,老是刷新出空白界面,但有时又有进去,感觉碰运气似的,体验不好,然后去测试公众号一步一步调整,过程一脸蒙蔽,不停的提示如下错误:

微信 开发诡异的40029错误invalid code错误 443 failed to respond错误的解决办法

{“errcode”:40029,”errmsg”:”invalidcode, hints: [ req_id: Cq41ba0095th45 ]”}

网上有很多出现同样问题的小伙伴。官网上说40029对应错误是”不合法的oauth_code“,但哪里不合法呢,我用weinxin-mp-2.50.java包,我保证参数都正确。但还是在获得access_token时报错。

         有人说code失效,是因为你重复请求了,请求两次导致code失效(code只能使用一次),但我确定code没失效,而且是第一次使用。后来感觉是weinxin-mp-2.5.0.jar发的请求有问题,废话不多说,总之我现在有解决办法了。

创建一个SSLSocket,然后自己发给它,接受返回的JSON即可。

用jar包里有问题的方法是:WxMpOAuth2AccessToken  accessToken= wxMpService.oauth2getAccessToken(code);

解决代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import yui.bss.mgr.base.sec.IAcctMgr;
import yui.bss.model.dto.ext.sec.AcctDtox;
import yui.bss.security.util.YUISecurityUtils;
import yui.comn.code.BaseSvcMsgCode;
import yui.comn.model.UserInfo;
import yui.comn.util.ExpUtil;
import yui.ui.web.weixin.service.model.ReturnModel;
// 获取
	public String testQ(String code) {
		StringBuilder url = new StringBuilder();
	    url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
	    url.append("appid=").append(this.wxMpService.getWxMpConfigStorage().getAppId());
	    url.append("&secret=").append(this.wxMpService.getWxMpConfigStorage().getSecret());
	    url.append("&code=").append(code);
	    url.append("&grant_type=authorization_code");
		HttpClient httpclient = new DefaultHttpClient();
        httpclient = this.wrapClient(httpclient);
        
		BufferedReader in = null;
		String content = null;
		try {
			HttpClient client = getSecuredHttpClient(new DefaultHttpClient());
			// 实例化HTTP方法
			HttpGet request = new HttpGet();
			request.setURI(new URI(url.toString()));
			HttpResponse response = client.execute(request);

			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			content = sb.toString();
			System.out.println(content);
			Gson gson = new GsonBuilder().create();
			JsonParser jsonParser = new JsonParser();
			JsonObject  jsonObject = jsonParser.parse(content).getAsJsonObject();
			String openid = (String)jsonObject.get("openid").getAsString();
			return openid;
		} catch (Exception e) {
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	/**
	 * 重新包装httpclient对象,忽略证书验证
	 * 
	 * @param httpClient
	 * @return
	 * @author:Administrator
	 * @date:2014-9-2
	 */
	private static DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) {
		final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				@Override
				public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
						throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
						throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}
			};
			ctx.init(null, new javax.net.ssl.TrustManager[] { tm }, new SecureRandom());
			SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = httpClient.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
			return new DefaultHttpClient(ccm, httpClient.getParams());
		} catch (Exception e) {
			System.out.println("=====:=====");
			e.printStackTrace();
		}
		return null;
	}

在code的回调方法里:

/**
	 * 由微信回调的方法
	 * 
	 * @param module
	 * @param path
	 * @param code
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/wechat/{module}/{path}", method = RequestMethod.GET)
	public ModelAndView get(@PathVariable("module") String module, @PathVariable("path") String path,
			@RequestParam(value = "code", required = true) String code, HttpServletResponse response) {
		// System.out.println("所属模块 :" + module + "所属页面 :" + path);
		WxMpOAuth2AccessToken accessToken;
		try {
			ModelAndView mv = new ModelAndView(module + "/" + path);
			String openId = this.testQ(code);
	return mv;
		} catch (Exception e) {
			e.printStackTrace();
			ExpUtil.capture(BaseSvcMsgCode.failure, "", e, logger);
		}
		return null;

成功获得到openId:

{
	"access_token": "j8-XkADjlgxTWY2l0UlztZ2ejcSaz-FD0obHf9NYqIq1aNX5n0w9-P03qb6yAtVbdyq7hTKu6Dc-TIiJc9_He3kGtTbjcoYAiow-W6yssEY",
	"expires_in": 7200,
	"refresh_token": "M2sGfzQt0EcB8cojNKa4xC8jSVVYDj21dZ36HYomU2Frbl4ZbIKrGVNL3fxPLkA-Tu1h9z0LRTKWlzbw8bvxgXuTaTu4PNrsiLMbw3DDhIg",
	"openid": "oUOwvw_c1v8Ym4WejCJeu4uFSYjg",
	"scope": "snsapi_base"
}

然后使用GSOn解决json数据.

 

顺带提醒一下微信支付成功后的回调链接。

1.      注意一下回调方法不会只回调一次,需要一个字段表示已经收到微信服务器发送的该订单支付回调链接。

2.      如果收不到请求,请注意一下是否javaweb后端设置了过滤,返回给微信服务器的响应是登陆界面。比如某个界面需要用户权限验证。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/132259.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • ldd命令 ubuntu_Linux ldd 命令 command not found ldd 命令详解 ldd 命令未找到 ldd 命令安装 – CommandNotFound ⚡️ 坑否…[通俗易懂]

    ldd命令 ubuntu_Linux ldd 命令 command not found ldd 命令详解 ldd 命令未找到 ldd 命令安装 – CommandNotFound ⚡️ 坑否…[通俗易懂]显示行号|选择喜欢的代码风格默认GitHubDuneLakeSidePlateauVibrantBlueEightiesTranquilldd命令打印程序和库的共享库依赖项。注意:ldd不是一个可执行程序,而只是一个Shell脚本。ldd命令安装:-bash:ldd:commandnotfound#Debianapt-getinstalllibc-bin#Ubuntuapt-…

  • mysql 提示表不存在的解决方法error: 1146: Table doesn‘t exist

    mysql 提示表不存在的解决方法error: 1146: Table doesn‘t exist直接拷贝数据库导致提示表不存在的解决方法电脑重装系统后把原来的mysqldata复制进去后大部分表是可以访问的,但是有几个表提示表不存在:error:1146:Table’a_content’doesn’texist这种情况就是要把原来mysql安装目录data里的ibdata1也要拷贝过去INNODB是MYSQL数据库一种流行的数据库引擎,支持事务(行级),在企业级应…

  • Django(20)ORM模型迁移命令

    Django(20)ORM模型迁移命令迁移命令makemigrations:将模型生成迁移脚本。模型所在的app,必须放在settings.py中的INSTALLED_APPS中。这个命令有以下几个常用选项:app_label:后面可

  • 51单片机:LED流水灯(仿真+代码)

    51单片机:LED流水灯(仿真+代码)这次用单片机做个简单的流水灯。先给大家看一下仿真软件的电路(软件为Proteus)上图就是用仿真软件制作的线路原理图AT89C51RC2:单片机BUTTON:按键CAP:电容CRYSTAL:晶振LED-GERRN:LED灯(绿色)RES:电阻接下来是程序部分(软件为keil)#include”reg51.h” //此文件中定义了单片机的一些特殊功能寄存器#include…

  • html中设置背景图片为平铺,html背景图片怎么设置平铺方式

    html中设置背景图片为平铺,html背景图片怎么设置平铺方式在html中,可利用background-repeat属性来设置背景图片的平铺方式;当属性值设置为“repeat”时可向垂直和水平方向平铺,“repeat-x”时可水平平铺,“repeat-y”时可垂直平铺,“no-repeat”时不平铺。本教程操作环境:windows7系统、CSS3&&HTML5版、DellG3电脑。html背景图片设置平铺方式div{border:1px…

  • python求平均值的怎么编写,python 怎么求平均值[通俗易懂]

    python求平均值的怎么编写,python 怎么求平均值[通俗易懂]python求平均值的方法:首先新建一个python文件;然后初始化sum总和的值;接着循环输入要计算平均数的数,并计算总和sum的值;最后利用“总和/数量”的公式计算出平均数即可。本文操作环境:Windows7系统,python3.5版本,DellG3电脑。首先我们先来了解一下计算平均数的IPO模式.输入:待输入计算平均数的数。处理:平均数算法输出:平均数明白了程序的IPO模式之后,我们打开本…

    2022年10月30日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号