微信小程序支付V3-jsapi,Java

准备工作:

1:邮箱(自行注册)

2:联系方式
3:小程序管理者身份证电子版

4:营业执照电子版
5:对公银行账户信息(税号,开户名,开户行,账号)

6:认证费用300

7:小程序上线必须要域名(本地测试不需要,可在微信开发者工具中将不校验域名勾选)

实现效果:点击付款手机下方弹出一个支付密码,展示支付金额

(自行添加的一个支付按钮做测试使用,具体业务做调整,只有支付,没做退款回调等)

前端代码:

<template>
	<view class="coll-list" v-for="item in collList">
		<view class="title">
			<text>商品名称:{{item.title}}</text>
			<text>商品金额:{{item.count}}</text>
			<text>商品描述:{{item.description}}</text>
			<button size="mini" v-if="item.status=='0'" @click="onpay(item)">待付款</button>
			<button size="mini" v-else-if="item.status=='1'">已付款</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				urlx: getApp().globalData.URLAl,
				YYMMDD: YYMMDD,
				collList: [{
						id: '0',
						title: "商品1",
						date: '2023-11-11',
						time: '17:55',
						img: "../../static/api.png",
						count: 1,
						status: '0',
						description: '这是一份'
					},
					{
						id: '1',
						title: "商品2",
						date: '2023-11-11',
						time: '17:55',
						img: "../../static/api.png",
						count: 1,
						status: '1',
						description: '这是一份111'
					}
				]
			}
		},
		onLoad() {
		},
		methods: {
			onpay(item) {
				wx.login({
					success(res) {
						if (res.code) {
							//发起网络请求
							wx.request({
								url: 'http://127.0.0.1:8085/weChatApp/appLogin',
								method: 'post',
								data: {
									code: res.code
								},
								success(res2) {
									let session_key = res2.data.data.session_key
									let openid = res2.data.data.openid

									// 发起支付
									wx.request({
										url: 'http://127.0.0.1:8085/appWeChatPay/paymentForGoods',
										method: 'post',
										data: {
											openid: openid,
											total: item.count, //金额必须是整数,以分为单位
											description: item.description
										},
										success(res3) {
											if (res3.data && res3.data.code == 200) {
												wx.requestPayment({
													"timeStamp": res3.data.timeStamp,
													"nonceStr": res3.data.nonceStr,
													"package": res3.data.package,
													"signType": res3.data.signType,
													"paySign": res3.data.paySign,
													success(res4) {
														console.log('用户支付扣款成功', res4)
													},
													fail(res4) {
														console.log('用户支付扣款失败', res4)
													}
												})
											}
										}
									})
								}
							})
						} else {
							console.log('登录失败!' + res.errMsg)
						}
					}

				})
			},
		}
	}
</script>

后端代码:

第一个接口:“/appLogin”

这个是获取当前用户的openid

@Override
    public Result<Object> appLogin(WeChatVO weiXinVO) {
        String code = weiXinVO.getCode();
        Result<Object> res = new Result<>();
        if (StringUtils.isNotEmpty(code)) {
            HttpUtil instance = HttpUtil.getInstance();
            String url = WeChatUrlConstants.CODE_SESSION_URL + "?appid=" + WxV3PayConfig.app_id +
                    "&secret=" + WxV3PayConfig.app_secret +
                    "&js_code=" + code +
                    "&grant_type=authorization_code";
            String result = instance.sendHttpGet(url);
            if (StringUtils.isNotEmpty(result)) {
                HashMap map = JSON.parseObject(result, HashMap.class);
                if (map.get("openid") != null) {
                    res.setMessage("查询成功");
                    res.setCode(200);
                    res.setData(map);
                    return res;
                }else{
                    res.setMessage((String) map.get("errmsg"));
                    res.setCode((Integer) map.get("errcode"));
                    res.setData(null);
                    return res;
                }
            }

        }else {
            res.setMessage("入参code为空,请联系管理员!");
            res.setCode(500);
            res.setData(null);
        }
        return res;
    }

第二个接口:“/paymentForGoods”

