当前位置:网站首页>Wechat applet withdrawal function
Wechat applet withdrawal function
2022-06-12 22:15:00 【Famine~】
1, Open wechat payment account , Opening The enterprise pays the change

2, Code up
/**
* Withdrawal function
*/
public function payOrder()
{
$openid = input('openid');// user openid
$userid = input('userid/d',0);// user uid
$amount = input('amount/s','');// Amount withdrawn
$User = Db::name('user')->field('id,integral')->where(['id' => $userid])->find();
if ($User['integral'] > 0 && !empty($User)) {
$trade_no = 'XJ1314520521' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);// Merchant order number
Db::startTrans();
try {
// Add payment information pay_trade
$data = [
'user_id' => $userid,
'class_id' => 3,
'order_no' => $trade_no,
'trade_no' => $trade_no,
'subject' => ' Withdrawal from Zhidou ',
'trade_channel'=>'wxpay',
'amount' => $amount,// Withdrawal points
'status'=>0,
'create_time' => time()
];
Db::name('pay_trade')->insert($data);
$card_grade = Db::name('pay_trade')->where(['order_no' => $data['order_no']])->update(['status' =>1]);// modify state - In the payment
$data['desc'] = ' Withdrawal from Zhidou ';
$data['appid'] = 'XXXXXXXXXXX';
$data['openid'] = 'XXXXXXXXXXXXX';
$result = $this->txFunc($data['openid'],$data['order_no'],$amount,$data['desc'],$data['appid']);
// die;
if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS' && $card_grade){
$partner_trade_no = Db::name('pay_order')->where(['partner_trade_no' => $result['partner_trade_no']])->count();
if ($partner_trade_no > 0) {
$info = [
'payment_no' => $result['payment_no'],
'payment_time' => $result['payment_time'],
'status' => 1
];
Db::name('pay_order')->where(['partner_trade_no' => $result['partner_trade_no']])->update($info);
Db::name('user')->where(['openid' => $openid])->update(['amount' => 0]);
}
$msg = [
'code' => 0,
'msg' => ' Withdrawal succeeded ',
'data' => 0
];
// Db::commit();
$code = $amount['user_name'] . ':' . $amount['amount'];
$res = $this->sendMobileCaptcha('18735393892', $code);
} else {
$msg = [
'code' => 1,
'msg' => ' Withdrawal failed ',
'data' => 1
];
}
} catch (\Exception $e) {
// Roll back the transaction
Db::rollback();
}
} else {
$msg = [
'code' => 1,
'msg' => ' Your balance is not enough for cash withdrawal ~',
'data' => 4
];
}
}
/**
* Enterprises pay ( The request to pay change to the wechat initiating enterprise )
* @param string $openid user openID
* @param string $trade_no Odd Numbers
* @param string $money amount of money ( Unit score )
* @param string $desc describe
* @param string $appid association appid
* @return string XML String of structure
**/
public function txFunc($openid,$trade_no,$money,$desc,$appid)
{
$data = array(
'mch_appid' => $appid,// association appid
'mchid' => 'XXXXXXXX',// Wechat payment merchant number
'nonce_str' => $this->getNonceStr(), // Random string
'partner_trade_no' => $trade_no, // Merchant order number , Need to be the only
'openid' => $openid,
'check_name' => 'NO_CHECK', //OPTION_CHECK Do not force verification of real names , FORCE_CHECK: mandatory NO_CHECK:
'amount' => $money * 100, // The payment amount is in minutes
'desc' => $desc,// Description information
'spbill_create_ip' => request()->ip(),
);
// Generate signature
$data['sign'] = $this->makeSign($data);
// structure XML data ( Data packets should be in the form of xml Format to send )
$xmldata = $this->arrToXml($data);
// request url
$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
// send out post request
$res = $this->curl_post_ssl($url,$xmldata);
return $res;
}
function share($url){
$appID='XXXXX';// Applet appID
$appSecret='XXXXXXXXXXXXX';// Applet appSecret
$jssdk = new JSSDK($appID, $appSecret);
$signPackage = $jssdk->GetSignPackage(urldecode($url));
if(!isset($signPackage)){
return $this->apiNullJson(101);
}
$data=[
'appId'=>$appID,
'timestamp'=>$signPackage["timestamp"],
'nonceStr'=>$signPackage["nonceStr"],
'signature'=>$signPackage["signature"]
];
$msg = [
'code' => 0,
'msg' => 'OK',
'data' => $data
];
return json($msg);
}
/**
* Random string
* @param int $length
* @return string
*/
function getNonceStr($length = 32)
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
/**
* Signature
* @param $data
* @return string
*/
function makeSign($data)
{
$key="XXXXXXXXXXXXXXX";// Merchant secret key Wechat payment platform -》 API Security -》 Set up APIv2 secret key
// Association sort
ksort($data);
// Dictionary sort
$str = http_build_query($data);
// Add merchant key
$str .= '&key=' . $key;
// Clean up the spaces
$str = urldecode($str);
$str = md5($str);
// Convert a capital
$result = strtoupper($str);
return $result;
}
/**
* Array rotation XML
* @param $data
* @return string
*/
function arrToXml($data)
{
$xml = "<xml>";
// Traversal combination
foreach ($data as $k=>$v){
$xml.='<'.$k.'>'.$v.'</'.$k.'>';
}
$xml .= '</xml>';
return $xml;
}
/**
* XML Turn array
* @param string
* return $data
* */
function xmlToArray($xml)
{
// Prohibit external references xml Entity
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
/**
* [curl_post_ssl send out curl_post data ]
* @param [type] $url [ Sending address ]
* @param [type] $xmldata [ Send file format ]
* @param [type] $second [ Set the maximum number of seconds to execute ]
* @param [type] $aHeader [ Set the head ]
* @return [type] [description]
*/
function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
$isdir = "../extend/Cert/";// Certificate location ; Absolute path
$ch = curl_init();// initialization curl
curl_setopt($ch, CURLOPT_TIMEOUT, $second);// Set the maximum number of seconds to execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// Require the result to be a string and output to the screen
curl_setopt($ch, CURLOPT_URL, $url);// Grab the specified page
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// Terminate authentication from the server
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');// Certificate type
curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');// Certificate location
curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY The encryption type of the private key specified in
curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');// Certificate location
curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
if (count($aHeader) >= 1) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);// Set the head
}
curl_setopt($ch, CURLOPT_POST, 1);//post submission
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);// All data use HTTP In the agreement "POST" Operation to send
$data = curl_exec($ch);// Execute a reply
if ($data) {
curl_close($ch);
return $this->xmlToArray($data);
} else {
$error = curl_errno($ch);
echo "call faild, errorCode:$error\n";
curl_close($ch);
return false;
}
}
/*
* Send SMS verification code
*/
function sendMobileCaptcha($mobile,$code = ''){
$content = " Hello! :".$code." RMB withdrawal succeeded ";
$dataMsg["pwd"] ='XXXXXX';
$dataMsg["username"]='XXXXX';
$dataMsg["mobile"] = $mobile;
$dataMsg["content"] = $content;
$statusCode = $this->http_post("http://api.uoleem.com.cn/sms/uoleemApi",$dataMsg);
$arr = explode(',',$statusCode);
return $arr;
}
/*
* send out POST request
*/
function http_post($url,$data,$param = array()){
$ch = curl_init();
if(!empty($param)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $param);
}
if (substr($url, 0, 8) == 'https://') {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);// Get the return data
curl_close($ch);
return $result;
}
边栏推荐
- The kotlin coroutine -- coroutine context and exception propagation
- Qt Quick 3D学习:鼠标拾取物体
- How to abstract a problem into a 0-1 knapsack problem in dynamic programming
- 多线程模型下的生产者消费者模式
- Pat grade A - 1167 Cartesian tree (30 points) (buildtree + level traversal)
- Interpretation of OCP function of oceanbase Community Edition
- Ansible playbook和变量(二)
- Build a highly available database
- SQL tuning guide notes 14:managing extended statistics
- 在同花顺开户证券安全吗,证券开户怎么开户流程
猜你喜欢

