uniapp 开发公众号 h5(openid,微信支付,订阅通知)

获取 openid,登陆

前台代码,注意修改 跳转地址 和 appid
onLoad((e)=>{
	if(e?.appkey && e?.inviterId && e?.wenId){}else{
		return uni.common.msg('链接不正确!')
	}
	let aaa=window.location.search
	if(!aaa){
		let url='https://xxxxx'+window.location.pathname+window.location.hash   //这里使用完整地址,
		url=encodeURIComponent(url)
		let state='lizhili' 
		window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxx&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state='+state+'#wechat_redirect'	
	}else{
		const queryString = aaa.split('?')[1];
		if (!queryString) {
			uni.common.msg('参数错误')
		}
		const params = queryString.split('&');
		const result = {};
		params.forEach(param => {
		const [key, value] = param.split('=');
			result[key] = decodeURIComponent(value);
		});
		if(!result?.code){
			uni.common.msg('参数错误')
		}
		//获取授权
		uni.common.httpPost('Weix/getuser2', {code:result.code}).then((res) => {
			openid.value=res.openid
			unionid.value=res?.unionid ? res.unionid : ''
			headimgurl.value=res?.headimgurl ? res.headimgurl : ''
			nickname.value=res?.nickname ? res.nickname : ''
			intttt(e) //接着操作数据
		});
	}
})
后端代码,获取openid,可以申请开放平台获取 联合id
$code =$request->post('code', '');
$appid='xxxxxx';
$secret='xxxxxx';
$res=Curl::curl("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code");
$res2=Curl::curl("https://api.weixin.qq.com/sns/userinfo?access_token={$res['access_token']}&openid={$res['openid']}&lang=zh_CN");
s($res2);

公众号支付

前台代码,注意修改 跳转地址 和 appid
uni.common.httpPost('weix/updateorderShare', { openid: openid.value,money }).then((res2) => {
//判断是否在微信环境中
	if (typeof WeixinJSBridge === 'undefined') {
		// onBridgeReady();
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
	function onBridgeReady() {
		WeixinJSBridge.invoke('getBrandWCPayRequest', {
			debug: true,
			appId: res2.appId,
			timeStamp: res2.timeStamp,
			nonceStr: res2.nonceStr,
			package: res2.package,
			paySign: res2.paySign,
			signType: res2.signType,
		}, function(res3) {
			if (res3.err_msg === 'get_brand_wcpay_request:ok') {
				// 支付成功的处理逻辑 
				uni.showToast({
					title: '微信支付成功',
					icon: 'none'
				})
				popup.value.close();
				uni.navigateTo({
					url:'/pages/paypages/paypages?type=1'
				})
			} else if (res3.err_msg == "get_brand_wcpay_request:cancel") {
				// 支付失败的处理逻辑 
				uni.showToast({
					title: '取消支付',
					icon: 'none'
				})
				popup.value.close();
			} else {
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				})
				popup.value.close();
				uni.navigateTo({
					url:'/pages/paypages/paypages?type=0'
				})
			}
		});
	}
});
后端代码,这里可以参考之前博客讲微信支付的
 $jia =$request->post('jia', 0);
$openid =$request->post('openid', '');
 //生成订单
 $orderNo =uniqid();
 ShareOrder::create([
     'order_no' => $orderNo,
     'openid' => $openid,
     'final_price' => $jia,
 ]);
 $config=[
     'mchid'=>'xxxxx',
     'zhengshu_no'=>'xxxxxx',
     'appid'=>'xxxxxx',
     'notify_url'=>'xxxxxx'
 ];
 $merchantId = $config['mchid'];
 // 从本地文件中加载「商户API私钥」,「商户API私钥」会用来生成请求的签名
 $merchantPrivateKeyFilePath = file_get_contents('/xxxxxxx/zhengshu/wx/apiclient_key.pem');
 $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
 // 「商户API证书」的「证书序列号」
 $merchantCertificateSerial = $config['zhengshu_no'];
 // 从本地文件中加载「微信支付平台证书」,用来验证微信支付应答的签名
 $platformCertificateFilePath = file_get_contents('/xxxxxxx/zhengshu/wx/cert.pem');
 $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
 // 从「微信支付平台证书」中获取「证书序列号」
 $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
 // 构造一个 APIv3 客户端实例
 $instance = Builder::factory([
     'mchid'      => $merchantId,
     'serial'     => $merchantCertificateSerial,
     'privateKey' => $merchantPrivateKeyInstance,
     'certs'      => [
         $platformCertificateSerial => $platformPublicKeyInstance,
     ],
 ]);
 try {
     $resp = $instance
         ->chain('v3/pay/transactions/jsapi')
         ->post(['json' => [
             'mchid'        => $config['mchid'],
             "out_trade_no"=> $orderNo,
             "appid"=> $config['appid'],
             "description"=> "付款",
             "notify_url"=> $config['notify_url'],
             "amount"=> [
                 "total"=> (int)($jia*100),
//                "total"=>1,
                 "currency"=> "CNY"
             ],
             "payer"=> [
                 "openid"=> $openid
             ]
         ]]);
     if ($resp->getStatusCode()==200) {
         $wo=json_decode($resp->getBody(), true); //prepay_id
         $params = [
             'appId'     => $config['appid'],
             'timeStamp' => (string)Formatter::timestamp(),
             'nonceStr'  => Formatter::nonce(),
             'package'   => 'prepay_id='.$wo["prepay_id"],
         ];
         $params += ['paySign' => Rsa::sign(
             Formatter::joinedByLineFeed(...array_values($params)),
             $merchantPrivateKeyInstance
         ), 'signType' => 'RSA'];

         // Db::name('user_gu')->where('id')
         echo json_encode($params);
         //s($params);
         // return ['code' => 1, 'message' => '微信支付成功','data'=>$params];
     }
 } catch (\Exception $e) {
     //return ['code' => 0, 'message' => '微信支付错误'];
     // 进行错误处理
     echo $e->getMessage(), PHP_EOL;
     if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
         $r = $e->getResponse();
         echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
         echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
     }
     echo $e->getTraceAsString(), PHP_EOL;
     $params='';
 }
 if($params){
     s($params);
 }else{
     e('支付失败');
 }

