支付寶(移動支付)服務端java版

所需支付寶jar包: sdk2-2.0.jar(點擊下載)html

工具類目錄結構:   點擊下載java

 

商戶信息已經公鑰私鑰的配置(公鑰私鑰的生成與支付寶商戶平臺配置請看官方文檔:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.nBDxfy&treeId=58&articleId=103242&docType=1 https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.BfaKdz&treeId=58&articleId=103578&docType=1),web

AlipayConfigspring

package com.rpframework.module.common.pay.alipay.config;

public class AlipayConfig {
    
    //↓↓↓↓↓↓↓↓↓↓請在這裏配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    // 合做身份者ID,以2088開頭由16位純數字組成的字符串
    public static String partner = "2088...";
    // 商戶的私鑰
    public static String private_key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKXcJq3Aj7uwht...";
public static String seller_email = "2088...";
    
    // 支付寶的公鑰
    public static String ali_public_key  = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89...";
//↑↑↑↑↑↑↑↑↑↑請在這裏配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
    

    // 調試用,建立TXT日誌文件夾路徑
    public static String log_path = "D:\\";

    // 字符編碼格式 目前支持 gbk 或 utf-8
    public static String input_charset = "utf-8";
    
    // 簽名方式
    public static String sign_type = "RSA";

}

PayUtils
package com.rk.shows.util;

import com.rk.shows.util.alipay.config.AlipayConfig;
import com.rk.shows.util.alipay.util.SignUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 *
 * 支付基本信息
 * @author zhangli
 * @date 2016年3月28日 下午2:35:24
 *
 *
 * 1.須要支付的信息  :
 *         用戶支付  支付相關業務 支付金額  回調業務
 * 2.第三方支付須要的信息:
 *         trade_no,subject,body,total_fee,notify_url
 *
 */
public class PayUtils {

    public static String sign(String content, String RSA_PRIVATE) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * 支付寶支付
     * @param trade_no      訂單號
     * @param total_fee     金額
     * @param subject       標題
     * @param body          內容
     * @param notify_url    回調地址
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String AliPay(String trade_no, Double total_fee, String subject, String body, String notify_url) throws UnsupportedEncodingException{
        String orderInfo = "_input_charset=\"utf-8\"";
        orderInfo += "&body=" + "\"" + body + "\"";
        orderInfo += "&it_b_pay=\"30m\"";
        orderInfo += "&notify_url=" + "\"" + notify_url + "\"";
        orderInfo += "&out_trade_no=" + "\"" + trade_no + "\"";
        orderInfo += "&partner=" + "\"" + AlipayConfig.partner + "\"";
        orderInfo += "&payment_type=\"1\"";
        orderInfo += "&return_url=\"" + notify_url + "\"";
        orderInfo += "&seller_id=" + "\"" + AlipayConfig.seller_email + "\"";
        orderInfo += "&service=\"mobile.securitypay.pay\"";
        orderInfo += "&subject=" + "\"" + subject + "\"";
        String format = String.format("%.2f", total_fee);
        if(format.indexOf(",")>0)format = format.replace(",", ".");
        orderInfo += "&total_fee=" + "\"" + format+"\"";
        System.out.println(orderInfo);
        String sign = sign(orderInfo, AlipayConfig.private_key);
        sign = URLEncoder.encode(sign, "utf-8");
        return orderInfo + "&sign=\"" + sign + "\"&" + "sign_type=\"RSA\"";
    }
}

 

接口controller:json

package com.textile.controller;

import com.rpframework.core.json.FailException;
import com.rpframework.core.json.JsonResp;
import com.rpframework.core.json.ParameterException;
import com.rpframework.module.common.bottom.controller.BaseController;
import com.rpframework.module.common.pay.alipay.util.AlipayNotify;
import com.rpframework.module.common.url.RequestDescription;
import com.textile.dto.MoneyDto;
import com.textile.entity.MemberIntroduction;
import com.textile.entity.MoneyRecord;
import com.textile.entity.User;
import com.textile.service.MemberIntroductionService;
import com.textile.service.MoneyRecordService;
import com.textile.service.UserService;
import com.textile.util.PayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by bin on 2016/11/16.
 */
@ResponseBody
@Controller
@RequestMapping
public class MoneyController {

    //http://139.224.42.24:8899
    //http://tt.tunnel.2bdata.com
    public static String alinotify = "/api/json/money/alipay/succ";

