微信支付-h5接入详细流程和代码

这里是具体的流程和代码,有什么疑问请参考我上一篇微信公众号接入流程的文章

1、申请一个微信服务号,这是你接入支付的前提
2、登录服务号,配置开发基本配置和网页授权权
3、申请开通微信支付,开通要使用的相关产品(公众号支付)
4、在账户中心进行相关的配置,设置秘钥

到这里前期的准备工作已经做完了,下面开始按照上面的流程开始进行代码的编写

---大戏开幕---

第一步:(我这里演示的是springmvc接入的版本)

编写controller ,在服务号中基本配置中配置的服务器地址URL

http://****/***-interface/wxPayApi/reqWxApp.htm

@Controller
@RequestMapping("/wxPayApi/")
public class WXPayApi extends BaseController{

@Autowired WXPayService wXPayService;
@Autowired OrderService orderService;

private static Logger logger = Logger.getLogger(WXPayApi.class);

         /**

     *

     * @Description: 用于接收get参数,返回验证参数

     * @param @param request

     * @param @param response

     * @param @param signature

     * @param @param timestamp

     * @param @param nonce

     * @param @param echostr

     * @author dapengniao

     * @date 2016年3月4日下午6:20:00

     */

    @RequestMapping(value = "reqWxApp.htm", method = RequestMethod.GET)

    public void doGet(

            HttpServletRequest request,

            HttpServletResponse response,

            @RequestParam(value = "signature", required = true) String signature,

            @RequestParam(value = "timestamp", required = true) String timestamp,

            @RequestParam(value = "nonce", required = true) String nonce,

            @RequestParam(value = "echostr", required = true) String echostr) {

        try {

            if (SignUtil.checkSignature(signature, timestamp, nonce)) {

                PrintWriter out = response.getWriter();

                out.print(echostr);

                out.close();

            } else {

                logger.info("这里存在非法请求!");

            }

        } catch (Exception e) {

            logger.error(e, e);

        }

    }


    @RequestMapping(value = "reqWxApp.htm", method = RequestMethod.POST)

    // post方法用于接收微信服务端消息

    public void  DoPost(HttpServletRequest request,HttpServletResponse response) throws IOException {

        System.out.println("这是post方法!");

        String openid = "";

        try{

               

        }catch(Exception e){

            logger.error(e,e);

        }

    }

   

}


第二步:

通过前台页面请求获取code,通过code获取页面授权的access_token,拿到openID

前台页面的代码:

var redirect_url = encodeURI("***********后台回调地址******************");

 location.href ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx798ded0c9460ae63"+

                   "&redirect_uri="+redirect_url+"&response_type=code&scope=snsapi_base"

                   +"&state=123#wechat_redirect";


后台代码:


//预支付选择商品页面.先获取用户code,再获取openId

    @RequestMapping(value = "/getOpenId.htm", method = RequestMethod.GET)  //{guid}

    public String  getDevicePay(Model model,@RequestParam("code") String code) throws Exception  {

             Map<String, String> map= new HashMap<String, String>();

             String param = "appid=wx798ded0c9460ae63&secret=30bdad70aafa34b8dc7609d1c9b39691&code="+ code +"&grant_type=authorization_code";

             String sr=HttpRequest.sendPost("https://api.weixin.qq.com/sns/oauth2/access_token", param);

        JSONObject json = JSONObject.fromObject(sr);

        String openID = String.valueOf(json.get("openid"));

        System.out.println("========openID==============================="+openID);

        if(!openID.equals("")){

//             eventService.saveOpenId(openID);

        }

       return "redirect:http://www.axigo.cn/axigo-wap/index1.html?openID="+openID;

}


通过后台方法把获取的openID返给前台,前台进行缓存;

这其中有一个恶心之处就是redirect跳转会刷新页面,一直没有解决,望大神们给小弟指点迷经,小弟不胜感激,我现在使用的方法是写两个首页,名称不同,从一个首页重定向到领一个首页,没有好的思路,望大神指点。。。。。。。。。


微信支付的接口代码

 

