微信公衆號支付是指在微信內嵌瀏覽器進入到公衆號以後,點擊電商頁面的支付接口,他使用了微信內嵌瀏覽器的支持,開發步驟以下:前端
(1)首先開通企業公衆號帳戶而且開通支付接口,詳細步驟能夠參考相關文檔,這裏再也不細數,這一步問題不大,主要是企業帳號等信息要設置準確,除了公衆號還有企業商戶號要設置。java
(2)將用戶openid傳遞到支付連接的參數中,例如:數據庫
<a href="/product/buy?id=productid&openid=user_openid">支付 </a>json
(3)先寫好支付成功後的微信回調函數處理程序,成功的話微信會訪問配置好的通知url(notify_url),會嘗試8次直到咱們寫回去success或者fail,示例代碼以下:api
@RequestMapping(value = "/wxpaycallback", method = { RequestMethod.POST,
RequestMethod.GET }, produces = { "application/json;charset=utf-8" })
public String weixinNotify(HttpServletRequest request,
HttpServletResponse response) {
try {
response.setCharacterEncoding("UTF-8");
InputStream inStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
String resultStr = new String(outSteam.toByteArray(), "utf-8");
Map<String, String> resultMap =MessageUtil.parseXml(resultStr);
String out_trade_no = resultMap.get("out_trade_no");//訂單號
String return_code = resultMap.get("return_code");
String mch_id=resultMap.get("mch_id");
if (return_code.contains("SUCCESS")) {
// 此處就是你的邏輯代碼
if (mch_id.equals(WeixinUtil.MCH_ID)){
OrderLogic.finishOrder(out_trade_no);//處理該訂單的狀態
}
}
//返回消息給微信服務器
String retXml = "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>";
PrintWriter out = response.getWriter();
out.print(retXml);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";//這句話能夠不用吧?
}瀏覽器
(4)Js端代碼:服務器
商品頁面增長如下代碼就會調用支付流程:微信
function onBridgeReady() {
var appId = $('#appId').val();// getUrlParam('appId');
var timeStamp = $('#timeStamp').val();// getUrlParam('timeStamp');
var nonceStr = $('#nonceStr').val();// getUrlParam('nonceStr');
var Package = $('#packageid').val();// getUrlParam('package');
var signType = $('#signType').val();// getUrlParam('signType');
var paySign = $('#paySign').val();// getUrlParam('paySign');
WeixinJSBridge.invoke('getBrandWCPayRequest', {
"appId" : appId, //公衆號名稱,由商戶傳入
"timeStamp" : timeStamp,// "1395712654", //時間戳,自1970年以來的秒數
"nonceStr" : nonceStr,// "e61463f8efa94090b1f366cccfbbb444", //隨機串
"package" : Package,// "prepay_id=u802345jgfjsdfgsdg888",
"signType" : signType,// "MD5", //微信簽名方式:
"paySign" : paySign,// "70EA570631E4BB79628FBCA90534C63FF7FADD89"
// //微信簽名
}, function(res) { // 使用以上方式判斷前端返回,微信團隊鄭重提示:res.err_msg將在用戶支付成功後返回
// ok,但並不保證它絕對可靠。
// alert(res.err_msg);
if (res.err_msg == "get_brand_wcpay_request:ok") {
alert("success");
}
if (res.err_msg == "get_brand_wcpay_request:cancel") {
alert("cancel");
}
if (res.err_msg == "get_brand_wcpay_request:fail") {
alert("fail");
}
});
}
function callPay() {
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();
}
}app
(5)還須要預先調用預下單接口才行,這部分代碼暫時找不到了,後面補充。dom
寫的不是很流暢,第一次寫,感受微信支付接口挺繞的,不如支付寶來的簡潔。
附件:
微信用戶在不一樣的公衆號裏時候openid值是不同的,所以在支付的時候要先將用戶的openid獲取到傳遞給支付頁面。獲取openid一個方式是經過Oauth連接,就是說先進入Oauth地址,將H5頁面url做爲參數傳遞給Oauth連接,微信會回調這個url並將隨機的code傳給這個H5,經過code來查詢微信api獲取openid值。
public class WeixinLogic {
private static final Logger logger = LoggerFactory
.getLogger(WeixinLogic.class);
private static Gson gson = MyGlobal.gson();
/*
* 生成並記錄短信驗證碼到數據庫
*/
private static String genBindSmsCode(String mobile) {
String code = "";
DB db = MyMongo.getDB();
if (db != null) {
code = UserLogic.createRandom(true, 4);
DBCollection collection = db.getCollection("wxsmscode");
BasicDBObject cond = new BasicDBObject("mobile", mobile);
DBObject obj = collection.findOne(cond);
if (obj != null) {
DBObject doc = new BasicDBObject("$set", new BasicDBObject(
"code", code));
collection.update(cond, doc);
} else {
DBObject doc = new BasicDBObject().append("mobile", mobile)
.append("code", code);
collection.insert(doc);
}
}
return code;
}
/*
* 發送短信驗證碼
*/
public static void SendSmsCode(String mobile) {
String code = genBindSmsCode(mobile);
UserLogic.sendSmsCode(mobile, code);
}
/*
* 綁定公衆號和手機號 成功返回true
*/
public static boolean bindwx(String openid, String mobile, String code) {
boolean ret = false;
if (!isMobileExist(mobile)) {
return false;
}
if (!checkSmsCode(mobile, code)) {
return false;
}
String old = getbindmobile(openid);
DB db = MyMongo.getDB();
if (db != null) {
DBCollection collection = db.getCollection("bindweixin");
if (!old.equals("")) {
collection.remove(new BasicDBObject("openid", openid));
}
try {
BindWeixin info = new BindWeixin();
DBObject doc = (DBObject) JSON.parse(gson.toJson(info));
collection.insert(doc);
return true;
} catch (Exception e) {
logger.error("bindwx" + e.getMessage());
return false;
}
}
return ret;
}
private static boolean isMobileExist(String mobile) {
boolean ret = true;
return ret;
}
/*
* 短信碼是否正確
*/
private static boolean checkSmsCode(String mobile, String code) {
boolean ret = false;
DB db = MyMongo.getDB();
if (db != null) {
DBCollection collection = db.getCollection("wxsmscode");
BasicDBObject cond = new BasicDBObject("mobile", mobile).append(
"code", code);
DBObject obj = collection.findOne(cond);
if (obj != null) {
ret = true;
}
}
return ret;
}
/*
* 返回微信用戶綁定的手機號
*/
public static String getbindmobile(String openid) {
String mobile = "";
DB db = MyMongo.getDB();
if (db != null) {
DBCollection collection = db.getCollection("bindweixin");
try {
DBObject obj = collection.findOne(new BasicDBObject("openid",
openid));
if (obj != null) {
BindWeixin info = gson.fromJson(obj.toString(),
BindWeixin.class);
mobile = info.mobile;
}
} catch (Exception e) {
logger.error("getbindmobile:" + e.getMessage());
}
}
return mobile;
}
public static void sendWXMonny(String re_openId, int money) {
String URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
String mch_id =WeixinUtil.MCH_ID;
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
parameters.put("wxappid",WeixinUtil.APPID);
parameters.put("mch_id", mch_id);
String nonscr = UUID.randomUUID().toString().toUpperCase()
.replace("-", "");
parameters.put("nonce_str", nonscr);// 隨機字符串
parameters.put("send_name", "中醫管家");
String billno = createBillNo(mch_id, "01");
parameters.put("mch_billno",billno);
parameters.put("re_openid", re_openId);//個人微信openid: "oW9-5s8Aecs_teXlIuwTwNbLQyHk"
parameters.put("total_amount",money+"");
parameters.put("total_num", "1");
parameters.put("wishing", "中醫管家");
parameters.put("client_ip", "127.0.0.1");
parameters.put("act_name", "測試紅包用例");
parameters.put("remark", "中醫管家");
// String sign = createSign("UTF-8", parameters);
// parameters.put("sign", sign);
sign(parameters);
String requestXML = getRequestXml(parameters);
String result = httpsRequest(URL, "POST", requestXML);
System.out.println("result:" + result);
}
public static String unifiedOrder(String openid,String trade_no,int fee,String doctorName){
//統一下單支付
String unified_url="https://api.mch.weixin.qq.com/pay/unifiedorder";
String notify_url="http://123.56.140.11/health/wxpaycallback";
// trade_no=UUID.randomUUID().toString().replace("-","");
try {
//生成sign簽名
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
parameters.put("appid",WeixinUtil.APPID);
parameters.put("attach", "中醫管家");
parameters.put("body",doctorName);
parameters.put("mch_id",WeixinUtil.MCH_ID);
String nonscr =trade_no;// UUID.randomUUID().toString().toUpperCase().replace("-", "");
parameters.put("nonce_str", nonscr);
parameters.put("notify_url",notify_url);
parameters.put("out_trade_no", trade_no);
parameters.put("total_fee",fee+"");
parameters.put("trade_type", "JSAPI");
parameters.put("spbill_create_ip","127.0.0.1");
parameters.put("openid", openid);
parameters.put("device_info", "WEB");
sign(parameters);
String requestXML = getRequestXml(parameters);
String result =WeixinUtil. httpsRequest(unified_url, "POST", requestXML);
System.out.println("result:" + result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private static String getRandomNum(int length) {
String val = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
val += String.valueOf(random.nextInt(10));
}
return val;
}
public static String createBillNo(String mch_id, String userId) {
// 組成: mch_id+yyyymmdd+10位一天內不能重複的數字
// 10位一天內不能重複的數字實現方法以下:
// 由於每一個用戶綁定了userId,他們的userId不一樣,加上隨機生成的(10-length(userId))可保證這10位數字不同
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyymmdd");
String nowTime = df.format(dt);
int length = 10 - userId.length();
return mch_id + nowTime + userId + getRandomNum(length);
}
public static void sign(SortedMap<Object, Object> params) {
String KEY =WeixinUtil.APIKEY;
Set<Entry<Object, Object>> entrys = params.entrySet();
Iterator<Entry<Object, Object>> it = entrys.iterator();
StringBuffer result = new StringBuffer();
while (it.hasNext()) {
Entry<Object, Object> entry = it.next();
result.append(entry.getKey()).append("=").append(entry.getValue())
.append("&");
}
result.append("key=").append(KEY);
params.put("sign", MD5Util.MD5Encode(result.toString(), "UTF-8")
.toUpperCase());
}
/*
* 發送紅包接口示例
*/
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set<Entry<Object, Object>> es = parameters.entrySet();
Iterator<Entry<Object, Object>> it = es.iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = String.valueOf(entry.getValue());
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)
|| "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 發送https請求
*
* @param requestUrl
* 請求地址
* @param requestMethod
* 請求方式(GET、POST)
* @param outputStr * 提交的數據 * @return 返回微信服務器響應的信息 */ public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) { try { String result = ""; // // 建立SSLContext對象,並使用咱們指定的信任管理器初始化 // TrustManager[] tm = { new MyX509TrustManager() }; // SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); // sslContext.init(null, tm, new java.security.SecureRandom()); // // 從上述SSLContext對象中獲得SSLSocketFactory對象 // SSLSocketFactory ssf = sslContext.getSocketFactory(); // 指定讀取證書格式爲PKCS12 KeyStore keyStore = KeyStore.getInstance("PKCS12"); // 讀取本機存放的PKCS12證書文件 FileInputStream instream = new FileInputStream(new File( "/root/apiclient_cert.p12")); try { // 指定PKCS12的密碼(商戶ID) keyStore.load(instream,WeixinUtil.MCH_ID.toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(keyStore, WeixinUtil.MCH_ID.toCharArray()) .build(); // 指定TLS版本 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf).build(); //URL url = new URL(requestUrl); HttpPost httpPost = new HttpPost(requestUrl); StringEntity reqEntity = new StringEntity(outputStr, "utf-8"); // 若是此處編碼不對,可能致使客戶端簽名跟微信的簽名不一致 reqEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(entity.getContent(), "UTF-8")); String text; while ((text = bufferedReader.readLine()) != null) { result += text; } } EntityUtils.consume(entity); } finally { response.close(); } return result; // HttpsURLConnection conn = // (HttpsURLConnection)httpclient.execute(httpPost);// // url.openConnection(); // conn.setSSLSocketFactory(sslsf); // conn.setDoOutput(true); // conn.setDoInput(true); // conn.setUseCaches(false); // // 設置請求方式(GET/POST) // conn.setRequestMethod(requestMethod); // conn.setRequestProperty("content-type", // "application/x-www-form-urlencoded"); // // 當outputStr不爲null時向輸出流寫數據 // if (null != outputStr) { // OutputStream outputStream = conn.getOutputStream(); // // 注意編碼格式 // outputStream.write(outputStr.getBytes("UTF-8")); // outputStream.close(); // } // // 從輸入流讀取返回內容 // InputStream inputStream = conn.getInputStream(); // InputStreamReader inputStreamReader = new InputStreamReader( // inputStream, "utf-8"); // BufferedReader bufferedReader = new BufferedReader( // inputStreamReader); // String str = null; // StringBuffer buffer = new StringBuffer(); // while ((str = bufferedReader.readLine()) != null) { // buffer.append(str); // } // // 釋放資源 // bufferedReader.close(); // inputStreamReader.close(); // inputStream.close(); // inputStream = null; // conn.disconnect(); // return buffer.toString(); } catch (ConnectException ce) { logger.error("鏈接超時:{}", ce); } catch (Exception e) { logger.error("https請求異常:{}", e); } return null; } }