欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信支付java版本之JSAPI支付+发送模板消息

程序员文章站 2024-03-13 16:18:27
本文为大家分享了java版本之jsapi支付+发送模板消息的相关资料,供大家参考,具体内容如下 1.工具类 工具类见:微信支付java版本之native付款 2....

本文为大家分享了java版本之jsapi支付+发送模板消息的相关资料,供大家参考,具体内容如下

1.工具类

工具类见:微信支付java版本之native付款

2.公众账号设置

微信支付java版本之JSAPI支付+发送模板消息

微信支付java版本之JSAPI支付+发送模板消息

3.代码实现

 openid:openid为用户与该公众账号之间代表用户的唯一标示 
以下类中涉及到生成token,关闭订单接口调用,获取配置文件信息,和工具类,在其他文章中有具体代码实现 

package com.zhrd.bussinss.platform.controller.rest;

import java.io.file;
import java.io.fileinputstream;
import java.io.inputstream;
import java.security.keystore;
import java.text.simpledateformat;
import java.util.arraylist;
import java.util.date;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import javax.net.ssl.sslcontext;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import net.sf.json.jsonobject;

import org.apache.http.httpentity;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httppost;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
import org.apache.http.conn.ssl.sslcontexts;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.util.entityutils;
import org.dom4j.document;
import org.dom4j.documenthelper;
import org.dom4j.element;
import org.dom4j.io.saxreader;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.bind.annotation.restcontroller;

import com.zhrd.bussinss.platform.bo.jspay;
import com.zhrd.bussinss.platform.bo.payhist;
import com.zhrd.bussinss.platform.constants.payhistorypaystatus;
import com.zhrd.bussinss.platform.constants.payhistorypaytype;
import com.zhrd.bussinss.platform.service.getweixinaccesstokenservice;
import com.zhrd.bussinss.platform.service.weixinpayservice;
import com.zhrd.bussinss.platform.utils.closeweixinorderutils;
import com.zhrd.bussinss.platform.utils.customizedpropertyplaceholderconfigurer;
import com.zhrd.bussinss.platform.weixinpayutils.clientcustomssl;

@restcontroller
@requestmapping("/rest/weixinsendmessage")
public class weixinsendmessagerestfulcontroller {
 
 
 @autowired
 weixinpayservice weixinpayservice;
 @autowired
 getweixinaccesstokenservice getweixinaccesstokenservice;
 
 private static long standardtime = 1662652800000l;
 
 
 
