APP微信支付的后台实现


参阅微信支付文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_5

APP微信支付的后台实现_第1张图片
这一部分说的已经很详细了;

1.app将订单信息传给自己的后台服务;

2.后台服务接受到订单信息后,构建预支付信息,回传给APP;

接下来的过程是:

3.app获取预支付信息。调起微信支付,完成支付;

4.微信同步返回,接收通知给APP;异步调用我方后台服务提供的接口。返回成功或失败的处理结果;


贴一段别人实现的代码:

package com.epeit.api.service.wechatPay.wxpay;

import com.epeit.api.annotations.FunctionCode;
import com.epeit.api.dao.ShoppingOrderMapper;
import com.epeit.api.dao.TenpayParamsMapper;
import com.epeit.api.dao.UserAddressMapper;
import com.epeit.api.dao.WxpayInfoMapper;
import com.epeit.api.dto.ApiRequest;
import com.epeit.api.dto.ApiResponse;
import com.epeit.api.enums.RestResultEnum;
import com.epeit.api.model.ShoppingOrderPo;
import com.epeit.api.model.TenpayParams;
import com.epeit.api.model.UserAddressPo;
import com.epeit.api.model.WxpayInfo;
import com.epeit.api.service.inner.CommonService;
import com.epeit.api.service.wechatPay.RequestHandler;
import com.epeit.api.service.wechatPay.client.TenpayHttpClient;
import com.epeit.api.service.wechatPay.util.Sha1Util;
import com.epeit.api.service.wechatPay.util.TenpayUtils;
import com.epeit.api.service.wechatPay.util.WxPayConfig;
import com.epeit.api.util.SerialNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by user on 2015/3/11.
 */
@FunctionCode(value = "wxPay", descript = "微信支付相关接口")
@Service
public class WxPayServiceImpl implements WxPayService {
    @Autowired
    private WxpayInfoMapper wxpayInfoMapper;

    @Autowired
    private TenpayParamsMapper tenpayParamsMapper;

    @Autowired
    private ShoppingOrderMapper shoppingOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Value("${epeit.api.server}")
    private String defaultApiServer;
    private TenpayParams tenpayParams;