回文链表及链表相交问题(和心怡的人相交)你真的会了吗?

【图像去噪】基于三边滤波器实现图像去噪附matlab代码

Ansible summary (VI)

SQL tuning guide notes 16:managing historical optimizer statistics

PE installation win10 system

Yyds dry inventory insider news: Series high-frequency interview questions, worth a visit!

Qt Quick 3D学习:鼠标拾取物体

How to prevent phishing emails? S/mime certificate to help!

关于 安装Qt5.15.2启动QtCreator后“应用程序无法正常启动0xc0000022” 的解决方法

Ansible PlayBook et ansible roles (3)
随机推荐
A puzzle about + =
Preliminary use of jvisualvm
What is the race condition? How do you find and solve the competition?
大学期间零基础如何开展编程学习
June training (day 11) - matrix
2022-02-28 incluxdb high availability planning
JVM Basics - > how GC determines that an object can be recycled
PE安装win10系统
SQL tuning guide notes 11:histograms
SQL tuning guide notes 14:managing extended statistics
Qt Quick 3D学习:使用鼠标键盘控制节点位置和方向
leetcodeSQL:574. Elected
Ansible playbook and ansible roles (III)
Yyds dry goods inventory solution Huawei machine test: weighing weight
2021 rust survey results released: 9354 questionnaires collected
Prefix sum and difference
talent showing itself! Oceanbase was selected into the 2021 "sci tech innovation China" open source innovation list
SQL tuning guide notes 15:controlling the use of optimizer statistics
USB mechanical keyboard changed to Bluetooth Keyboard
3.5 setup and teardown of test classes