 /**
 * 微信发送消息
 * @param request
 * @param response
 * @return
 */
 @requestmapping(value="/weixinsend",method=requestmethod.get)
 @responsebody
 public object weixinsend(httpservletrequest request,httpservletresponse response,string orderno,string openid){
 system.out.println("==========================微信发送消息开始========================"+getweixinaccesstokenservice.accesstoken());
 try{
 
 keystore keystore = keystore.getinstance("pkcs12");
 fileinputstream instream = new fileinputstream(new file(
 customizedpropertyplaceholderconfigurer.getcontextproperty("wx.cert").tostring()));
 try {
 keystore.load(instream, "见邮件".tochararray());
 }finally {
 instream.close();
 }

 // trust own ca and all self-signed certs
 sslcontext sslcontext = sslcontexts.custom().loadkeymaterial(keystore,
 "10061401".tochararray()).build();
 // allow tlsv1 protocol only
 sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory(
 sslcontext, new string[] { "tlsv1" }, null,
 sslconnectionsocketfactory.allow_all_hostname_verifier);
 closeablehttpclient httpclient = httpclients.custom()
 .setsslsocketfactory(sslsf).build();
 // httpget httpget = new
 // httpget("https://api.mch.weixin.qq.com/secapi/pay/refund");   //获取token详见获取token的文章
 httppost httppost = new httppost(
 "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getweixinaccesstokenservice.accesstoken());
 
 
 
 payhist ph = null;
 list<map<string,object>> td = weixinpayservice.gettrade(orderno);
 date dt = new date();
 simpledateformat sdf = new simpledateformat("yyyymmddhhmmss");
 string noncestr = sdf.format(dt).tostring();
 date now = new date();
 
 string tradepayno = orderno+string.format("%10d",standardtime - now.gettime()).substring(0, 10);
 system.out.println("订单标号orderno======="+orderno);
 system.out.println("10位随机数======="+string.format("%10d",standardtime - now.gettime()).substring(0, 10));
 string price = math.round(float.valueof(td.get(0).get("price").tostring())*100)+"";
 long timeexpirestrold = dt.gettime();   //获取配置文件信息 详见获取配置文件信息的文章
 long timenew = long.parselong(customizedpropertyplaceholderconfigurer.getcontextproperty("weixin.send2finish.overtime").tostring());
 long timeexpirenew = timeexpirestrold+timenew;
 date dttimeexpire = new date(timeexpirenew);
 simpledateformat dtsdf = new simpledateformat("yyyymmddhhmmss");
 string timeexpire = dtsdf.format(dttimeexpire).tostring();
 system.out.println("noncestr=="+noncestr);
 system.out.println("orderno=="+orderno);
 system.out.println("price=="+price);
 system.out.println("timestart=="+noncestr);
 system.out.println("timeexpire=="+timeexpire);
 
 
 
 jsonobject resultjspay = (jsonobject) getjspay(noncestr, "订单", tradepayno, price, noncestr,timeexpire,openid);
 resultjspay.getstring("prepayid");
 
 system.out.println("================222prepay_id222========================="+resultjspay.getstring("prepayid").tostring());
 
 list<map<string,map<string,string>>> data = new arraylist<map<string,map<string,string>>>();
 map<string,map<string,string>> firstparam = new hashmap<string, map<string,string>>();
 map<string,string> valueparam = new hashmap<string, string>();
 valueparam.put("value", td.get(0).get("buyername")+"(先生/女士)的订单");
 valueparam.put("color", "#173177");
 map<string,string> valueparam1 = new hashmap<string, string>();
 valueparam1.put("value", orderno);
 valueparam1.put("color", "#173177");
 map<string,string> valueparam2 = new hashmap<string, string>();
 valueparam2.put("value", "智慧社区爱生鲜订单");
 valueparam2.put("color", "#173177");
 map<string,string> valueparam3 = new hashmap<string, string>();
 valueparam3.put("value", td.get(0).get("price")+"元");
 valueparam3.put("color", "#173177");
 map<string,string> valueparam4 = new hashmap<string, string>();
 valueparam4.put("value", "等待支付");
 valueparam4.put("color", "#173177");
 map<string,string> valueparam5 = new hashmap<string, string>();
 valueparam5.put("value", "点击支付");
 valueparam5.put("color", "#173177");
 firstparam.put("first", valueparam);
 firstparam.put("keyword1", valueparam1);
 firstparam.put("keyword2", valueparam2);
 firstparam.put("keyword3", valueparam3);
 firstparam.put("keyword4", valueparam4);
 firstparam.put("remark", valueparam5);
 data.add(firstparam);
 
 jspay jp = new jspay();
 jp.settouser(openid);
 jp.settemplate_id("miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6p9gpgg");
 jp.settopcolor("#173177");
 jp.seturl("http://公众账号设置的链接/weixin_jspay/weixinjspay/init.action?packagevalue="+resultjspay.getstring("prepayid").tostring());
 jp.setdata(data);
 jsonobject jsonobject = jsonobject.fromobject(jp);
 string str = new string(jsonobject.tostring().getbytes("utf-8"), "iso8859-1"); 
 
// string xml = clientcustomssl.refundnativepackage(weixinrefundservice.gettradepayno(orderno),noncestr,totalfee,refundfee,noncestr);
 try {
 system.out.println("data=========="+str.tostring());
 stringentity se = new stringentity(str.tostring().replace("[", "").replace("]", "").tostring());
 
 httppost.setentity(se);

 system.out.println("executing request" + httppost.getrequestline());

 closeablehttpresponse responseentry = httpclient.execute(httppost);
 try {
 httpentity entity = responseentry.getentity();
 
 
  inputstream in = entity.getcontent(); 
  byte b[] = new byte[1024]; 
  int len = 0; 
  int temp=0;  //所有读取的内容都使用temp接收 
  while((temp=in.read())!=-1){ //当没有读取完时,继续读取 
  b[len]=(byte)temp; 
  len++; 
  } 
  in.close(); 
  system.out.println(new string(b,0,len)); 
  
  
  
 if (entity != null) {
 system.out.println("response content length: "
  + entity.getcontentlength());
 system.out.println("==="+responseentry.getentity().tostring());
 
 jsonobject result = jsonobject.fromobject(new string(b,0,len));
 if(result.getstring("errmsg").equals("ok")){
 ph = new payhist();
 ph.settradepayurl("");
 ph.setpaytradeno(orderno);
 ph.settradepayno(tradepayno);
 ph.setpaystatus(payhistorypaystatus.wechat_pay_status_wait);
 ph.setpaytype(payhistorypaytype.wechat_js_pay);
 list<payhist> payhistlist = weixinpayservice.getpayhist(orderno,"wechat","");
 if(payhistlist == null || payhistlist.size() == 0){
  weixinpayservice.addpayhist(ph);
 }else{         //关闭订单详见取消订单的文章
  jsonobject strstatus = (jsonobject) closeweixinorderutils.closeweixinorder(payhistlist.get(0).gettradepayno());
  if(strstatus.getstring("status").equals("success")){
  system.out.println(ph.gettradepayno());
  weixinpayservice.updatepayhist(ph);
  }
 }
 }
 
 return result;

 }
 entityutils.consume(entity);
 }
 finally {
 responseentry.close();
 }
 }
 finally {
 httpclient.close();
 }
 return null;
 
 }catch(exception e){
 e.printstacktrace();
 jsonobject result = new jsonobject();
 result.put("status","error");
 result.put("msg",e.getmessage());
 return result;
 }
 
 
 }
 