商户系统先调用该接口在微信支付服务后台生成预支付交易单
 @Override
    public Map<String, Object> weChatDoUnifiedOrder(WeChatPayVO weChatPayVO) throws IOException {

        //请求URL
        CloseableHttpClient httpClient = WXPaySignatureCertificateUtil.checkSign();
        HttpPost httpPost = new HttpPost(WeChatUrlConstants.JS_API);
        String outTradeNo = generateOrderId();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("mchid", WxV3PayConfig.mch_id)
                .put("appid", WxV3PayConfig.app_id)
                .put("description",weChatPayVO.getDescription())
                .put("notify_url", WeChatUrlConstants.WECHAT_PAY_NOTIFY_URL)//回调
                .put("out_trade_no", outTradeNo);
        rootNode.putObject("amount")
                .put("total",weChatPayVO.getTotal())
                .put("currency","CNY");
        rootNode.putObject("payer")
                .put("openid",weChatPayVO.getOpenid());
        // 请求body参数
        StringEntity entity = new StringEntity(rootNode.toString(),"utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HashMap<String, Object> map = new HashMap<>();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                JSONObject object = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
                String prepayId = object.getString("prepay_id");
                map.put("code",200);
                map.put("message", "下单成功");
                //获取预付单
                map.put("prepay_id",prepayId);
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));

                //生成签名
                Long timestamp = System.currentTimeMillis() / 1000;
                map.put("timeStamp",String.valueOf(timestamp));
                //随机字符串,长度为32个字符以下
                String nonceStr = WXPayUtil.generateNonceStr();
                map.put("nonceStr",nonceStr);
                //统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=***
                map.put("package","prepay_id="+prepayId);
                //签名算法,应与后台下单时的值一致
                map.put("signType","RSA");
                //生成带签名支付信息
                String paySign = WXPaySignatureCertificateUtil.jsApiPaySign(String.valueOf(timestamp), nonceStr, prepayId);
                map.put("paySign",paySign);
                return map;
            } else if (statusCode == 204) {
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            response.close();
        }
        return null;
    }

WeChatUrlConstants:
package com.insigma.hzrb.common.constant;


/**
 * 常量
 */
public class WeChatUrlConstants {

    public static String CODE_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";


    public static String JS_API = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";


    public static final String DOMAIN_API = "https://api.mch.weixin.qq.com/v3";


    //微信支付回调
    public static final String WECHAT_PAY_NOTIFY_URL = "";


    //申请退款
    public static final String REFUND_DOMESTIC_REFUNDS = "/refund/domestic/refunds";

    //微信退款回调
    public static final String WECHAT_REFUNDS_NOTIFY_URL = "https://xxx.xxxx.com/api/appPayment/weChatPayRefundsNotify";

    //关闭订单
    public static final String PAY_TRANSACTIONS_OUT_TRADE_NO   = "/pay/transactions/out-trade-no/{}/close";




}
WxV3PayConfig:这些参数哪里找可以自行百度,相当好找

import lombok.Data;


@Data
public class WxV3PayConfig {

    //支付通知地址
    private String payNotifyUrl;


    //平台证书序列号
    public static final String mchserialno = "";

    //appID
    public static final String app_id = "";
    // 小程序密钥
    public static final String app_secret = "";

    //商户id
    public static final String mch_id = "";

    // API V3密钥
    public static final String apiV3Key = "";

    // 商户API V3私钥
    public static final String privateKey = "";


}

有问题可以联系,业务代码自己添加

### 回答1: 微信小程序支付api-v3是微信提供的一种支付方式,它基于RESTful风格的API设计,使用HTTP协议传输数据,全部使用JSON格式,具有优秀的跨平台性能和安全性。本文将为大家提供微信小程序支付api-v3 php的完整代码。 微信小程序支付api-v3 php完整代码: 首先,需要获取商户的API密钥和证书文件,然后设置请求头信息,代码如下: $merchant_api_secret = 'Your Secret Key'; //商户API密钥 $merchant_cert_file = 'path/to/cert.pem'; //商户证书文件路径 $merchant_key_file = 'path/to/key.pem'; //商户密钥文件路径 $timestamp = time(); $nonce_str = uniqid(); $signature = generate_signature($merchant_api_secret, $timestamp, $nonce_str, $http_method, $http_uri, $query_string, $body); $header = array( 'Authorization: ' . $authorization, 'Accept: application/json', 'Content-Type: application/json', 'User-Agent: your-device', 'Wechatpay-Serial: your-certificate-serial-number', 'Wechatpay-Timestamp: ' . $timestamp, 'Wechatpay-Nonce: ' . $nonce_str, 'Wechatpay-Signature: ' . $signature, ); 然后,我们需要调用微信小程序支付api-v3接口,具体如下: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM'); curl_setopt($ch, CURLOPT_SSLCERT, $merchant_cert_file); curl_setopt($ch, CURLOPT_SSLKEY, $merchant_key_file); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method); if (!empty($body)){ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); } $response = curl_exec($ch); $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($status_code !== 200){ throw new Exception('微信小程序支付api-v3调用错误,错误代码' . $status_code); } $response_payload = json_decode($response, true); curl_close($ch); 以上就是微信小程序支付api-v3 php的完整代码,通过以上代码可以实现微信小程序支付api-v3的接口调用,实现支付等操作。同时需要注意的是,具体代码需要根据自己的实际情况进行调整。 ### 回答2: 微信小程序支付API-v3是一套用于支付的接口,支持PHP语言,这里提供完整的代码实现。 在使用微信小程序支付API-v3前需要进行身份验证,将私钥转换为PKCS8格式和获取API证书,并将两者合成一个PEM格式的文件。接下来就可以创建支付订单并进行支付了。 以下是PHP代码的示例: ```php <?php require_once "wxpayloader.php"; $wxpayConfig = new WxPayConfig(); // 公众号ID $wxpayConfig->setAppId("your app id"); // 商户号 $wxpayConfig->setMchId("your mch id"); // 商户API秘钥 $wxpayConfig->setApiKey("your api key"); // 商户API证书路径 $wxpayConfig->setSslCertPath("path/to/your/apiclient_cert.pem"); // 商户API证书密钥路径 $wxpayConfig->setSslKeyPath("path/to/your/apiclient_key.pem"); // 微信支付平台API证书路径 $wxpayConfig->setSslRootCaPath("path/to/your/rootca.pem"); // 接口请求地址 $wxpayConfig->setApiUrl("https://api.mch.weixin.qq.com/"); // 验证商户API证书 $result = WxPayApi::sslVerify($wxpayConfig); if($result['result'] != 0) { die("SSL证书验证失败:" . $result['errmsg']); } // 创建订单 $out_trade_no = "20170525" . rand(10000, 99999); $total_fee = 1; $trade_type = "JSAPI"; // 交易类型为小程序支付 $notify_url = "http://your.domain.com/weixin/paynotify.php"; // 支付结果通知URL $wxpayData = new WxPayData(); $wxpayData->setBody("test"); $wxpayData->setOutTradeNo($out_trade_no); $wxpayData->setTotalFee($total_fee); $wxpayData->setTradeType($trade_type); $wxpayData->setNotifyUrl($notify_url); $wxpayData->setOpenid("your openid"); // 用户的openid,小程序通过wx.login获取 // 统一下单 $result = WxPayApi::unifiedOrder($wxpayConfig, $wxpayData); if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') { die("统一下单失败:" . $result['err_code_des']); } // 获取微信小程序支付参数 $prepay_id = $result["prepay_id"]; $wxpayData = new WxPayData(); $wxpayData->setAppId($wxpayConfig->getAppId()); $wxpayData->setTimeStamp(time()); $wxpayData->setNonceStr(WxPayApi::generateNonceStr()); $wxpayData->setPackage("prepay_id=" . $prepay_id); $wxpayData->setSignType("RSA"); // 生成签名 $sign = WxPayApi::generateSignature($wxpayData, $wxpayConfig); // 将签名加到数据包中 $wxpayData->setPaySign($sign); // 返回小程序支付参数 echo json_encode($wxpayData->getValues()); ``` 以上代码首先创建了WxPayConfig对象,将商户号、API密钥、API证书路径等信息设置进去。然后创建订单数据包,通过WxPayApi::unifiedOrder方法提交到微信支付平台统一下单。如果成功,则获取预支付ID,按照微信小程序支付的规定生成签名,再将签名加到数据包中,最终返回给小程序,由小程序前端发起支付请求。 获取API证书和PKCS8格式私钥的方法,请参考微信支付平台官方文档。 ### 回答3: 微信小程序支付 API-v3 提供了一种安全、高效、简便的支付方式,帮助开发者更好地满足用户需求。以下是微信小程序支付 API-v3 PHP 完整代码。 首先,要使用微信小程序支付 API-v3,需要先在微信支付商户平台上注册并开通服务。 接下来,下载 PHP SDK 安装包,将下载得到的文件解压后,将文件夹内的文件复制到项目代码所在的目录中。 在代码中导入 SDK 中的类库: ```php require_once "lib/WxPay.Api.php"; require_once "lib/WxPay.Data.php"; ``` 接着,需要通过商户号和 API 密钥进行身份验证: ```php $config = new WxPayConfig(); $config->SetMerchantId("商户号"); $config->SetKey("API密钥"); ``` 然后,实例化一个统一下单对象,并设置相关支付参数: ```php $input = new WxPayUnifiedOrder(); $input->SetBody("商品描述"); // 商品描述 $input->SetAttach("附加数据"); // 附加数据 $input->SetOut_trade_no("商户订单号"); // 商户订单号 $input->SetNotify_url("回调URL"); // 回调URL $input->SetTotal_fee("总金额"); // 总金额(单位:分) $input->SetTrade_type("JSAPI"); // 交易类型 $input->SetOpenid("用户openid"); // 用户openid ``` 接着,调用统一下单 API 并获取支付参数: ```php $order = WxPayApi::unifiedOrder($config, $input); $prepayId = $order["prepay_id"]; $nonceStr = WxPayApi::getNonceStr(); $timeStamp = time(); $package = "prepay_id=" . $prepayId; $signType = "HMAC-SHA256"; $paySign = WxPayApi::getPaySign($config, $nonceStr, $package, $signType, $timeStamp); ``` 最后,在前端页面中使用获取到的支付参数调起微信支付即可。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值