eption
*/
private JSONObject doPostUrl(String url, String param) throws ServerSystemException {
final String CONTENT_TYPE_TEXT_JSON = "application/json";
DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
String result;
try {
StringEntity stringEntity = new StringEntity(param);
stringEntity.setContentType(CONTENT_TYPE_TEXT_JSON);
stringEntity.setContentEncoding("UTF-8");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
httpClient.close();
} catch (IOException e) {
logger.error("执行POST请求发生错误!", e);
throw new ServerSystemException("执行POST请求发生错误!{}", e);
}
return JSONObject.parseObject(result);
}
获取code
在此之前,我想我们应该抽出一个微信工具类,专门来封装各种请求和RequestUtil来结合使用,是的,这是一个很好的选择。
WxRequestUtil.java
public calss WxRequestUtil {
@AutoWired
private WechatConfigBean config;
/**
* <p>获得静默授权的url</p>
* @return
*/
public String getSlientUrl() {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + config.getAppId() +
"&redirect_uri=" + URLEncoder.encode(config.getCallBackSlientUrl()) +
"&response_type=code" +
"&scope=snsapi_base" +
"&state=STATE#wechat_redirect";
return url;
}
}
接着我想我们应该参照开发文档来重定向到这个url,然后微信服务器会检查参数接着重定向到我们的回调地址,嗯嗯,你猜对了,就是参数带的那个redirect_uri,那么我们应该补充一下回调接口
获取openId
WechatController.java
/**
* 获得openId,静默授权
* @param code
* @param session
* @param response
*/
@RequestMapping(value = "/slient/check")
public RequestResult<String> callBackBase(@RequestParam(value = "code", required = false) String code, HttpServletResponse response) {
String openId = wechatService.getOpenIdBySlientAuthy(
return ResultUtil.success(openId);
}
我想我应该解释一下,控制器层我用的都是规范化的请求响应,不知道的可以参考我前面的博文。另外一点我需要说明的就是我们还需要一个service来处理获取openId的逻辑。
WechatService.java
/**
* 静默授权获得openId
* @param code
* @return
*/
public String getOpenIdBySlientAuthy(String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + config.getAppId() +
"&secret=" + config.getAppSecret() +
"&code=" + code +
"&grant_type=authorization_code";
//为了代码简便,此处省略异常处理
JSONObject jsonObject = doGetUrl(url);
return jsonObject.getString("openid");
}
至此,我们获得了openId,那么接着我们回到支付的话题上
微信支付
首先,我需要说明的是,微信支付的一个流程,至于为什么呢,我的目的很明确就是要描述清楚微信支付。我做支付的时候看过很多资料,有一个很深的体会就是代码复制来复制去,一大片一大片的代码看着心碎。在这里,我就不贴微信官方的流程图了,我相信你看着流程图会吓一跳,所以我选择不残害你。回到正题,微信支付最重要的就是三个步骤。
- 统一下单,得到预支付id, 次数需要你提供商户的信息以及商品的信息,然后得到一个预支付id(请相信我,其他返回的数据并没有什么实际的意义)
- 组装调起支付参数(我不知道叫什么名字更贴切,索性就这么叫吧,这个步骤其实就是使用预支付id,和其他的配置信息签名生成请求数据,返回至前台调用)
- 调起支付(使用jssdk或者h5接口调起支付)
其他的步骤就不是那么重要了,比如支付接口通知接口,可以根据自己的需求进行改写,这里我就不多说了。
统一下单
PayService.java
/**
* 获得统一下单参数
* @param openId
* @param totalFee
* @param ip
* @param body
* @return
*/
public String getPayParam(String openId, String totalFee, String ip, S