初试微信公众号支付

因为业务的需求,需要在微信内置的网页实现支付功能。微信提供的文档:https://pay.weixin.qq.com/index.php/core/home/login?return_url=%2F

通过综合考虑,选择公众号支付方式。 

第一步:需要本身的公众号去申请开通微信支付。

第二步:微信本身提供的开发文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1, 按照文档中的开发步骤,进行配置

第三步:首先需要在后台实现统一下单接口,

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import com.util.Constants;
import com.util.IdcardUtils;
import com.util.IpAddr;
import com.util.WxPayUtil;
import net.sf.json.JSONObject;

String requestUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
appid = "";
  mch_id =Constants.MCH_ID;//微信公众号开通支付功能会有对应的商户号
  nonce_str = WxPayUtil.generateNonceStr();
body = planName;
out_trade_no = WxPayUtil.getCurrentTimestamp()+"";
total_fee = premium;
String spbill_create_ip = IpAddr.GetIpAddr();
String notify_url=""; //异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
trade_type="JSAPI";
String openid = "";
Map<String, String> signMap = new HashMap();
signMap.put("appid", appid);
signMap.put("body", body);
signMap.put("mch_id", mch_id);
signMap.put("nonce_str", nonce_str);
signMap.put("notify_url", notify_url);
signMap.put("openid", openid);
signMap.put("out_trade_no", out_trade_no);
signMap.put("spbill_create_ip", spbill_create_ip);
signMap.put("total_fee", total_fee+"");
signMap.put("trade_type", trade_type);
key = Constants.TK_PARNTER_KEY;
sign = WxPayUtil.generateSignature(signMap,key);
signMap.put("sign", sign);
String mapXml = WxPayUtil.mapToXml(signMap);//注意以上参数的顺序不能有差错
//boolean mapRes = WxPayUtil.isSignatureValid(mapXml, key);
URL httpUrl = new URL(requestUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
httpURLConnection.setRequestProperty("Host", "api.mch.weixin.qq.com");
httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(10*1000);
  httpURLConnection.setReadTimeout(10*1000);
    httpURLConnection.connect();
  OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(mapXml.getBytes("UTF-8"));
        //获取内容
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        final StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        String resp = stringBuffer.toString();
        Syst em.out.println(resp);
        if (stringBuffer!=null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream!=null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map<String,String> result = WxPayUtil.xmlToMap(resp);
        String return_code = result.get("return_code");
        String return_msg = result.get("return_msg");
        String result_code = result.get("result_code");
        if(!"SUCCESS".equals(return_code)||!"SUCCESS".equals(result_code)){
        msg=return_msg;
        //return "success";
        }
        prepay_id = result.get("prepay_id");
        appid = result.get("appid");
        nonce_str = result.get("nonce_str");
        sign = result.get("sign");
        Long timeStampL = WxPayUtil.getCurrentTimestamp();
        timeStamp = timeStampL.toString();
        Map<String,String> twoSign = new HashMap<String, String>();
        twoSign.put("appId", appid);
        twoSign.put("timeStamp", timeStamp);
        twoSign.put("nonceStr", nonce_str);
        twoSign.put("package", "prepay_id="+prepay_id);
        twoSign.put("signType", "MD5");
        sign2 = WxPayUtil.generateSignature(twoSign, key);
return "success";

中间用到的一些工具包,微信均有提供(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1)。

第四步,如果成功的话会返回prepared_id,接下来实现前段页面,只需要在前段页面已有的逻辑代码上加上

if (typeof WeixinJSBridge == "undefined"){
          if( document.addEventListener ){
              document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
          }else if (document.attachEvent){
              document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
              document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
          }
        }else{
          onBridgeReady(result);
        }

function onBridgeReady(result){
      var appId = result.appid;
      var timeStamp=result.timeStamp;
      var nonceStr = result.nonce_str;
      var prepay_id = result.prepay_id;
      var paySign = result.sign2;
      WeixinJSBridge.invoke(
          'getBrandWCPayRequest',{
        "appId": appId,
        "timeStamp":timeStamp,
        "nonceStr":nonceStr,
        "package":"prepay_id="+prepay_id,
        "signType":"MD5",
        "paySign":paySign
          },
          function(res){     
              if(res.err_msg == "get_brand_wcpay_request:ok" ) {
              }else{
            alert("支付失败"); 
              }     // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回    ok,但并不保证它绝对可靠。 
          }
      ); 
    }
   

以上就是我实现微信公众号支付的过程,初次尝试,还请路过的大神提出改进;


在微信小程序中,requestAnimationFrame方法的兼容性存在问题。微信小程序本身不提供requestAnimationFrame方法,而是将其实现放在了webgl canvas的上下文中。因此,只有2.7.0版本以后的机型才能使用requestAnimationFrame方法。如果你想在使用普通的canvas时,也使用requestAnimationFrame来控制画面渲染刷新,可以使用setInterval或者setTimeout来实现降级处理。以下是降级处理的代码: ```javascript (function() { var lastTime = 0; // 兼容各种浏览器 var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } // 降级处理 if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { // 保证如果重复执行callback的话,callback的执行起始时间相隔16ms var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }()); ``` 这段代码可以使得在微信小程序中使用requestAnimationFrame方法进行画面渲染刷新。所以在微信小程序中,要使用requestAnimationFrame方法,需要进行降级处理。同时,需要注意的是,requestAnimationFrame和setTimeout不是一回事,根据其定义,可以在不同场景下使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [微信小程序webgl+Three.js初试水(一)](https://blog.csdn.net/sinat_33342614/article/details/99889762)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [从微信小程序重力感应API到requestAnimationFrame探索实现](https://blog.csdn.net/weixin_33747129/article/details/89175163)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值