app對接微信支付(app支付)


(先補充一下,app喚醒微信支付失敗的話,在確保沒錯的情況下,建議換一個手機或者重新下載微信,不知道是微信緩存還是什么原因)

1、先申請好開發環境

app支付不需要公眾號,所以申請好開發商號和開發平台的app應用即可,獲取到如下圖的幾個

 

還有就是在申請應用的時候記得設置正確的應用包名和應用簽名。

2、可以查看微信開發文檔(https://pay.weixin.qq.com/)。

controller層

/**
     *  @description: 微信支付開始下單
     *  @date:  2021/6/7
     */
    @GetMapping("/createOrder")
    public JsonData createOrder(@RequestParam(value = "videoId", required = true) int videoId,
                                @RequestParam(value = "userId", required = true) int userId,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {


        Map<String, String> map = videoOrderService.wxSave(videoId, userId,request);
//        if (codeUrl == null) {
//            throw new NullPointerException();
//        }
        return JsonData.buildSuccess(map,"微信支付獲取codeUrl")}

serviceImpl層

需要先引入pom文件

<dependency>
            <groupId>com.github.wxpay</groupId>
            <artifactId>wxpay-sdk</artifactId>
            <version>0.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

 

/**
     * 微信生成訂單
     *
     * @param videoId
     * @param userId
     */
    @Override
    public Map<String, String> wxSave(int videoId, int userId,HttpServletRequest request) throws Exception {

       
        Video video = videoMapper.selectById(videoId);
        //AppUser appUser = appUserMapper.selectById(userId);
        //生成訂單
        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setVideoId(video.getId());
        videoOrder.setOutTradeNo(CommonUtils.generateUUID());
     //未支付的狀態 videoOrder.setState(
0); videoOrder.setCreateTime(new Date()); videoOrder.setTotalFee(video.getPrice()); videoOrder.setVideoId(video.getId()); videoOrder.setVideoTitle(video.getTitle()); videoOrder.setVideoImg(video.getCoverImg()); videoOrder.setUserId(userId);
     //先生成訂單信息,支付狀態設置為未支付 Map
<String, String> codeUrl = unifiedOrder(videoOrder,request); return codeUrl; }

private Map<String, String> unifiedOrder(VideoOrder videoOrder,HttpServletRequest request) throws Exception {

        //生成未支付訂單
        int insert = videoOrderMapper.insert(videoOrder);
     //這些字段都可以在開發文檔上找到,盡量直接復制,以免打錯
        SortedMap<String,String> params = new TreeMap<>();
        params.put("appid",weChatConfig.getAppid());
        params.put("mch_id",weChatConfig.getMchId());
        params.put("nonce_str",CommonUtils.generateUUID());
        params.put("body",videoOrder.getVideoTitle());
        params.put("out_trade_no",videoOrder.getOutTradeNo());
        params.put("total_fee",String.valueOf(1));
        params.put("spbill_create_ip",getRealIp(request));
        params.put("notify_url",weChatConfig.getNotifyUrl());
        params.put("trade_type","APP");

        //生成簽名/這里也可以用微信支付的自帶的工具類,WXPayUtil.generateSignedXml(params,weChatConfig.getKey());
        String sign = WxPayUtil.createSign(params,weChatConfig.getKey());

        params.put("sign",sign);

        String payXml = WxPayUtil.mapToXml(params);

        System.out.println(payXml);
        //統一下單
        String orderStr = HttpUtils.doPost(weChatConfig.getUnifiedOrderUrl(),payXml,4000);
        if(null == orderStr) {
            return null;
        }

        Map<String, String> unifiedOrderMap =  WXPayUtil.xmlToMap(orderStr);
        System.out.println(unifiedOrderMap.toString());

        //unifiedOrderMap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        Long timeStamp = System.currentTimeMillis() / 1000;

        SortedMap<String, String> ps = new TreeMap();
        ps.put("appid", unifiedOrderMap.get("appid"));
        ps.put("partnerid", weChatConfig.getMchId());
        ps.put("noncestr", unifiedOrderMap.get("nonce_str"));
        ps.put("package","Sign=WXPay");
        ps.put("prepayid",unifiedOrderMap.get("prepay_id"));
        ps.put("timestamp", String.valueOf(timeStamp));
        //二次簽名
        String sign2 = WxPayUtil.createSign(ps,weChatConfig.getKey());
        ps.put("sign",sign2);

        String s = WxPayUtil.mapToXml(ps);
        System.out.println(s);
        System.out.println(ps.toString());
        return ps;

    }

統一下單封裝方法

/**
     * 封裝post
     * @return
     */
    public static String doPost(String url, String data,int timeout){
        CloseableHttpClient httpClient =  HttpClients.createDefault();
        //超時設置

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(timeout) //連接超時
                .setConnectionRequestTimeout(timeout)//請求超時
                .setSocketTimeout(timeout)
                .setRedirectsEnabled(true)  //允許自動重定向
                .build();


        HttpPost httpPost  = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type","text/html; chartset=UTF-8");

        if(data != null && data instanceof  String){ //使用字符串傳參
            StringEntity stringEntity = new StringEntity(data,"UTF-8");
            httpPost.setEntity(stringEntity);
        }

        try{

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(httpEntity);
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return null;

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM