目录

1.前置条件

1.1官方文档

1.2申请微信商户号

1.2.1申请步骤

2.后端API实现

3.前端实现


1.前置条件

1.1官方文档

新版微信:支付开发者文档

旧版文档:https://pay.weixin.qq.com/wiki/doc/api/index.html

ps:旧版的SDK文档官网不再支持,本文demo基于旧版本的实现

下面账号实在官网申请的

1.2申请微信商户号

商户号的申请需要填写相关材料,签署电子协议等,申请后需要准备4个代码串。

appid、mch_id、partnerkey、sign

1.2.1申请步骤

2.后端API实现

微信支付-开发者文档

HttpClient

引入依赖

            <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.1</version></dependency>
//新版https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay6_0.shtml
//辅助微信接口调用的辅助函数<dependency><groupId>com.github.wxpay</groupId><artifactId>wxpay-sdk</artifactId><version>0.0.3</version></dependency>

此版本api为老版本主要使用3个函数

//获取随机字符串
WXPayUtil.generateNonceStr()
//MAP转换为XML字符串(自动添加签名)
WXPayUtil.generateSignedXml(param, partnerkey)
//xml转换成MAP
WXPayUtil.xmlToMap(result)

代码

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;/*** http请求客户端***/
public class HttpClient {private String url;private Map<String, String> param;private int statusCode;private String content;private String xmlParam;private boolean isHttps;private boolean isCert = false;//证书密码 微信商户号(mch_id)private String certPassword;public boolean isHttps() {return isHttps;}public void setHttps(boolean isHttps) {this.isHttps = isHttps;}public boolean isCert() {return isCert;}public void setCert(boolean cert) {isCert = cert;}public String getXmlParam() {return xmlParam;}public void setXmlParam(String xmlParam) {this.xmlParam = xmlParam;}public HttpClient(String url, Map<String, String> param) {this.url = url;this.param = param;}public HttpClient(String url) {this.url = url;}public String getCertPassword() {return certPassword;}public void setCertPassword(String certPassword) {this.certPassword = certPassword;}public void setParameter(Map<String, String> map) {param = map;}public void addParameter(String key, String value) {if (param == null)param = new HashMap<String, String>();param.put(key, value);}public void post() throws ClientProtocolException, IOException {HttpPost http = new HttpPost(url);setEntity(http);execute(http);}public void put() throws ClientProtocolException, IOException {HttpPut http = new HttpPut(url);setEntity(http);execute(http);}public void get() throws ClientProtocolException, IOException {if (param != null) {StringBuilder url = new StringBuilder(this.url);boolean isFirst = true;for (String key : param.keySet()) {if (isFirst)url.append("?");elseurl.append("&");url.append(key).append("=").append(param.get(key));}this.url = url.toString();}HttpGet http = new HttpGet(url);execute(http);}/*** set http post,put param*/private void setEntity(HttpEntityEnclosingRequestBase http) {if (param != null) {List<NameValuePair> nvps = new LinkedList<NameValuePair>();for (String key : param.keySet())nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数}if (xmlParam != null) {http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));}}private void execute(HttpUriRequest http) throws ClientProtocolException,IOException {CloseableHttpClient httpClient = null;try {if (isHttps) {if(isCert) {//TODO 需要完善FileInputStream inputStream = new FileInputStream(new File(ConstantPropertiesUtils.CERT));KeyStore keystore = KeyStore.getInstance("PKCS12");char[] partnerId2charArray = certPassword.toCharArray();keystore.load(inputStream, partnerId2charArray);SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();SSLConnectionSocketFactory sslsf =new SSLConnectionSocketFactory(sslContext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();} else {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain,String authType)throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();}} else {httpClient = HttpClients.createDefault();}CloseableHttpResponse response = httpClient.execute(http);try {if (response != null) {if (response.getStatusLine() != null)statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();// 响应内容content = EntityUtils.toString(entity, Consts.UTF_8);}} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {httpClient.close();}}public int getStatusCode() {return statusCode;}public String getContent() throws ParseException, IOException {return content;}
}

有了发送请求的方式后就需要拼接参数向官网提供的网址发送请求,在发送请求后返回二维码的字符串,在通过前端的解析获取字符串

    @Overridepublic Map createNative(Long orderId)  {try {
//        1.根据orderid查询订单信息OrderInfo orderInfo = orderService.getById(orderId);
//        2.根据订单信息,交易类型创建交易记录paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
//        3.封装调用微信接口参数HashMap<String, String> paramMap = new HashMap<>();paramMap.put("appid", ConstantPropertiesUtils.APPID);paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);paramMap.put("nonce_str", WXPayUtil.generateNonceStr());String body = orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname();paramMap.put("body", body);paramMap.put("out_trade_no", orderInfo.getOutTradeNo());paramMap.put("total_fee", "1"); //设置交易金额paramMap.put("spbill_create_ip", "127.0.0.1");paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");paramMap.put("trade_type", "NATIVE");
//        4.创建客户都安兑现是(url)HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
//        5.向客户都安对象存入参数(map=>xml)client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));client.setHttps(true);
//        6.客户都安对象发送请求client.post();
//        7.获取相应(xml),转换类型(xml=>map)String xml = client.getContent();System.out.println("xml=" + xml);Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
//        8.封装返回HashMap<String, Object> map = new HashMap<>();map.put("orderId", orderId);map.put("totalFee", orderInfo.getAmount());map.put("resultCode", resultMap.get("result_code"));map.put("codeUrl", resultMap.get("code_url"));return map;} catch (Exception e) {throw new RuntimeException(e);}}

3.前端实现

前端的实现需要单独使用一个工具vue-qriously该插件专门用于对微信的code进行二维码展示

安装:npm install vue-qriously

需要在main.js或者插件中启动工具

import Vue from 'vue'
import VueQriously from 'vue-qriously'
Vue.use(VueQriously)

页面实现

在主vue中绑定value值,就可以显示结果

<qriously :value="payObj.codeUrl" :size="220"></qriously>

微信二维码API支付实现demo相关推荐

  1. 微信二维码支付快速入门

    目录 一.二维码生成插件qrious 二.HttpClient 三.微信扫码支付 1.申请步骤 2.开发文档 四.入门Demo 1.工程搭建 2.myStudy-pay-interface 3.myS ...

  2. Java支付宝二维码支付和退款,微信二维码支付

    在蚂蚁金服开发平台下载demo 打开 TradePayDemo 项目,里面的main可以直接运行,在配置文件zfbinfo.properties中改为自己支付宝的信息 # 支付宝网关名.partner ...

  3. 对接微信二维码支付流程

    客户在平台下单 平台生成订单记录并且请求微信支付系统获取支付链接地址 微信支付系统响应支付地址通过平台H5技术生成支付二维码 用户扫描支付二维码跳转支付链接地址并且微信支付系统校验支付链接有效性 用户 ...

  4. 关于前端调用微信二维码支付,二维码无法显示的问题

    昨天测试提交了一个bug,说是公司网站调用微信支付时无法显示微信二维码,于是去测试环境测试了一下,发现果然有问题: 此时后台日志打印了如下信息,微信接口返回的错误提示是:"invalid s ...

  5. 微信二维码支付支付宝二维码支付(主扫模式)开发指南

    微信二维码支付 熟悉微信支付全家桶的童鞋应该都清楚,微信支付是没有提供PC网关支付的,那么传统的网站需要怎么接入微信支付产品呢? 我们可以选择微信支付中的Native支付产品,官方介绍: Native ...

  6. 支付付宝个人转账API,在线生成转账二维码API

    支付付宝个人转账API,在线生成转账二维码API 代码 alipays://platformapi/startapp?appId=09999988&actionType=toAccount&a ...

  7. 重磅!微信二维码引擎OpenCV开源!3行代码让你拥有微信扫码能力

    点击上方"CVer",选择加"星标"置顶 重磅干货,第一时间送达 本文转载自:OpenCV团队 2011年12月微信3.5版本正式上线"扫一扫&quo ...

  8. 微信二维码海报推广示例

    这俩天根据客户 需求 微信商城 能生成自己的二维码 并且 需先关注公众号,扫码的用户显示出自己的上级 研究两天,发现微信二维码接口能实现这个功能 ! 思路:1.生成微信永久二位码 具体看微信公众文档 ...

  9. PHP给微信二维码 添加背景和昵称 ,微信带参数海报跨坑记录。

    先获取微信二维码,这里我获取的是永久二维码: $wx= $this->getTicket($this->userid);//我带的参数是用户ID,可自由发挥.//下面是相关函数 funct ...

最新文章

  1. CentOS7 minimal 没有netstat命令
  2. JavaScript中的遍历详解
  3. Linux运维之常见命令
  4. MySQL在单表上创建视图
  5. C# winform 上传文件到服务器
  6. Windows 10推出周年更新,Edge浏览器支持扩展并改进JavaScript支持
  7. mysql timestampt 输入字符串的格式不正确._mysql中取出的时间格式不正确
  8. Eclipse中自动添加注释
  9. mysql中的isnull
  10. 有var d = new Date(‘20xx-m-09‘),可以设置为m+1月份的操作是?
  11. 使用NAS动态存储卷创建有状态应用
  12. 程序员都在用什么高效率的工具?
  13. Bailian2973 Skew数【进制】
  14. ENVI Flaash大气校正与6S大气校正(Landsat8OLI)
  15. MySQL乱码的问题
  16. 随机课堂、随机提问、随机抽检、随机名单,可去重可重复
  17. 群晖 kodi mysql,用群晖为 Kodi 注入多设备同步能力
  18. Excel 批量删除空白行,你用了 2 小时,同事 3 分钟就搞定了
  19. 运动蓝牙耳机挑选要注意什么?蓝牙耳机知识科普
  20. 二进制转bcd码c语言程序,二进制转8421BCD码的算法

热门文章

  1. 呼市丰州学院有计算机专业,内蒙古丰州职业学院计算机系
  2. 你的华为手机总是杀后台,很烦人!那是这4个设置没关闭吧
  3. 黑科技|你们要的手机AR导航来了!
  4. 2010年5月51CTO壁纸点评活动获奖公告
  5. 机器学习 第三节 第三课
  6. day28 static关键字详解 static在代码中的顺序
  7. VisionPro中分享CogPMAlignTool图像匹配工具的使用详解_史上最全
  8. PDF怎么转CAD?这些方法值得收藏
  9. 安装Vue CLI项目(Vue2.0)
  10. python xposed_Xposed应用的开发