package com.slodon.b2b2c.controller.member.front;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.core.config.DomainUrlUtil;
import com.slodon.b2b2c.core.constant.MemberConst;
import com.slodon.b2b2c.core.constant.OrderPaymentConst;
import com.slodon.b2b2c.core.constant.PayConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.uid.GoodsIdGenerator;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.member.example.MemberBalanceRechargeExample;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.member.pojo.MemberBalanceRecharge;
import com.slodon.b2b2c.model.member.MemberBalanceRechargeModel;
import com.slodon.b2b2c.model.member.MemberModel;
import com.slodon.b2b2c.starter.entity.SlodonPayRequest;
import com.slodon.b2b2c.starter.entity.SlodonPayResponse;
import com.slodon.b2b2c.starter.entity.cpcn.TxPayRequest;
import com.slodon.b2b2c.starter.pay.SlodonPay;
import com.slodon.b2b2c.starter.util.ZjPayUtil;
import com.slodon.b2b2c.util.PayPropertiesUtil;
import com.slodon.b2b2c.vo.member.BalanceRechargeDetailVO;
import com.slodon.b2b2c.vo.member.BalanceRechargeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import payment.api.util.GUIDGenerator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.slodon.b2b2c.core.constant.PayConst.*;

@Api(tags = "front-充值")
@Slf4j
@RestController
@RequestMapping("front/balanceRecharge")
public class FrontMemberBalanceRechargeController extends BaseController {

    private final static String PAY_SUCCESS_URL = "/pages/recharge/list";
    private final static String PAY_SUCCESS_URL_PC = "/member/balance";

    @Resource
    private MemberBalanceRechargeModel memberBalanceRechargeModel;
    @Resource
    private MemberModel memberModel;
    @Resource
    private SlodonPay slodonPay;
    @Resource
    private PayPropertiesUtil payPropertiesUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("余额")
    @GetMapping("getMemberBalance")
    public JsonResult<Object> getMemberBalance(HttpServletRequest request) {

        Member member = UserUtil.getUser(request, Member.class);
        Member memberDb = memberModel.getMemberByMemberId(member.getMemberId());
        //响应
        HashMap<String, Object> map = new HashMap<>();
        map.put("balanceAvailable", memberDb.getBalanceAvailable());
        map.put("rechargeSum", memberDb.getBalanceAvailable().add(memberDb.getBalanceFrozen()));
        return SldResponse.success(map);
    }

    @ApiOperation("充值明细列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payState", value = "支付状态 1-未支付 2-已支付", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<BalanceRechargeVO>> getList(HttpServletRequest request, @RequestParam(name = "payState", required = false) Integer payState) {

        Member member = UserUtil.getUser(request, Member.class);

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        MemberBalanceRechargeExample example = new MemberBalanceRechargeExample();
        example.setMemberId(member.getMemberId());
        example.setPayState(payState);
        List<MemberBalanceRecharge> list = memberBalanceRechargeModel.getMemberBalanceRechargeList(example, pager);
        ArrayList<BalanceRechargeVO> vos = new ArrayList<>();
        list.forEach(memberBalanceRecharge -> {
            BalanceRechargeVO vo = new BalanceRechargeVO(memberBalanceRecharge);
            vos.add(vo);
        });
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("充值详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rechargeId", value = "充值id", paramType = "query", required = true)
    })
    @GetMapping("detail")
    public JsonResult<BalanceRechargeDetailVO> getBalanceRecharge(HttpServletRequest request, @RequestParam("rechargeId") Integer rechargeId) {
        //校验
        MemberBalanceRecharge detail = memberBalanceRechargeModel.getMemberBalanceRechargeByRechargeId(rechargeId);
        Member member = UserUtil.getUser(request, Member.class);
        AssertUtil.isTrue(!member.getMemberId().equals(detail.getMemberId()), "无权限");

        MemberBalanceRecharge memberBalanceRecharge = memberBalanceRechargeModel.getMemberBalanceRechargeByRechargeId(rechargeId);
        BalanceRechargeDetailVO vo = new BalanceRechargeDetailVO(memberBalanceRecharge);
        return SldResponse.success(vo);
    }