    @FunctionCode(value = "wxPay.wxPayGoods", descript = "支付订单处理接口")
    @Override
    public ApiResponse> wxPayGoods(ApiRequest apiRequest) {
       Object  userIdObj = apiRequest.get("userId");
       Object  orderCodeObj = apiRequest.get("orderCode");
       Object  deviceInfoObj = apiRequest.get("deviceInfo");
       Object  userIpObj = apiRequest.get("userIp");
        if (StringUtils.isEmpty(userIdObj)||StringUtils.isEmpty(orderCodeObj)) {
            return new ApiResponse>(RestResultEnum.MissParameterException);
        }
       ApiResponse> apiResponse =null;
       //支付单生成
       try {
               TenpayParams tenpayParams = this.tenpayParamsMapper.selectTenPayParamsByorderCode(orderCodeObj.toString());
               if(tenpayParams!=null){
                   Map outParams = new HashMap();
                   //输出参数
                   outParams.put("retcode", "0");
                   outParams.put("retmsg", "OK");
                   outParams.put("appid", tenpayParams.getAppid());
                   outParams.put("partnerid", tenpayParams.getPartnerid());
                   outParams.put("noncestr", tenpayParams.getNoncestr());
                   outParams.put("package", "Sign=WXPay");
                   outParams.put("prepayid", tenpayParams.getPrepayid());
                   outParams.put("timestamp", tenpayParams.getTimestamp());
                   outParams.put("sign", tenpayParams.getSign());
                   outParams.put("orderCode",orderCodeObj.toString());
                   apiResponse = new ApiResponse>(RestResultEnum.SUCCESS, 1, outParams);
               }else{
                   String userId = userIdObj.toString();
                   //根据用户ID获取到该用户的地址
                   UserAddressPo userAddressPo = this.userAddressMapper.queryUserAddressByUserId(Long.valueOf(userId.toString()));
                   HashMap hashMap2 = new HashMap();
                   hashMap2.put("orderCode",orderCodeObj.toString());
                   ShoppingOrderPo shoppingOrderPo =  this.shoppingOrderMapper.selectShoppingOrderByOrderCode(hashMap2);
                   String totalPrice =shoppingOrderPo.getFinalPrice().toString();//最总价格作为实际支付的价格
                   Double fiprice = Double.valueOf(totalPrice)*100;
                   Integer price = (int)Math.round(fiprice);
                   //判断价格不能低于1分钱
                   if(price>=1){
                       totalPrice = price.toString();
                       String body = "";
                       WxpayInfo wxpayInfo = new WxpayInfo();
                       wxpayInfo.setWxpayCode(orderCodeObj.toString());
                       wxpayInfo.setTotalfee(Double.valueOf(totalPrice));
                       wxpayInfo.setPayState(0);//支付未成功--等待微信支付完成的异步通知
                       wxpayInfo.setAttach("");
                       if(!StringUtils.isEmpty(deviceInfoObj)){
                           wxpayInfo.setDeviceinfo(deviceInfoObj.toString());
                       }
                       wxpayInfo.setUserid(Integer.valueOf(userIdObj.toString()));
                       if(!StringUtils.isEmpty(userIpObj)){
                           wxpayInfo.setUserip(userIpObj.toString());
                       }
                       wxpayInfo.setTimestart(new Date());
                       wxpayInfo.setOrderAddress(userAddressPo.getAddress());
                       wxpayInfo.setGoodstag("");
                       wxpayInfo.setBody(body);
                       this.wxpayInfoMapper.insertSelective(wxpayInfo);
                       HttpServletRequest request = apiRequest.getRequest();
                       HttpServletResponse response = apiRequest.getResponse();
                       //获取提交的商品价格
                       String order_price = totalPrice;
                       //获取提交的商品名称
                       String product_name = body;
                       Map outParams = new HashMap();
                       RequestHandler reqHandler = new RequestHandler(request, response);
                       TenpayHttpClient httpClient = new TenpayHttpClient();
                       //初始化
                       reqHandler.init();
                       reqHandler.init(WxPayConfig.app_id,WxPayConfig.partner, WxPayConfig.partner_key);
                       //=========================
                       //生成预支付单
                       //=========================
                       String noncestr = Sha1Util.getNonceStr();
                       //设置package订单参数
                       SortedMap packageParams = new TreeMap();
                       packageParams.put("appid", WxPayConfig.app_id);
                       packageParams.put("body",WxPayConfig.body ); //商品描述
                       packageParams.put("mch_id", WxPayConfig.partner); //商户号
                       packageParams.put("nonce_str", noncestr);
                       packageParams.put("notify_url", defaultApiServer+"/wxPay/wxPayNotify"); //接收财付通通知的URL
                       packageParams.put("out_trade_no", orderCodeObj.toString()); //商家订单号
                       packageParams.put("spbill_create_ip", request.getRemoteAddr()); //订单生成的机器IP,指用户浏览器端IP
                       packageParams.put("total_fee", order_price); //商品金额,以分为单位
                       packageParams.put("trade_type", "APP"); //商品描述
                       String timestamp = Sha1Util.getTimeStamp();
                       packageParams.put("time_start", timestamp); //字符编码

                       //获取prepayId
                       String prepayid = reqHandler.sendPrepay(packageParams);
                       if (null != prepayid && !"".equals(prepayid)) {
                           //签名参数列表
                           Map map =new HashMap();
                           map.put("appid",WxPayConfig.app_id);
                           map.put("noncestr",noncestr);
                           map.put("package","Sign=WXPay");
                           map.put("partnerid",WxPayConfig.partner);
                           map.put("prepayid",prepayid);
                           map.put("timestamp",timestamp);
                   /* 统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,将数据传输给APP。
                    参与签名的字段名为appId,partnerId,prepayId,nonceStr,timeStamp,package。
                    注意:package的值格式为prepay_id=wx20141009175351724b348a500087751557*/
                           //生成签名
                           System.out.println("**********:"+map.toString());
                           String sign = TenpayUtils.createSign(map);
                           //输出参数
                           outParams.put("retcode", "0");
                           outParams.put("retmsg", "OK");
                           outParams.put("appid", WxPayConfig.app_id);
                           outParams.put("partnerid", WxPayConfig.partner);
                           outParams.put("noncestr", noncestr);
                           outParams.put("package", "Sign=WXPay");
                           outParams.put("prepayid", prepayid);
                           outParams.put("timestamp", timestamp);
                           outParams.put("sign", sign);
                           outParams.put("orderCode",orderCodeObj.toString());
                       } else {
                           outParams.put("retcode", "-2");
                           outParams.put("retmsg", "错误:获取prepayId失败");
                       }
                       this.insertTenpayParams(outParams);
                       response.resetBuffer();
                       response.setHeader("ContentType", "text/json");
                       apiResponse=new ApiResponse>(RestResultEnum.SUCCESS,1,outParams);
                   }else{
                       apiResponse=new ApiResponse>(RestResultEnum.CheckMoney);
                   }
               }
        }catch (Exception ex){
           ex.printStackTrace();
            apiResponse=new ApiResponse>(RestResultEnum.UNKNOW_ERROR);
        }
        return apiResponse;
    }


    /**
     * 再次支付未付款订单的调用方法
     *
     * @param apiRequest
     * @return
     */
    @FunctionCode(value = "wxPay.payAgain", descript = "再次支付未付款订单的调用方法")
    @Override
    public ApiResponse payAgain(ApiRequest apiRequest) {
        Object orderCodeObj = apiRequest.get("orderCode");
        if (StringUtils.isEmpty(orderCodeObj)) {
            return new ApiResponse(RestResultEnum.MissParameterException);
        }
        ApiResponse apiResponse = null;
        try {
           TenpayParams tenpayParams = this.tenpayParamsMapper.selectTenPayParamsByorderCode(orderCodeObj.toString());
              //如果支付成功则调用此接口,并将订单的数据拆解存储对应的数据表
            apiResponse = new ApiResponse(RestResultEnum.SUCCESS, 1, tenpayParams);
        } catch (Exception ex) {
            apiResponse = new ApiResponse(RestResultEnum.UNKNOW_ERROR);
        }
        return apiResponse;
    }

    private void insertTenpayParams(Map tenpayParams) {
        TenpayParams tenpayParams1 = new TenpayParams();
        tenpayParams1.setAppid(tenpayParams.get("appid"));
        tenpayParams1.setNoncestr(tenpayParams.get("noncestr"));
        tenpayParams1.setPartnerid(tenpayParams.get("partnerid"));
        tenpayParams1.setPrepayid(tenpayParams.get("prepayid"));
        tenpayParams1.setRetcode(tenpayParams.get("retcode"));
        tenpayParams1.setRetmsg(tenpayParams.get("retmsg"));
        tenpayParams1.setSign(tenpayParams.get("sign"));
        tenpayParams1.setTimestamp(tenpayParams.get("timestamp"));
        tenpayParams1.setWxpayPackage(tenpayParams.get("package"));
        tenpayParams1.setOrderCode(tenpayParams.get("orderCode"));
        this.tenpayParamsMapper.insertSelective(tenpayParams1);//新增微信支付认证信息
    }
}









你可能感兴趣的:(微信)