    @RequestMapping
    @RequestDescription("支付寶支付回調地址")
    @Transactional(rollbackFor = Throwable.class)
    public String alipaySucc(HttpServletRequest request) throws IOException {
        System.out.println("支付寶回調");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 亂碼解決,這段代碼在出現亂碼時使用。若是mysign和sign不相等也能夠使用這段代碼轉化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //String out_trade_no = request.getParameter("out_trade_no");// 商戶訂單號

        //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表(如下僅供參考)//
        //商戶訂單號

        //String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付寶交易號

        //String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易狀態
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表(以上僅供參考)//

        if(AlipayNotify.verify(params)){//驗證成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //請在這裏加上商戶的業務邏輯程序代碼

            //——請根據您的業務邏輯來編寫程序(如下代碼僅做參考)——

            if(trade_status.equals("TRADE_FINISHED")){
                //判斷該筆訂單是否在商戶網站中已經作過處理
                //若是沒有作過處理,根據訂單號(out_trade_no)在商戶網站的訂單系統中查到該筆訂單的詳細,並執行商戶的業務程序
                //請務必判斷請求時的total_fee、seller_id與通知時獲取的total_fee、seller_id爲一致的
                //若是有作過處理,不執行商戶的業務程序

                //注意:
                //退款日期超過可退款期限後(如三個月可退款),支付寶系統發送該交易狀態通知
            } else if (trade_status.equals("TRADE_SUCCESS")){
                //判斷該筆訂單是否在商戶網站中已經作過處理
                //若是沒有作過處理,根據訂單號(out_trade_no)在商戶網站的訂單系統中查到該筆訂單的詳細,並執行商戶的業務程序
                //請務必判斷請求時的total_fee、seller_id與通知時獲取的total_fee、seller_id爲一致的
                //若是有作過處理,不執行商戶的業務程序

                //注意:
                //付款完成後,支付寶系統發送該交易狀態通知

                String total_fee = params.get("total_fee");
                Long userId = Long.valueOf(params.get("out_trade_no").split("O")[0]);
                //updateUserPay(userId, total_fee);
                return "success";
            }
            //——請根據您的業務邏輯來編寫程序(以上代碼僅做參考)——
            //////////////////////////////////////////////////////////////////////////////////////////
        }else{//驗證失敗
            System.out.println("+++++++++++++++++++=驗證失敗");
            return "fail";
        }
        return "fail";
    }

  /*
    private void updateUserPay(Long userId, String total_fee) {
        User user = userService.selectByPrimaryKey(userId);

        if (user != null) {
            user.setPassword(null);
            //餘額
            BigDecimal account = user.getAccount() == null ? BigDecimal.valueOf(0.00) : user.getAccount();
            user.setAccount(account.add(BigDecimal.valueOf(Double.valueOf(total_fee))));
            //積分
            //BigDecimal integral = user.getIntegral() == null ? BigDecimal.valueOf(0.00) : user.getIntegral();
            //user.setIntegral(integral.add(BigDecimal.valueOf(Double.valueOf(total_fee))));
            int i = userService.updateByPrimaryKeySelective(user);
            if (i <= 0) {
                log.debug("更新用戶出錯");
            }

            //充值記錄
            MoneyRecord moneyRecord = new MoneyRecord();
            moneyRecord.setTitle("充值");
            moneyRecord.setType(1);
            moneyRecord.setMoneyChange("+" + total_fee);
            moneyRecord.setUserId(userId);

            moneyRecordService.insertJson(moneyRecord);
            log.debug("記錄添加成功");
        }
    }
  */

    @RequestMapping
    @RequestDescription("支付寶充值")
    @Transactional(rollbackFor = Throwable.class)
    public JsonResp<?> getAlipayOrderSign(Double money, HttpServletRequest request) throws Exception {
        String sym = request.getRequestURL().toString().split("/api/")[0];
        Long userId = baseController.getUserId();
        String trade_no0 = userId + "O" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        String trade_no = trade_no0.substring(0,32);
        String stringStringMap = null;
        stringStringMap =  PayUtils.AliPay(
                trade_no,
                money,       //金額
                "紡織達人充值",   //訂單名稱
                "紡織達人充值",   //訂單說明
                sym + alinotify //回調哪一個方法
        );
        if (stringStringMap != null) {
            str = stringStringMap.substring(17,stringStringMap.length()-3);
        }

        JsonResp<String> jsonResp = new JsonResp<>();
        if (stringStringMap != null) {
            return jsonResp.data(stringStringMap);
        }else {
            throw new FailException();
        }

    }

}

 

 

官方文檔: https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.VbKyV2&treeId=59&articleId=103563&docType=1api

 

參考資料:微信

 

技術客服:
https://cschannel.alipay.com/newPortal.htm?scene=mt_zczx&token=&pointId=&enterurl=https%3A%2F%2Fsupport.open.alipay.com%2Falipay%2Fsupport%2Findex.htm

教程
http://blog.csdn.net/xingzizhanlan/article/details/52709899
公鑰私鑰:
https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.nBDxfy&treeId=58&articleId=103242&docType=1
文檔:
https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.rnMrxU&treeId=193&articleId=105465&docType=1

http://www.cnblogs.com/xu-xiang/p/5797643.html

網頁支付:
http://www.jb51.net/article/88127.htm

支付寶和微信支付:
簡書:http://www.jianshu.com/p/a4f515387264

12.2:
支付寶支付:
http://blog.csdn.net/fengshizty/article/details/53215196app

 

 

app支付和移動支付的疑問:dom

http://www.cnblogs.com/harris-peng/p/6007020.html工具

相關文章
相關標籤/搜索