订阅通知,分享 等等

前台代码,需要先申请订阅模版
先引入 npm install weixin-js-sdk --save
import jweixin from 'weixin-js-sdk'
const makeJsapi=()=>{
	//请求生成 公众号 编辑 下面是关于ios 的适配
	let url=''
	let userAgent = navigator.userAgent;
	  if (/MicroMessenger/i.test(userAgent)) {
	    if (/iPhone|iPad|iPod/i.test(userAgent)) {
	      url=location.href.split('#')[0] 
	    }
	  }
	  if(!url){
		  url=location.href
	  }
	uni.common.httpPost('weix/makeJsapi', {url}).then(async (res) => {
		jweixin.config({
		  debug: true, 
		  appId: res.appid, 
		  timestamp: res.timestamp, 
		  nonceStr: res.nonceStr, 
		  signature: res.signature,
		  jsApiList: [], 
		  openTagList: ['wx-open-subscribe'] 
		});
		 jweixin.ready(function (e) {
		          console.log("注册api成功-",e)
		 });
		 jweixin.error(function (res) {
		        console.log("注册api失败-: ",res)
		});
	});
}
后端代码, 这里使用了 微信支付的 sdk
$url=$request->post('url', '');
$appid='xxxxxxxx';
$secret='xxxxxxxxxx';
$access_token=Cache::get('access_token');
if(!$access_token){
    $res=Curl::curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret");
    $access_token=$res['access_token'];
    Cache::set('access_token', $res['access_token'],7000);
}
$jsapi=Curl::curl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi");
$jsapToken=$jsapi['ticket'];
$noncestr=Formatter::nonce();
$timestamp=Formatter::timestamp();
$str="jsapi_ticket=$jsapToken&noncestr=$noncestr&timestamp=$timestamp&url=$url";
s([
    'appid'=>$appid, // 必填,公众号的唯一标识
    'timestamp'=>$timestamp , // 必填,生成签名的时间戳
    'nonceStr'=>$noncestr, // 必填,生成签名的随机串
    "signature"=> sha1($str)
]);

用js退出页面

const webout=()=>{
	setTimeout(function() {
		// 安卓
		document.addEventListener(
			"WeixinJSBridgeReady",
			function() {
				WeixinJSBridge.call("closeWindow");
			},
			false
		);
		// 苹果
		WeixinJSBridge.call("closeWindow");
	}, 800)

	window.top.close();
	window.close();
}
相关推荐
dccose7 分钟前
vue3 uniapp 扫普通链接或二维码打开小程序并获取携带参数
小程序·uni-app
fpcc4 小时前
redis6.0之后的多线程版本的问题
c++·redis
刘九灵4 小时前
Redis ⽀持哪⼏种数据类型?适⽤场景,底层结构
redis·缓存
上优5 小时前
uniapp 选择 省市区 省市 以及 回显
大数据·elasticsearch·uni-app
登云时刻7 小时前
Kubernetes集群外连接redis集群和使用redis-shake工具迁移数据(一)
redis·kubernetes·bootstrap
煎饼小狗13 小时前
Redis五大基本类型——Zset有序集合命令详解(命令用法详解+思维导图详解)
数据库·redis·缓存
秋意钟14 小时前
缓存雪崩、缓存穿透【Redis】
redis
简 洁 冬冬15 小时前
046 购物车
redis·购物车
soulteary15 小时前
突破内存限制:Mac Mini M2 服务器化实践指南
运维·服务器·redis·macos·arm·pika
wkj00116 小时前
php操作redis
开发语言·redis·php