当前位置: 首页 > news >正文

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

获取 openid,登陆

前台代码,注意修改 跳转地址 和 appid
onLoad((e)=>{if(e?.appkey && e?.inviterId && e?.wenId){}else{return uni.common.msg('链接不正确!')}let aaa=window.location.searchif(!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.openidunionid.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();
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • C++ -- 负载均衡式在线OJ (一)
  • 大模型 - 分布式训练方法汇总
  • SQL-锁
  • 【算法】最短路径算法思路小结
  • C#中Override与New关键字的运用及实例解析
  • c# 什么是扩展方法
  • Oracle-OracleConnector
  • Linux应用层开发(7):网络编程
  • html+css+js网页设计 找法网2个页面(带js)ui还原度百分之90
  • C语言实现UDP广播
  • 力扣227题基本计算器II(Python实现)
  • Kali Linux——网络安全的瑞士军刀
  • 登录页滑块验证图
  • Windows下编译安装PETSc
  • 简单介绍BTC的Layer2项目RGB
  • [Vue CLI 3] 配置解析之 css.extract
  • docker-consul
  • extract-text-webpack-plugin用法
  • FineReport中如何实现自动滚屏效果
  • GitUp, 你不可错过的秀外慧中的git工具
  • Idea+maven+scala构建包并在spark on yarn 运行
  • JavaScript类型识别
  • Linux快速复制或删除大量小文件
  • mysql innodb 索引使用指南
  • React+TypeScript入门
  • SSH 免密登录
  • Synchronized 关键字使用、底层原理、JDK1.6 之后的底层优化以及 和ReenTrantLock 的对比...
  • vue 个人积累(使用工具,组件)
  • 第十八天-企业应用架构模式-基本模式
  • 工作中总结前端开发流程--vue项目
  • 计算机常识 - 收藏集 - 掘金
  • 开源地图数据可视化库——mapnik
  • 聊聊springcloud的EurekaClientAutoConfiguration
  • 聊一聊前端的监控
  • 爬虫模拟登陆 SegmentFault
  • 前端每日实战:61# 视频演示如何用纯 CSS 创作一只咖啡壶
  • 使用权重正则化较少模型过拟合
  • 它承受着该等级不该有的简单, leetcode 564 寻找最近的回文数
  • 阿里云移动端播放器高级功能介绍
  • ‌JavaScript 数据类型转换
  • # 20155222 2016-2017-2 《Java程序设计》第5周学习总结
  • # centos7下FFmpeg环境部署记录
  • # 消息中间件 RocketMQ 高级功能和源码分析(七)
  • #职场发展#其他
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (19)夹钳(用于送货)
  • (保姆级教程)Mysql中索引、触发器、存储过程、存储函数的概念、作用,以及如何使用索引、存储过程,代码操作演示
  • (附源码)spring boot网络空间安全实验教学示范中心网站 毕业设计 111454
  • (利用IDEA+Maven)定制属于自己的jar包
  • (七)Activiti-modeler中文支持
  • (十六)串口UART
  • (实战篇)如何缓存数据
  • (图文详解)小程序AppID申请以及在Hbuilderx中运行
  • (学习日记)2024.03.25:UCOSIII第二十二节:系统启动流程详解
  • (转)IOS中获取各种文件的目录路径的方法