记录微信支付的操作流程
一 ,获取 openId 准备工作
1. 微信公账号的appId 、设置业务域名的验证文件 MP_verify_xxxx.txt
2. 微信公账号的 secret
只需要 1、2 ,就可以拿到openId 了
-------------------- 下面的这些,后续支付会用到 -------------------------------------------
3. 微信支付的商户ID
4. 微信支付的证书序列号
5. 微信支付的 证书文件
6. 微信支付的 v3key
@Value("${wechat.pay.appId:}")
private String WECHAT_APPID;
@Value("${wechat.pay.secret:}")
private String WECHAT_SECRET;
@Value("${wechat.pay.mchId:}")
private String WECHAT_MCHID;
@Value("${wechat.pay.serialNo:}")
private String WECHAT_SERIALNO;
@Value("${wechat.pay.callbackurl:}")
private String WECHAT_NOTIFY_URL;
@Value("${wechat.pay.apiclientKey}")
private String WECHAT_FILE_PATH;
@Value("${wechat.pay.apiV3Key:}")
private String WECHAT_APIV3KEY;
二. 获取授权的URL,拿到code
这一步,需要将上面微信公众号的验证文件,放到你对应的域名下面,添加域名的时候会校验,放的位置不对的话,校验会不通过
放好之后,就可以拼接获取code的链接了
public static void main(String[] args) {
String appID = "XXX";
String yourUrl = "https://xxxx.com";
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appID +"&redirect_uri=" + URLEncoder.encode(yourUrl) + "%2Faccout%2Fpayment&response_type=code&scope=snsapi_base&state="+ UUIDUtil.get32UUID() +"#wechat_redirect";
}
如果想获取微信用户的其他信息,可通过改变 scope 参数值,来获取用户的信息,
官方参数说明,点击直达
三 ,通过code,获取openId
将第二步的url,返给前端,前端会拿到一个code,回传给后端处理,就可以拿到用户的openId了,具体代码
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@Slf4j
public class WxUtil {
private static final String WECHAT_OAUTH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
/**
* 通过code换取网页授权access_token
*/
public static ResultData getAccessToken(String appid, String secret, String code) {
try {
String param = "appid=" + appid
+ "&secret=" + secret
+ "&code=" + code
+ "&grant_type=authorization_code";
log.info("获取accessToke请求参数:{}", param);
String result = HttpUtil.get(WECHAT_OAUTH_ACCESS_TOKEN_URL + "?" + param, 60000);
log.info("获取accessToke请求参数:{}", result);
if (StringUtils.isEmpty(result)) {
log.error("{}:获取微信access_token返回为空", appid);
return ResultData.fail("获取微信access_token返回为空");
}
JSONObject resultJson = JSONObject.parseObject(result);
if (StringUtils.isEmpty(resultJson.getString("access_token")) || StringUtils.isEmpty(resultJson.getString("openid"))) {
return ResultData.fail(resultJson.getString("errmsg"));
}
return ResultData.success("获取微信信息成功",resultJson);
} catch (Exception e) {
log.error("appid:{},{},获取accessToke异常", appid, code, e);
return ResultData.fail("获取accessToke异常");
}
}
}
如果只想获取openId , 这行代码就可以了 ,resultJson.getString("openid");