    @ApiOperation("会员充值接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payMethod", value = "支付方式，balance==余额支付；wx==微信支付；alipay==支付宝；paypal==payPal", required = true, paramType = "query"),
            @ApiImplicitParam(name = "payType", required = true, paramType = "query", value = "支付类型：[BALANCE,NATIVE,APP,JSAPI,MWEB,PAYPAL]"),
            @ApiImplicitParam(name = "amount", value = "充值金额", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "用户code（JSAPI支付时必填）", paramType = "query"),
            @ApiImplicitParam(name = "codeSource", value = "用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器", paramType = "query"),
            @ApiImplicitParam(name = "bankCode", value = "银行编码，中金网银支付，编码账号二选一", paramType = "query"),
            @ApiImplicitParam(name = "bankAccount", value = "银行账号，中金网银支付，编码账号二选一", paramType = "query")
    })
    @PostMapping("recharge")
    public JsonResult<Object> recharge(HttpServletRequest request,
                                       @RequestParam(value = "payType") String payType,
                                       @RequestParam(value = "payMethod") String payMethod,
                                       @RequestParam(value = "amount") String amount,
                                       @RequestParam(value = "code", required = false) String code,
                                       @RequestParam(value = "codeSource", required = false) Integer codeSource,
                                       @RequestParam(value = "bankCode", required = false) String bankCode,
                                       @RequestParam(value = "bankAccount", required = false) String bankAccount) throws Exception {
        Member memberToken = UserUtil.getUser(request, Member.class);

        //获取最新的用户信息
        Member memberDb = memberModel.getMemberByMemberId(memberToken.getMemberId());

        //该用户的总余额达到999999.00时，不可进行充值
        if (memberDb.getBalanceAvailable().add(memberDb.getBalanceFrozen()).compareTo(new BigDecimal(999999)) >= 0) {
            return SldResponse.fail("该用户的总余额达到999999.00，不可进行充值");
        }

        BigDecimal fee = new BigDecimal(amount);
        AssertUtil.isTrue(fee.compareTo(BigDecimal.ZERO) <= 0, "充值金额有误");
        if (fee.compareTo(new BigDecimal(999999)) > 0) {
            return SldResponse.fail("充值金额不能超过999999.00");
        }

        BigDecimal newBalance = memberDb.getBalanceAvailable().add(memberDb.getBalanceFrozen()).add(fee);
        if (newBalance.compareTo(new BigDecimal(999999)) > 0) {
            return SldResponse.fail("新的余额已超过999999.00");
        }

        String rechargeSn = GoodsIdGenerator.getOrderSn();

        //构造三方支付请求参数
        SlodonPayRequest payRequest = this.getPayRequest(memberToken.getMemberId(), payMethod, payType, rechargeSn, fee, code, codeSource, WebUtil.getRealIp(request), bankCode, bankAccount);

        //保存充值信息
        String tradeSn = "";
        if (payMethod.toLowerCase().contains(METHOD_ZJ.toLowerCase())) {
            //中金支付，预先生成交易流水号
            tradeSn = payRequest.getTxPayRequest().getTxSn();
        }
        Integer rechargeId = this.saveRecharge(rechargeSn, payType, payMethod, new BigDecimal(amount), memberDb, tradeSn);
        SlodonPayResponse slodonPayResponse = slodonPay.unitePay(payRequest);
        slodonPayResponse.setRechargeId(rechargeId);
        return SldResponse.success(slodonPayResponse);
    }

    /**
     * 新增充值信息
     *
     * @param rechargeSn 充值单号
     * @param payType    支付类型
     * @param payMethod  支付方式
     * @param amount     支付金额
     * @param member     会员
     * @param tradeSn    支付流水号
     */
    private Integer saveRecharge(String rechargeSn, String payType, String payMethod, BigDecimal amount, Member member, String tradeSn) {
        MemberBalanceRecharge memberBalanceRecharge = new MemberBalanceRecharge();
        memberBalanceRecharge.setRechargeSn(rechargeSn);
        String paymentCode = payType + payMethod.toUpperCase();
        String paymentName = OrderPaymentConst.PAYMENT_NAME_ONLINE;
        if (payMethod.contains(METHOD_WX)) {
            paymentName = NAME_WX;
        } else if (payMethod.contains("ali")) {
            paymentName = NAME_ALIPAY;
        } else if (payMethod.contains(METHOD_PAYPAL)) {
            paymentName = NAME_PAYPAL;
        } else if (payMethod.contains("bank")) {
            paymentName = NAME_BANK;
        }

        memberBalanceRecharge.setPaymentCode(paymentCode);
        memberBalanceRecharge.setPaymentName(paymentName);
        memberBalanceRecharge.setPayAmount(amount);
        memberBalanceRecharge.setPayState(MemberConst.PAY_STATE_1);
        memberBalanceRecharge.setMemberId(member.getMemberId());
        memberBalanceRecharge.setMemberName(member.getMemberName());
        memberBalanceRecharge.setMemberMobile(member.getMemberMobile());
        memberBalanceRecharge.setCreateTime(new Date());
        memberBalanceRecharge.setTradeSn(tradeSn);
        memberBalanceRechargeModel.saveMemberBalanceRecharge(memberBalanceRecharge);
        return memberBalanceRecharge.getRechargeId();
    }

    @ApiOperation("继续充值接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payMethod", value = "支付方式，balance==余额支付；wx==微信支付；alipay==支付宝", required = true, paramType = "query"),
            @ApiImplicitParam(name = "payType", required = true, paramType = "query",
                    value = "支付类型：[BALANCE,NATIVE,APP,JSAPI,MWEB]"),
            @ApiImplicitParam(name = "rechargeSn", value = "充值单号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "用户code（JSAPI支付时必填）", paramType = "query"),
            @ApiImplicitParam(name = "codeSource", value = "用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器", paramType = "query"),
            @ApiImplicitParam(name = "bankCode", value = "银行编码，中金网银支付，编码账号二选一", paramType = "query"),
            @ApiImplicitParam(name = "bankAccount", value = "银行账号，中金网银支付，编码账号二选一", paramType = "query")
    })
    @PostMapping("rechargeContinue")
    public JsonResult<Object> rechargeContinue(HttpServletRequest request,
                                               @RequestParam(value = "payType") String payType,
                                               @RequestParam(value = "payMethod") String payMethod,
                                               @RequestParam(value = "rechargeSn") String rechargeSn,
                                               @RequestParam(value = "code", required = false) String code,
                                               @RequestParam(value = "codeSource", required = false) Integer codeSource,
                                               @RequestParam(value = "bankCode", required = false) String bankCode,
                                               @RequestParam(value = "bankAccount", required = false) String bankAccount) throws Exception {
        Member memberToken = UserUtil.getUser(request, Member.class);

        //查询充值记录
        MemberBalanceRechargeExample rechargeExample = new MemberBalanceRechargeExample();
        rechargeExample.setRechargeSn(rechargeSn);
        rechargeExample.setMemberId(memberToken.getMemberId());
        List<MemberBalanceRecharge> memberBalanceRechargeList = memberBalanceRechargeModel.getMemberBalanceRechargeList(rechargeExample, null);
        AssertUtil.notEmpty(memberBalanceRechargeList, "充值单号有误");

        MemberBalanceRecharge rechargeDb = memberBalanceRechargeList.get(0);

        if (rechargeDb.getPayState() == MemberConst.PAY_STATE_2) {
            return SldResponse.fail("订单已支付");
        }

        //构造三方支付请求参数
        SlodonPayRequest payRequest = this.getPayRequest(memberToken.getMemberId(), payMethod, payType, rechargeSn, rechargeDb.getPayAmount(), code, codeSource, WebUtil.getRealIp(request), bankCode, bankAccount);

        if (payMethod.toLowerCase().contains(METHOD_ZJ.toLowerCase())) {
            if (!StringUtils.isEmpty(rechargeDb.getTradeSn())) {
                //之前的支付流水号，关闭支付单
                ZjPayUtil.closeOrder(rechargeDb.getTradeSn(), stringRedisTemplate.opsForValue().get("zj_pay_institution_id"));
            }
            //中金支付，更新支付流水号
            MemberBalanceRecharge update = new MemberBalanceRecharge();
            update.setRechargeId(rechargeDb.getRechargeId());
            update.setTradeSn(payRequest.getTxPayRequest().getTxSn());
            memberBalanceRechargeModel.updateMemberBalanceRecharge(update);
        }
        SlodonPayResponse slodonPayResponse = slodonPay.unitePay(payRequest);
        slodonPayResponse.setRechargeId(rechargeDb.getRechargeId());
        return SldResponse.success(slodonPayResponse);
    }

    /**
     * 构造支付请求对象
     *
     * @param memberId    会员id
     * @param payMethod   支付方式
     * @param payType     支付类型
     * @param paySn       支付单号
     * @param payAmount   支付金额
     * @param code        用户code（JSAPI支付时必填）
     * @param codeSource  用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器
     * @param ip          ip
     * @param bankCode    银行编码，中金网银支付
     * @param bankAccount 银行账号，中金网银支付
     * @return 支付请求对象
     */
    private SlodonPayRequest getPayRequest(Integer memberId, String payMethod, String payType, String paySn,
                                           BigDecimal payAmount, String code, Integer codeSource, String ip, String bankCode, String bankAccount) throws Exception {
        SlodonPayRequest request = new SlodonPayRequest();
        AssertUtil.isTrue(!payMethod.equals(METHOD_WX) && !payMethod.equals(METHOD_ALIPAY) && !payMethod.equals(METHOD_PAYPAL)
                && !payMethod.equals(METHOD_ZJ_WX) && !payMethod.equals(METHOD_ZJ_ALI) && !payMethod.equals(METHOD_ZJ_BANK), "支付方式有误");
        request.setPayMethod(payMethod);
        request.setPayType(payType);
        request.setCodeSource(codeSource);
        if (payType.equalsIgnoreCase(ALI_TYPE_NATIVE)) {
            //pc扫码支付
            request.setReturnUrl(DomainUrlUtil.SLD_PC_URL + PAY_SUCCESS_URL_PC);
        } else {
            //移动支付
            request.setReturnUrl(DomainUrlUtil.SLD_H5_URL + PAY_SUCCESS_URL);
        }
        //商品描述
        String body = stringRedisTemplate.opsForValue().get("basic_site_name") + "-用户充值单";
        request.setSubject(body);
        request.setBody(body);
        switch (payMethod) {
            case METHOD_WX:
                request.setWxPayProperties(payPropertiesUtil.getWxPayProperties(payType));
                request.setNotifyUrl(DomainUrlUtil.SLD_API_URL + "/v3/member/front/rechargeCallback/wx");
                if (payType.equals(WX_TYPE_JSAPI) || payType.equals(WX_TYPE_MINIAPP)) {
                    //小程序、微信内部浏览器支付，获取openid
                    request.setOpenId(this.getOpenId(payType, memberId, code));
                }
                break;
            case METHOD_PAYPAL:
                request.setPayPalProperties(payPropertiesUtil.getPayPalProperties());
                request.setNotifyUrl(DomainUrlUtil.SLD_API_URL + "/v3/member/front/rechargeCallback/payPal");
                break;
            case METHOD_ALIPAY:
                request.setAlipayProperties(payPropertiesUtil.getAliPayProperties());
                request.setNotifyUrl(DomainUrlUtil.SLD_API_URL + "/v3/member/front/rechargeCallback/ali");
                break;
            case METHOD_ZJ_BANK:
            case METHOD_ZJ_WX:
            case METHOD_ZJ_ALI:
                //中金
                request.setNotifyUrl(DomainUrlUtil.SLD_API_URL + "/v3/member/front/rechargeCallback/zj");
                request.setTxPayRequest(this.getTxPayRequest(memberId, payMethod, payType, bankCode, bankAccount, code, codeSource));
                break;
            default:
                break;
        }
        request.setPaySn(paySn);
        if ("1".equals(stringRedisTemplate.opsForValue().get("pay_test_enable"))) {
            request.setPayAmount(new BigDecimal("0.01"));
        } else {
            request.setPayAmount(payAmount);
        }
        request.setIp(ip);

        return request;
    }

    /**
     * 构造中金支付请求参数
     *
     * @param memberId    会员id
     * @param payMethod   支付方式{@link PayConst#METHOD_ZJ_WX}
     * @param payType     支付类型{@link PayConst#ZJ_TYPE_NATIVE}
     * @param bankCode    银行编码，中金网银支付
     * @param bankAccount 银行账号，中金网银支付
     * @param code        用户code（JSAPI支付时必填）
     * @param codeSource  用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器
     * @return 中金支付请求参数
     */
    public TxPayRequest getTxPayRequest(Integer memberId, String payMethod, String payType, String bankCode, String bankAccount, String code, Integer codeSource) throws Exception {
        //构造中金支付请求参数
        String institutionId = stringRedisTemplate.opsForValue().get("zj_pay_institution_id");
        AssertUtil.notEmpty(institutionId, "支付方式暂未开通");
        TxPayRequest txPayRequest = new TxPayRequest();
        txPayRequest.setInstitutionId(institutionId);
        txPayRequest.setTxSn(GUIDGenerator.genGUID());
        txPayRequest.setPayerUserId("m" + memberId);
        txPayRequest.setPayeeUserId(institutionId);
        txPayRequest.setPayeeAccountNumber("0001");
        txPayRequest.setHasSubsequentSplit("1");//无后续分账

        txPayRequest.setGoodsName(stringRedisTemplate.opsForValue().get("basic_site_name"));
        txPayRequest.setCancelPayRedirectPageURL(DomainUrlUtil.SLD_PC_URL + PAY_SUCCESS_URL_PC);
        txPayRequest.setRedirectPageURL(DomainUrlUtil.SLD_PC_URL + PAY_SUCCESS_URL_PC);

        switch (payMethod) {
            case METHOD_ZJ_BANK:
                //网银，只有pc扫码
                txPayRequest.setPaymentWay("20");
                txPayRequest.setPageUrl(DomainUrlUtil.SLD_PC_URL + PAY_SUCCESS_URL_PC);
                txPayRequest.setBankID(StringUtils.isEmpty(bankCode) ? ZjPayUtil.getBankInfo(bankAccount, institutionId) : bankCode);
                break;
            case METHOD_ZJ_WX:
                //微信
                switch (payType) {
                    case ZJ_TYPE_NATIVE:
                        //扫码
                        txPayRequest.setPaymentWay("42");
                        txPayRequest.setScanPaymentType(PayConst.ZJ_QR_TYPE_WX);
                        break;
                    case ZJ_TYPE_APP:
                        //app
                        txPayRequest.setPaymentWay("80");
                        txPayRequest.setPayType("31");
                        txPayRequest.setPayWay("46");
                        txPayRequest.setPlatformName(stringRedisTemplate.opsForValue().get("basic_site_name"));
                        txPayRequest.setSubAppID(stringRedisTemplate.opsForValue().get("login_wx_app_appid"));
                        txPayRequest.setRedirectSource("10");
                        break;
                    case ZJ_TYPE_JSAPI:
                        //微信h5
                        txPayRequest.setPaymentWay("80");
                        txPayRequest.setPayType("31");
                        txPayRequest.setPayWay("50");
                        txPayRequest.setPlatformName(stringRedisTemplate.opsForValue().get("basic_site_name"));
                        txPayRequest.setSubOpenID(getOpenId(payType, memberId, code));
                        txPayRequest.setSubAppID(stringRedisTemplate.opsForValue().get("login_wx_dev_appid"));
                        txPayRequest.setRedirectSource("30");
                        break;
                    case ZJ_TYPE_MWEB:
                        //普通h5
                        txPayRequest.setPaymentWay("80");
                        txPayRequest.setPayType("31");
                        txPayRequest.setPayWay("45");
                        txPayRequest.setPlatformName(stringRedisTemplate.opsForValue().get("basic_site_name"));
                        txPayRequest.setSubAppID(stringRedisTemplate.opsForValue().get("login_wx_dev_appid"));
                        txPayRequest.setRedirectSource("20");
                        break;
                    case ZJ_TYPE_MINIAPP:
                        //微信小程序
                        txPayRequest.setPaymentWay("80");
                        txPayRequest.setPayType("31");
                        txPayRequest.setPayWay("51");
                        txPayRequest.setPlatformName(stringRedisTemplate.opsForValue().get("basic_site_name"));
                        txPayRequest.setSubOpenID(getOpenId(payType, memberId, code));
                        txPayRequest.setSubAppID(stringRedisTemplate.opsForValue().get("login_wx_mini_appid"));
                        txPayRequest.setRedirectSource("40");
                        break;
                }
                break;
            case METHOD_ZJ_ALI:
                //支付宝
                switch (payType) {
                    case ZJ_TYPE_NATIVE:
                        //扫码
                        txPayRequest.setPaymentWay("42");
                        txPayRequest.setScanPaymentType(ZJ_QR_TYPE_ALI);
                        break;
                    case ZJ_TYPE_APP:
                        //app
                        txPayRequest.setPaymentWay("80");
                        txPayRequest.setPayType("32");
                        txPayRequest.setPayWay("46");
                        txPayRequest.setPlatformName(stringRedisTemplate.opsForValue().get("basic_site_name"));
                        txPayRequest.setRedirectSource("10");
                        break;
                    case ZJ_TYPE_MWEB:
                        //普通h5
                        txPayRequest.setPaymentWay("80");
                        txPayRequest.setPayType("32");
                        txPayRequest.setPayWay("45");
                        txPayRequest.setPlatformName(stringRedisTemplate.opsForValue().get("basic_site_name"));
                        txPayRequest.setRedirectSource("20");
                        break;
                }
                break;
        }
        return txPayRequest;
    }


    /**
     * 公众号支付/小程序支付，获取openid
     *
     * @param payType  支付类型，公众号/小程序
     * @param memberId 会员id
     * @param code     用户code
     * @return openid
     */
    private String getOpenId(String payType, Integer memberId, String code) {
        //获取openid的url
        String token_url;
        if (WX_TYPE_MINIAPP.equals(payType)) {
            //小程序
            token_url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + stringRedisTemplate.opsForValue().get("login_wx_mini_appid") +
                    "&secret=" + stringRedisTemplate.opsForValue().get("login_wx_mini_appsecret") + "&js_code=" + code + "&grant_type=authorization_code";
        } else if (WX_TYPE_JSAPI.equals(payType)) {
            //微信内部浏览器
            token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + stringRedisTemplate.opsForValue().get("login_wx_dev_appid") +
                    "&secret=" + stringRedisTemplate.opsForValue().get("login_wx_dev_appsecret") + "&code=" + code + "&grant_type=authorization_code";
        } else {
            return "";
        }
        String resp = HttpUtil.get(token_url);
        if (0 == JSONObject.parseObject(resp).getIntValue("errcode")) {
            return JSONObject.parseObject(resp).getString("openid");
        } else {
            log.error("获取openid出错：" + resp);
            throw new MallException("获取openid出错：");
        }
    }

}
