小程序获取用户的openid,在app.js保存下openid
//app.js
App({
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
var that = this;
wx.login({
success(res) {
console.log(res);
if (res.code) {
// 发起网络请求
wx.request({
url: 'https://api.test.top/login.php',
data: {
code: res.code
},
header: {
'content-type': "application/x-www-form-urlencoded"
},
success(api_result) {
console.log(api_result.data.data);
if (api_result.data.status == 1000) {
that.globalData.openid = api_result.data.data.openid;
console.log(123);
} else {
wx.showToast({
title: '获取openid失败',
icon: 'none'
})
}
// console.log( api_result );
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
globalData: {
userInfo: null,
openid:null
}
})
视图页面添加一个按钮,添加点击事件
<button bindtap="wechatTestPay">支付一分钱</button>
js页面
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
},
wechatTestPay:function( e ){
var that = this;
// console.log(app.globalData);
wx.request({
url: 'https://接口地址/wechatpay.php',
data: {
openid: app.globalData.openid
},
header: {
'content-type': "application/x-www-form-urlencoded"
},
success(api_result) {
console.log(api_result.data.data);
if (api_result.data.status == 1000) {
// that.globalData.openid = api_result.data.data.openid;
wx.requestPayment(
{
'timeStamp':api_result.data.data.timeStamp,
'nonceStr': api_result.data.data.nonceStr,
'package': api_result.data.data.package,
'signType': 'MD5',
'paySign': api_result.data.data.paySign,
'success': function (res) {
console.log('success');
console.log(res);
},
'fail': function (res) {
console.log('fail');
console.log(res);
},
'complete': function (res) {
console.log('complete');
console.log(res);
}
})
} else {
wx.showToast({
title: '统一下单失败',
icon: 'none'
})
}
// console.log( api_result );
}
})
}
})
调用服务段接口:
<?php
#微信统一下单接口
$url='https://api.mch.weixin.qq.com/pay/unifiedorder';
$param=[
#公众账号ID
'appid'=>'微信小程序id',
'mch_id'=>'商户id',
'nonce_str'=>uniqid(),
'sign_type'=>'MD5',
'body'=>'test',
'detail'=>'test',
'out_trade_no'=>date('Ymd').rand(10000,99999),
'total_fee'=>1,
'spbill_create_ip'=>$_SERVER['SERVER_ADDR'],
'notify_url'=>'https://你的域名/notify.php',
'trade_type'=>'JSAPI',
'openid' => $_GET['openid']
];
ksort($param);
$sign_str=urldecode(http_build_query($param));
$sign_str.='&key=商户的密钥';
$sign_str=md5($sign_str);
$param['sign']=strtoupper($sign_str);
//print_r($param);exit;
function CurlPost($url, $param = [], $is_post = 1, $timeout = 5 )
{
//初始化curl
$curl = curl_init();
// 设置请求的路径
curl_setopt($curl, CURLOPT_URL, $url);
if ($is_post == 1) {
//设置POST提交
curl_setopt($curl, CURLOPT_POST, 0);
}
//显示输出结果 1代表 把接口返回的结果当作一个字符串处理
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 设置请求超时时间
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($is_post == 1) {
//提交数据 -- 设置post提交的数据
if (is_array($param)) {
//http_build_query
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
} else {
curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
}
}
//执行请求
$data = $data_str = curl_exec($curl);
//处理错误
if ($error = curl_error($curl)) {
$log_data = array(
'url' => $url,
'param' => $param,
'error' => '<span style="color:red;font-weight: bold">' . $error . '</span>',
);
var_dump($log_data);
exit;
}
# 关闭CURL
curl_close($curl);
//json数据转换为数组
$data = json_decode($data, true);
if (!is_array($data)) {
$data = $data_str;
}
#调用玩接口之后写一个日志
$log = [
'url' => $url,
'param' => $param,
'response' => $data_str
];
file_put_contents(__DIR__ . '/wechat.log', print_r($log, true), 8);
return $data;
}
function arrzxml($arr){
$xml='<xml version="1.0" encoding="UTF-8">';
foreach($arr as $key=>$value){
if(is_numeric($value)){
$xml.="<".$key.">".$value."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$value."]]></".$key.">";
}
}
$xml.='</xml>';
// var_dump($xml);exit;
return $xml;
}
$xml=arrzxml($param);
$result=CurlPost($url,arrzxml($param));
//echo '<pre/>';
$api_arr = json_decode( json_encode(simplexml_load_string( $result , 'SimpleXMLElement', LIBXML_NOCDATA) ), true );
if( $api_arr['return_code'] == 'SUCCESS' ){
# 统一下单接口成功, 再次加密
$prepay_id = $api_arr['prepay_id'];
$arr = [
'appId' => 'appid',
'timeStamp' =>"".time(),
'nonceStr' => uniqid(),
'package' => "prepay_id=$prepay_id",
'signType' => 'MD5'
];
ksort( $arr );
$sign_str=urldecode( http_build_query($arr) );
$sign_str.='&key=商户密钥';
$sign_str=md5($sign_str);
$arr['paySign'] = $sign_str;
$api_return = [
'status' => 1000,
'data' => $arr,
'success' => 'ok'
];
}else{
$api_return = [
'status' => 1,
'data' => [],
'msg' => '统一下单失败'
];
}
echo json_encode( $api_return );
exit;