支付寶支付接口開發———在線掃碼支付

 

1、所需jar包

服務端sdk下載地址:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.470nRM&treeId=193&articleId=103419&docType=1java

詳細文檔參考:螞蟻金服開放平臺文檔中心,具體的api及測試demo均可以查到 地址: https://doc.open.alipay.com/express

SDK包說明

  • alipay-sdk-java*.jar—————————支付寶SDK編譯文件jar
  • alipay-sdk-java*-source.jar——————支付寶SDK源碼文件jar
  • commons-logging-1.1.1.jar——————SDK依賴的日誌jar
  • commons-logging-1.1.1-sources.jar———SDK依賴的日誌源碼jar

注意

    • 集成支付寶接口須要引入的文件是:
      alipay-sdk-java*.jar
      commons-logging-1.1.1.jar
    • 若進一步瞭解代碼實現請引入文件:
      alipay-sdk-java*-source.jar
      commons-logging-1.1.1-sources.jar

2、調用支付

 

    //調用支付
public void toPay() { String orderid = getRequest().getParameter("id"); if (StringUtils.isBlank(orderid)) { throw new NullPointerException(); } Order order = orderService.selectById(orderid); if (order == null) { throw new NullPointerException("根據訂單號查詢不到訂單信息!"); } Ordership ordership = ordershipService.selectOne(new Ordership(orderid)); if (ordership == null) { throw new NullPointerException("根據訂單號查詢不到配送信息!"); } ArrayNode goods_detail = JsonUtils.createArrayNode();// 商品詳情設置(json格式-非必須參數,根據業務邏輯處理) String out_trade_no = order.getPayNo();//支付編號(訂單編號-必須惟一) double total_amount = 0.01;//訂單金額 String subject = "訂單標題";//訂單描述 AlipayTradePrecreateResponse resp = aliPayService.aliPay(out_trade_no, total_amount, subject, goods_detail);// 訂單編號--訂單金額--訂單描述--商品明細(無 ) if ("10000".equals(resp.getCode())) {//若請求成功,則進行邏輯處理 String qr_code = resp.getQrCode(); /** * 生成二維碼 */ // 支付寶返回Code(url)--用戶account--訂單--id(拼二維碼地址而已) AttachmentEntity attachmentEntity = this.creatPayCode(qr_code, account, out_trade_no); if (attachmentEntity == null) { throw new NullPointerException("訂單生成失敗!OrdersAction--toPay"); } else { // 返回二維碼地址 getOut().println(attachmentEntity.getAtt_path()); } } else { throw new NullPointerException("二維碼生成失敗!OrdersAction--toPay"); } }


   public AlipayTradePrecreateResponse aliPay(String out_trade_no, double total_amount,
                                               String subject, ArrayNode goods_detail) {
        /**
         * 建立Json對象 封裝信息
         */
        ObjectNode biz_content = JsonUtils.createObjectNode();
        biz_content.put("out_trade_no", out_trade_no); //訂單號
        biz_content.put("total_amount", total_amount); //訂單總金額
        biz_content.put("subject", subject); //訂單標題
        biz_content.put("timeout_express", "5m"); //該筆訂單容許的最晚付款時間,逾期將關閉交易
     
        AlipayTradePrecreateResponse response = null;
    //請求支付接口對象  
    //參數
    //1.請求網址 2.本身所註冊的應用id(支付寶分配給開發者的應用ID) 3.私鑰 4.json 5.字符編碼集 6.公鑰
    //實例化客戶端
     AlipayClient alipayClient = new DefaultAlipayClient(request_url, app_id, private_key, "json", charset,
                                                            public_key);
     //實例化具體API對應的request類,類名稱和接口名稱對應
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizContent(biz_content.toString());
      
       try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException ex) {
            log.error(ex.getMessage());
        } 
        return response;
    }
//生成二維碼
private AttachmentEntity creatPayCode(String url, String user_id, String order_id) {

        String serverClassPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String logo_path = serverClassPath + "config/logo.png";
        String uploadPath = "payForUser/" + user_id + "/order/" + order_id + "/" + "payCode";
        String attName = "payCode.jpg";// 定義原圖的名稱
        BufferedImage barCode = BarCodeService.createImage(url, logo_path);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(barCode, "jpg", imageOutputStream);
        } catch (IOException iOException) {
            iOException.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        String barCode_url = ossService.uploadFile(uploadPath, inputStream, attName);//將二維碼文件上傳阿里雲(可自主處理)
        AttachmentEntity attachmentEntity = new AttachmentEntity();
        attachmentEntity.setAtt_name(attName);
        attachmentEntity.setAtt_path(barCode_url);
        attachmentEntity.setMoudel_name("payCode");
        attachmentEntity.setAtt_type("jpg");
        attachmentEntity.setUpload_time(DateUtils.getSystemDate());
        attachmentEntity.setDownload_count(0);
        attachmentEntity.setGid(DataUtils.getUUID());
        attachmentEntity.setIs_compress(0);
        attachmentEntity.setEntity_id(order_id);

        return attachmentEntity;

    }

3、查詢支付狀態

    public String isPay() {
    
            AlipayTradeQueryResponse alipayTradeQueryResponse = aliPayService.aliQuery(order.getPayNo());//訂單編號
            if (alipayTradeQueryResponse.isSuccess()) {//若查詢狀態爲success
        
                if ("10000".equals(alipayTradeQueryResponse.getCode())) {
                    String Body = alipayTradeQueryResponse.getBody();
                    String out_trade_no = alipayTradeQueryResponse.getOutTradeNo();// 支付編號

                    ObjectNode objectNode = (ObjectNode) JsonUtils.stringToJsonObject(Body)
                            .get("alipay_trade_query_response");
                    String trade_status = objectNode.get("trade_status").textValue();// 支付狀態
                    if (trade_status != null && "TRADE_SUCCESS".equals(trade_status)) {
                        String trade_no = objectNode.get("trade_no").textValue();//支付寶交易號
                        
                        //支付記錄建立
                        orderService.createPayInfo(order,trade_no,orderpay.orderpay_paystatus_y,orderpay.orderpay_paymethod_alipayescow,"");//訂單--支付寶交易號-支付狀態-支付類型
                        orderService.orderStutasChange(orderId);// 修改訂單狀態
                        getOut().print("000000");
                        return null;
                    }else if (trade_status != null && "TRADE_CLOSED".equals(trade_status)) {//二維碼失效
                        String trade_no = objectNode.get("trade_no").textValue();//支付寶交易號
                        //修改訂單支付編號。從新生成二維碼
                        String orderId=out_trade_no.substring(0, out_trade_no.length()-13);
                        e.setId(orderId);
                        String payNo=orderId+new Date().getTime();
                        e.setPayNo(payNo);
                        orderService.update(e);                
                    getOut().print("000001");
                            return null;
                    }

                }
            }
            return null;
    }
相關文章
相關標籤/搜索