支付宝(移动支付)服务端java版

所需支付宝jar包: sdk2-2.0.jar(点击下载)

工具类目录结构:   点击下载

 

商户信息已经公钥私钥的配置(公钥私钥的生成与支付宝商户平台配置请看官方文档: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),

AlipayConfig

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:

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=1

 

参考资料:

 

技术客服:
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/53215196

 

 

app支付和移动支付的疑问:

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

 
posted @ 2016-12-28 17:13  007少侠  阅读(6672)  评论(0编辑  收藏  举报
友情链接:便宜vps(CN2GIA线路)
站长统计: