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

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

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

{"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() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)throws CertificateException {// TODO Auto-generated method stub}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)throws CertificateException {// TODO Auto-generated method stub}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {// TODO Auto-generated method stubreturn 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后端设置了过滤,返回给微信服务器的响应是登陆界面。比如某个界面需要用户权限验证。

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

  1. Android Studio设置代理后显示:Cause: dl.google.com:443 failed to respond错误

    以前在Android Studio 的Preference设置中,设置了socks代理后,就能够正常的进行更新和自动下载依赖,最近老是有问题,今天在添加了新的依赖后,点编译按钮就显示 Cause: d ...

  2. 解决微信公众号OAuth出现40029(invalid code,不合法的oauth_code)的错误

    关于OAuth 官方教程:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&la ...

  3. 错误代码:40029, 错误信息:code 无效,微信原始报文:{“errcode“:40029,“errmsg“:“invalid code, rid: 63a4082d-7a02e2ba-1fa5

    错误代码:40029, 错误信息:code 无效,微信原始报文:{"errcode":40029,"errmsg":"invalid code, ri ...

  4. 微信小程序实现手机号登录:报40029, 错误信息:code 无效,微信原始报文:{“errcode“:40029,“errmsg“:“invalid code

    40029, 错误信息:code 无效,微信原始报文:{"errcode":40029,"errmsg":"invalid code, hints: ...

  5. 小程序--错误{errcode:40029,errmsg:invalid code, hints: [ req_id: weh8ka0297hc58 ]}

    1 小程序–错误{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: weh8ka029 ...

  6. 微信小程序登陆凭证校验出现{errcode:40029,errmsg:invalid code, hints: [ req_id: weh8ka0297hc58 ]}

    问题描述: 微信小程序登陆校验时需要使用临时登录凭证code ,appID和appsecret获取 session_key 和 openid 等.但是后台向微信服务器请求时一直报{"errc ...

  7. 微信小程序——登陆凭证校验报错{errcode:40029,errmsg:invalid code, hints: [ req_id: weh8ka0297hc58 ]}

    微信小程序登陆校验时需要使用临时登录凭证code ,appID和appsecret来向微信服务接口来获取 session_key 和 openid .但是后台向微信服务器请求时得到的一直是{" ...

  8. 微信小程序错误码40029 ——errcode: 40029, errmsg: invalid code, hints: [ req_id: gElDqRLnRa-744jra ]

    微信小程序二次开发的时候一定要注意:分清演示版与正式版,一般的二次开发都会有一个演示版与正式版,开发一般是用的演示版,而这时,我们的调的接口也是演示版的接口,那你的APPID也要相对应,否则便会报错4 ...

  9. 微信网页授权报错{errcode:40029,errmsg:invalid code}

    原因:前端开发在重定向链接上拿code时将code处理成小写了 因为微信网页授权涉及到用户的私密信息,所以会特别严格,区分大小写也是正规操作. 我们写的h5网页现在微信里获得用户权限,就需要走微信的微 ...

最新文章

  1. ASP.NET极限:页面导航 (翻译)
  2. mysql产生大量数据_mysql语句批量产生大量测试数据
  3. python判断互质_整数判断是否互质并求逆元的 python 实现
  4. 实现深拷贝的常用方法
  5. CollabNet Subversion Edge 安裝筆記 (1):基本安裝設定篇
  6. 【金融计量学】面板数据(自用笔记,第一次写)
  7. 110KV降压变电所电气一次部分及防雷保护设计
  8. Windows10新版本设置卓越性能
  9. vmware虚拟机搭建网络拓扑教程
  10. LVM精简卷(Thinly-Provisioned Logical Volumes)的扩容
  11. UPC 备战省赛第六场 Bumped!
  12. 六一儿童节 | TcaplusDB祝大小朋友节日快乐
  13. 如何优雅地管理微信数据库?
  14. iOS 苹果手机客户端微信支付调起失败--无法调起微信的原因
  15. Linux下挂载NTFS分区
  16. 深度学习方法在负荷预测中的应用综述(论文阅读)
  17. scrapy将爬取的数据存入mysql_scrapy爬取数据存入MySQL
  18. 服务器阵列状态显示verify,VerifyServerName 协议选项 [VERIFY]
  19. python毕业设计作品基于django框架 二手物品交易系统毕设成品(8)毕业设计论文模板
  20. 35dir分类目录伪静态规则文件全网最全.htaccess,httpd.ini,web.config

热门文章

  1. 老男孩mysql高级专业dba实战课程_老男孩MySQL高级专业DBA实战课程/高级运维DBA课程/MySQL视频教程下载...
  2. Stm32 Max6675 K型热电偶 采集温度值(代码+相关方法)
  3. VBA快速入门学习笔记
  4. 公钥密码系统主要依赖的三种数学难题:1.大整数因子分解问题 2.离散对数问题 (DLP问题) 3. 椭圆曲线上的离散对数问题(ECDLP)
  5. 视频图像处理技术优势安防视频监控应用
  6. 移动端网页知识点总结
  7. 企业级网络架构: 综合项目和网络升级(NETWORK05----DAY26)
  8. mysql正则表达式中括号单汉字_正则表达式中(括号) [方括号] {大括号}的区别
  9. 幸运与不幸-一起来编个有趣的故事
  10. 论文阅读(3):Image-Based 3D Object Reconstruction:State-of-the-Art and Trends in the Deep Learning Era