 public static object getjspay(string noncestr,string orderdescribe,string orderno,string price,string timestart,string timeexpire,string openid) {
 try{
 
 keystore keystore = keystore.getinstance("pkcs12");
 fileinputstream instream = new fileinputstream(new file(
 customizedpropertyplaceholderconfigurer.getcontextproperty("wx.cert").tostring()));
 try {
 keystore.load(instream, "10061401".tochararray());
 }finally {
 instream.close();
 }

 // trust own ca and all self-signed certs
 sslcontext sslcontext = sslcontexts.custom().loadkeymaterial(keystore,
 "见邮件".tochararray()).build();
 // allow tlsv1 protocol only
 sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory(
 sslcontext, new string[] { "tlsv1" }, null,
 sslconnectionsocketfactory.allow_all_hostname_verifier);
 closeablehttpclient httpclient = httpclients.custom()
 .setsslsocketfactory(sslsf).build();
 // httpget httpget = new
 // httpget("https://api.mch.weixin.qq.com/secapi/pay/refund");
 httppost httppost = new httppost(
 "https://api.mch.weixin.qq.com/pay/unifiedorder");
 
 string xml = clientcustomssl.createjsapipackage(noncestr,orderdescribe,orderno,price,timestart,timeexpire,openid);
 try {

 
 stringentity se = new stringentity(xml);
 
 httppost.setentity(se);

 system.out.println("executing request" + httppost.getrequestline());

 closeablehttpresponse responseentry = httpclient.execute(httppost);
 try {
 httpentity entity = responseentry.getentity();

 system.out.println("----------------------------------------");
 system.out.println(responseentry.getstatusline());
 if (entity != null) {
 system.out.println("response content length: "
 + entity.getcontentlength());
 
 saxreader saxreader = new saxreader();
 document document = saxreader.read(entity.getcontent());
 element rootelt = document.getrootelement();
 
 document documentxml =documenthelper.parsetext(xml);
 element rooteltxml = documentxml.getrootelement();
 
 
 system.out.println("根节点:" + rootelt.getname());
 system.out.println("==="+rootelt.elementtext("result_code"));
 system.out.println("==="+rootelt.elementtext("return_msg"));
 string resultcode = rootelt.elementtext("result_code");
 jsonobject result = new jsonobject();
 if(resultcode.equals("success")){
 system.out.println("=================prepay_id===================="+ rootelt.elementtext("prepay_id"));
 result.put("prepayid", rootelt.elementtext("prepay_id"));
 result.put("sign",rooteltxml.elementtext("sign"));
 result.put("status","success");
 result.put("msg","success");
 }else{
 result.put("status","false");
 result.put("msg",rootelt.elementtext("err_code_des"));
 }
 
 
 return result;

 }
 entityutils.consume(entity);
 }
 finally {
 responseentry.close();
 }
 }
 finally {
 httpclient.close();
 }
 return null;
 
 
 }catch(exception e){
 e.printstacktrace();
 jsonobject result = new jsonobject();
 result.put("status","error");
 result.put("msg",e.getmessage());
 return result;
 }
 } 
 
 }

4.weixin_jspay项目中代码实现 
控制层代码 

package com.weixin.jspay.controller;



import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;


import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;



@controller
@requestmapping("/weixinjspay")
public class weixinjspaycontroller {
 

