java对接微信支付接口_一 微信支付分对接(java)

1.支付分介绍

微信支付分是对个人的身份特质、支付行为、使用历史等情况的综合计算分值,旨在为用户提供更简单便捷的生活方式。

微信用户可以在具体应用场景中,开通微信支付分。开通后,用户可以在【微信—>钱包—>支付分】中查看分数和使用记录。(即需在应用场景中使用过一次,钱包才会出现支付分入口)。

官方最新API地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/payscore/chapter1_1.shtml

需要联系微信方开通服务,分配服务id即 service_id,同时需要证书序列号和密钥以及ipv3密钥等服务。

2.需要注意的点

接口调用使用微信支付API v3

相较于的之前微信支付API,主要区别是:

·遵循统一的Restful的设计风格

·使用JSON作为数据交互的格式,不再使用XML

·使用基于非对称密钥的SHA256-RSA的数字签名算法,不再使用MD5或HMAC-SHA256

·不再要求HTTPS客户端证书

·使用AES-256-GCM,对回调中的关键信息进行加密保护

关于请求需要引入maven

5f187844dda1

maven配置

使用postman调试

需要参考:https://github.com/wechatpay-apiv3/wechatpay-postman-script

同时正确键入 private_key(证书密钥)、mch_id(商户号)、serialNo(证书序列号)

代码调用加密部分

/**

* 获取请求头

* @param method 方法

* @param url 地址

* @param body 传输json

* @return

* @throws IOException

* @throws SignatureException

* @throws NoSuchAlgorithmException

* @throws InvalidKeyException

*/

public  MapgetToken(String method, HttpUrl url, String body)throws IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {

String nonceStr =  CreateNumber.getRandom(32);

long timestamp = System.currentTimeMillis() /1000;

String message =buildMessage(method, url, timestamp, nonceStr, body);

String signature = sign(message.getBytes(StandardCharsets.UTF_8));

Map map=new HashMap();

map.put("sign","mchid=\""+MCH_ID+"\","

+"nonce_str=\""+nonceStr+"\","

+"timestamp=\""+timestamp+"\","

+"serial_no=\""+SERIAL_NO+"\","

+"signature=\""+signature+"\"");

map.put("timestamp",timestamp);

map.put("noncestr",nonceStr);

return map;

}

/**

* 签名 生成 signature

* @param message

* @return

* @throws NoSuchAlgorithmException

* @throws IOException

* @throws SignatureException

* @throws InvalidKeyException

*/

public Stringsign(byte[] message)throws NoSuchAlgorithmException, IOException,  SignatureException, InvalidKeyException {

Signature sign = Signature.getInstance("SHA256withRSA");

sign.initSign(getPrivateKey(KEYSTORE_PATH));

sign.update(message);

return Base64.getEncoder().encodeToString(sign.sign());

}

/**

* 拼接传输数据

* @param method

* @param url

* @param timestamp

* @param nonceStr

* @param body

* @return

*/

static StringbuildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {

String canonicalUrl = url.encodedPath();

if (url.encodedQuery() !=null) {

canonicalUrl +="?" + url.encodedQuery();

}

System.err.println(method +"\n"

+ canonicalUrl +"\n"

+ timestamp +"\n"

+ nonceStr +"\n"

+ body +"\n");

return method +"\n"

+ canonicalUrl +"\n"

+ timestamp +"\n"

+ nonceStr +"\n"

+ body +"\n";

}

/**

* 获取密钥

* @param filename

* @return

* @throws IOException

*/

public  PrivateKeygetPrivateKey(String filename)throws IOException {

String content =new String(Files.readAllBytes(Paths.get(filename)), "utf-8");

try {

String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")

.replace("-----END PRIVATE KEY-----", "")

.replaceAll("\\s+", "");

KeyFactory kf = KeyFactory.getInstance("RSA");

return kf.generatePrivate(

new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));

}catch (NoSuchAlgorithmException e) {

throw new RuntimeException("当前Java环境不支持RSA", e);

}catch (InvalidKeySpecException e) {

throw new RuntimeException("无效的密钥格式");

}

}

/**

* post请求 租借、修改、撤销、完结等使用

* @param url

* @param params

* @return

*/

public  MapsendBodyPost(String url, Object params) {

OutputStreamWriter out =null;

BufferedReader in =null;

StringBuilder result =new StringBuilder();

Map map =new HashMap<>();

try {

URL realUrl =new URL(url);

HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

String param = JSONObject.toJSONString(params);

// 发送POST请求必须设置如下两行

conn.setDoOutput(true);

conn.setDoInput(true);

// POST方法

conn.setRequestMethod("POST");

// 设置通用的请求属性

conn.setRequestProperty("accept", "*/*");

conn.setRequestProperty("connection", "Keep-Alive");

conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

conn.setRequestProperty("Content-Type", "application/json");

map = getToken("POST", HttpUrl.parse(url), param);

conn.setRequestProperty("Authorization", "WECHATPAY2-SHA256-RSA2048" +" " + map.get("sign"));

conn.connect();

// 获取URLConnection对象对应的输出流

out =new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);

// 发送请求参数

logger.info("param:" + param);

out.write(param);

// flush输出流的缓冲

out.flush();

// 定义BufferedReader输入流来读取URL的响应

in =new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));

String line;

while ((line = in.readLine()) !=null) {

result.append(line);

}

}catch (Exception e) {

e.printStackTrace();

result.append("error");

}

// 使用finally块来关闭输出流、输入流

finally {

try {

if (out !=null) {

out.close();

}

if (in !=null) {

in.close();

}

}catch (IOException ex) {

ex.printStackTrace();

result.append("error");

}finally {

Map maps =new HashMap<>();

if (result.toString().contains("error")) {

maps.put("result", result.toString());

}else {

maps.put("result", JSONObject.parseObject(result.toString()));

}

maps.put("sign", map.get("sign"));

maps.put("timestamp", map.get("timestamp"));

maps.put("noncestr", map.get("noncestr"));

return maps;

}

}

}

/**

* Get请求 多用于查询租借订单

* @param url

* @param params

* @param param

* @return

*/

public  StringdoGet(String url, Map params,String param) {

String result ="";

HttpClient httpClient = HttpClientBuilder.create().build();

HttpGet httpGet =null;

try {

URIBuilder uriBuilder =new URIBuilder(url);

if (null != params && !params.isEmpty()) {

for (Map.Entry entry : params.entrySet()) {

uriBuilder.addParameter(entry.getKey(), entry.getValue());

}

}

URI uri = uriBuilder.build();

// 创建get请求

httpGet =new HttpGet(uri);

httpGet.setHeader("accept", "*/*");

httpGet.setHeader("connection", "Keep-Alive");

httpGet.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

httpGet.setHeader("Authorization","WECHATPAY2-SHA256-RSA2048"+" "+getToken("GET", HttpUrl.parse("https://api.mch.weixin.qq.com/v3/payscore/serviceorder?"+param),"").get("sign"));

HttpResponse response = httpClient.execute(httpGet);

Header[] s=httpGet.getHeaders("Authorization");

System.err.println(String.valueOf(s[0]));

result = EntityUtils.toString(response.getEntity());

}catch (Exception e) {

ExceptionUtils.getStackTrace(e);

result="error";

return result;

}finally {

if (null != httpGet) {

httpGet.releaseConnection();

}

}

return result;

}

使用接口发起调用即可

5f187844dda1

调用示例

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值