// @ApiOperation(value = "微信支付调用", httpMethod = "POST")

         @RequestMapping(value = "/couponsConfirm.htm", method = RequestMethod.POST)

         public @ResponseBody ResultBase couponsConfirm(HttpServletRequest request,@RequestBody Map<String, String> map) {

                  ResultBase res = new ResultBase();

                  JSONObject json = new JSONObject();

                  // 获取签名signature

                  String appId = ConfigUtil.APPID;// 取项目中配置的公众号id

                  String secret = ConfigUtil.APP_SECRECT;// 取项目中配置的公众号密钥

                  // 域名的切换

                  String domainAddr = "www.axigo.cn";// 项目中配置的网站的域名

                  Map<String, String> mapUrl = new HashMap<String, String>();

                  mapUrl.put("appid", appId);

                  mapUrl.put("secret", secret);

                  String cruurl = "";

                  if (map.containsKey("url") && CommonUtil.notEmpty(map.get("url").toString())) {

                          cruurl = map.get("url").toString();

                  }

                  String url = cruurl;

                  System.out.println("url=============================" + url);

                  mapUrl.put("url", url);

                  // 开始微信分享链接签名

                  Map<String, String> params = wXPayService.WXSignature(mapUrl);

                  json.put("params", params);

                  System.out.println("signature=============================" + String.valueOf(params.get("signature")));

                  json.put("signature", String.valueOf(params.get("signature")));

                  //=================================================================

                  String openid = "";

                  String orderNo = "";

                  String remoteAddr = request.getRemoteAddr();

                  if (CommonUtil.notEmpty(String.valueOf(map.get("openid")))) {

                          openid = String.valueOf(map.get("openid"));

                  }

                  if (CommonUtil.notEmpty(String.valueOf(map.get("orderNo")))) {

                          orderNo = String.valueOf(map.get("orderNo"));

                  }

                  System.out.println("========openid=================" + openid+ "==========================" + orderNo);

                  // openid可通过微信高级接口oath2.0网页授权接口获取到用户信息,此接口本文中就不提供了,如果有需要,请留言。

                  json.put("openid", openid);

                  // orderNo是你的商品订单号,自行生成的随机订单号,但是要保证随机性,不能有重复订单号。

                  json.put("orderNo", orderNo);

                  String timeStamp = PayCommonUtil.create_timestamp();

                  String nonceStr = PayCommonUtil.CreateNoncestr();

                  json.put("appid", ConfigUtil.APPID);

                  json.put("timestamp", timeStamp);

                  json.put("nonceStr", nonceStr);


                  String total_price = getWXPayParam(map);

                  String prepayId = WxPayUtil.unifiedorder("蒙源商城-购物支付", orderNo, openid,nonceStr,remoteAddr,total_price);

                  System.out.println("prepayId=================================>"+ prepayId);

                  // String userAgent = request.getHeader("user-agent");

                  // char agent =

                  // userAgent.charAt(userAgent.indexOf("MicroMessenger")+15);

                  // m.addAttribute("agent", new String(new

                  // char[]{agent}));//微信版本号,用于前面提到的判断用户手机微信的版本是否是5.0以上版本。


                  SortedMap<Object, Object> signParams = new TreeMap<Object, Object>();

                  signParams.put("appId", ConfigUtil.APPID);

                  signParams.put("nonceStr", nonceStr);

                  signParams.put("package", "prepay_id=" + prepayId);

                  signParams.put("timeStamp", timeStamp);

                  signParams.put("signType", "MD5");


                  // 生成支付签名,要采用URLENCODER的原始值进行SHA1算法!

                  String sign = PayCommonUtil.createSign(signParams);

                  System.out.println("paySign==============================" + sign);


                  json.put("paySign", sign);

                  json.put("signType", "MD5");


                  json.put("packageValue", "prepay_id=" + prepayId);


                  res.setObj(json);

                  res.setResult(ResultBase.RESULT_SUCC);

                  return res;

         }

   

         @RequestMapping(value = "succ.htm", produces = MediaType.APPLICATION_JSON_VALUE)

         public void wxpaySucc(HttpServletRequest request,HttpServletResponse response) throws IOException,JDOMException {

                  System.out.println("=========================微信支付回调===========================");

                  InputStream inStream = request.getInputStream();

                  ByteArrayOutputStream outSteam = new ByteArrayOutputStream();

                  byte[] buffer = new byte[1024];

                  int len = 0;

                  while ((len = inStream.read(buffer)) != -1) {

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值