 @requestmapping(value = "/init", method = requestmethod.get)
 public string init( httpservletrequest request,httpservletresponse response,string packagevalue,string paysign) {
 system.out.println("===================微信jspay开始=================");
 system.out.println("packagevalue==============="+packagevalue);
 system.out.println("paysign====================="+paysign);
 request.setattribute("packagevalue", "prepay_id=" + packagevalue);
 request.setattribute("paysign", paysign);
 system.out.println("===================微信jspay页面跳转开始=================");
 return "weixin";
 }
 
 

}


 jsp代码

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="/weixin_jspay/js/md5.js"></script>

 

 <script language="javascript">
 window.onload=function(){
 var packagevalue = '${packagevalue}';
 var paysign = '${paysign}';
 alert("packagevalue======"+packagevalue);
 alert("paysign======"+paysign);
 var signstring ="appid=见公共账号&noncestr=随机字符串&package="+packagevalue+"&paysign="+paysign+"&signtype=md5&timestamp=时间"; 
  //alert(signstring);
  var md5signvalue= ("" + cryptojs.md5(signstring)).touppercase();
 
 //alert(md5signvalue);
 
 weixinjsbridge.invoke('getbrandwcpayrequest',{
  "appid" : "<span style="font-family: arial, helvetica, sans-serif;">见公共账号</span>",
  "timestamp" : "1395712654",
  "noncestr" : "123456",
  "package" : packagevalue,
  "signtype" : "md5", 
  "paysign" : md5signvalue
 },function(res){
 alert(res.err_msg);
 weixinjsbridge.log(res.err_msg); 
  if(res.err_msg == "get_brand_wcpay_request:ok"){ 
   alert("微信支付成功"); 
  }else if(res.err_msg == "get_brand_wcpay_request:cancel"){ 
   alert("用户取消支付"); 
  }else{ 
   alert("支付失败"); 
  } 
 })
 }
 
 
 
 </script>
 </head>
 <body>
 <button type="button" onclick="callpay('${packagevalue}','${paysign}')" >微信jspay</button> 
 </body>
</html> 

微信支付md5.js:md5.js 和微信支付开发文档:

本文已被整理到了《javascript微信开发技巧汇总》,欢迎大家学习阅读。

为大家推荐现在关注度比较高的微信小程序教程一篇:《微信小程序开发教程》小编为大家精心整理的,希望喜欢。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。