微信V3扫码支付代码实现

1设置需要的微信参数

 /**
     * 商户号
     */
    private String mchId="";

    /**
     * 公众号id 需要和商户号绑定
     */
    private String wxPayAppid="wxddddd";
    /**
     * 商户证书序列号,需要和证书对应
     */
    private String mchSerialNo="123";
    /**
     * API V3密钥
     */
    private String apiV3Key="eewweewe";
    /**
     * 商户私钥路径(微信服务端会根据证书序列号,找到证书获取公钥进行解密数据)
     */
    private String privateKeyPath="classpath:/cert/apiclient_key.pem";

2pom设置微信jar

<dependency>
            <groupId>com.github.wechatpay-apiv3</groupId>
            <artifactId>wechatpay-apache-httpclient</artifactId>
            <version>0.3.0</version>
        </dependency>

3设置微信clientBean

    /**
     * 加载秘钥
     *
     * @return
     * @throws IOException
     */
    public PrivateKey getPrivateKey() throws IOException {
        InputStream inputStream = new ClassPathResource(payConfig.getPrivateKeyPath()
                .replace("classpath:", "")).getInputStream();

        String content = new BufferedReader(new InputStreamReader(inputStream))
                .lines().collect(Collectors.joining(System.lineSeparator()));

        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");

            PrivateKey finalPrivateKey = kf.generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey.replace("\r\n", ""))));

            return finalPrivateKey;

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }


    /**
     * 定时获取微信签名验证器,自动获取微信平台证书(证书里面包括微信平台公钥)
     *
     * @return
     */
    @Bean
    public ScheduledUpdateCertificatesVerifier getCertificatesVerifier() throws IOException {

        // 使用定时更新的签名验证器,不需要传入证书
        ScheduledUpdateCertificatesVerifier verifier = null;
        verifier = new ScheduledUpdateCertificatesVerifier(
                new WechatPay2Credentials(payConfig.getMchId(),
                        new PrivateKeySigner(payConfig.getMchSerialNo(),
                                getPrivateKey())),
                payConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8));

        return verifier;
    }


    /**
     * 获取http请求对象,会自动的处理签名和验签,
     * 并进行证书自动更新
     *
     * @return
     */
    @Bean("wechatPayClient")
    public CloseableHttpClient getWechatPayClient(ScheduledUpdateCertificatesVerifier verifier) throws IOException {
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(payConfig.getMchId(),payConfig.getMchSerialNo() , getPrivateKey())
                .withValidator(new WechatPay2Validator(verifier));

        // 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签,并进行证书自动更新
        CloseableHttpClient httpClient = builder.build();

        return httpClient;
    }

4调用微信支付接口


        String outTradeNo = System.currentTimeMillis()+"";

        /**
         * {
         * 	"mchid": "1566XXX",
         * 	"out_trade_no": "native556012014070332333",
         * 	"appid": "wxdace645e0bc2cXXX",
         * 	"description": "ssss店",
         * 	"notify_url": "https://weixin.qq.com/",
         * 	"amount": {
         * 		"total": 1,
         * 		"currency": "CNY"
         *        }
         * }
         */
        JSONObject payObj = new JSONObject();
        payObj.put("mchid",payConfig.getMchId());
        payObj.put("out_trade_no",outTradeNo);
        payObj.put("appid",payConfig.getWxPayAppid());
        payObj.put("description","liddad");
        payObj.put("notify_url",payConfig.getCallbackUrl());

        //订单总金额,单位为分。
        JSONObject amountObj = new JSONObject();
        amountObj.put("total",100);
        amountObj.put("currency","CNY");

        payObj.put("amount",amountObj);
        //附属参数,可以用在回调
        payObj.put("attach","{\"accountNo\":"+888+"}");


        String body = payObj.toJSONString();

        log.info("请求参数:{}",body);

        StringEntity entity = new StringEntity(body,"utf-8");
        entity.setContentType("application/json");

        HttpPost httpPost = new HttpPost(WechatPayApi.NATIVE_ORDER);
        httpPost.setHeader("Accept","application/json");
        httpPost.setEntity(entity);

        try(CloseableHttpResponse response = wechatPayClient.execute(httpPost)){

            //响应码
            int statusCode = response.getStatusLine().getStatusCode();
            //响应体
            String responseStr = EntityUtils.toString(response.getEntity());

            log.info("下单响应码:{},响应体:{}",statusCode,responseStr);

        }catch (Exception e){
            e.printStackTrace();
        }

5结果展示

com.test.demo.WechatPayTest              : 下单响应码:200,响应体:{"code_url":"weixin://wxpay/fdffd?pr=oK8bxIlzz"}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值