uniap之微信公众号支付

近来用uniapp开发H5的时候,需要接入支付,原来都是基于后端框架来做的,所以可谓是一路坑中过,今天整理下大致流程分享给大家。

先封装util.js,便于后面调用
javascript 复制代码
const isWechat =function(){
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === 'micromessenger';
}
const wechatAppid = function() {
  return '你的appid';
}
const payed = function(data){
	WeixinJSBridge.invoke('getBrandWCPayRequest', data, function(respay) {
		if (respay.err_msg === "get_brand_wcpay_request:ok") {
			uni.showToast({
				title:'支付成功',
				icon:"none"
			})
		} else if (respay.err_msg === "get_brand_wcpay_request:cancel") {
			uni.showToast({
				title:"取消支付",
				icon:"none",
				duration:2000
			})
		} else if (respay.err_msg === "get_brand_wcpay_request:fail") {
			uni.showToast({
				title:"支付失败",
				icon:"none",
				duration:2000
			})
		}
	}, function(err) {
		uni.showToast({
			title:err,
			icon:"none",
			duration:2000
		})
	})
}
/**
 * http请求
 * action 方法名
 * data  传输数据
 * Method 请求方式 GET POST
 */
const Requests = function (action,data,Method='GET',event) {
	var headers = {
		'content-type': 'application/json' // 默认值
	}
	if (Method == 'POST') {
		headers = {
			'content-type': 'application/x-www-form-urlencoded' // 默认值
		}
	}
	uni.request({
		url: config.requestUrl + action,
		method:Method,
		header:headers,
		data: data,
		success(res) {
			if (res.data.status == 100) {
				return event(res.data);
			}else {
				uni.showToast({
					title: res.data.msg,
					icon:'none'
				})
			}
		},fail() {
			uni.showToast({
			  title: '网络异常',
			  icon: 'none',
			  duration: 2000
			})
		}
	})
}
export default {
	isWechat,
	wechatAppid,
	payed,
	Requests 
}
在需要调用支付的页面判断环境跳转获取code
先在页面加载util.js
javascript 复制代码
import util from 'common/util.js'
再在onload里判断获取code
javascript 复制代码
if(!options.code === false){
	this.code  =options.code
}else{
	if(util.isWechat()){
		let appid = util.wechatAppid();
		let local = window.location.href;
		window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+encodeURIComponent(local)+'&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
		return;
	}
}
最后再需要支付的地方进行调用
javascript 复制代码
var that = this
//先创建订单
util.Requests('order/createOrder',{id:that.id},'POST',  function(eve) {
		var eves = eve.result
		//再从后台获取统一下单支付参数
		util.Requests('pay/pay',{order_id:eves,code:that.code},'POST',  function(event) {
			util.payed(event.result)
	})
})

ok,至此,就结束了,喵~

相关推荐
阿里嘎多学长几秒前
2026-02-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Anastasiozzzz29 分钟前
Java异步编程:CompletableFuture从入门到底层实现
java·开发语言
九.九1 小时前
高性能算子库 ops-nn 的底层架构:从调度到指令的极致优化
开发语言
比奇堡派星星1 小时前
sed命令
linux·运维·服务器·开发语言
船神丿男人1 小时前
C++:STL string(一)
开发语言·c++
程序员zgh1 小时前
Linux 内存管理单元 MMU
linux·运维·服务器·c语言·开发语言·c++
想做功的洛伦兹力12 小时前
2026/2/12日打卡
开发语言·c++·算法
大模型玩家七七2 小时前
技术抉择:微调还是 RAG?——以春节祝福生成为例
android·java·大数据·开发语言·人工智能·算法·安全
逍遥德2 小时前
编程技能点小记之if-else条件分支合理用法
java·开发语言·代码规范·代码复审·极限编程·代码覆盖率
低调小一2 小时前
Fresco 图片加载全链路解析:从 SimpleDraweeView 到 Producer 责任链
android·开发语言·fresco