


Code sharing for developing WeChat red envelope function using PHP
This article mainly introduces the implementation method of WeChat red envelopes in PHP WeChat public account development. It analyzes the implementation ideas, steps and specific operation skills of PHP to implement the red envelope sending function of WeChat public accounts in the form of examples. Friends in need can refer to it. I hope Can help everyone.
1. Requirements:
Fans click on their company’s order on the customer’s public platform, and then give the order a cashback of five yuan. Send it to the WeChat ID of the order.
2. Development ideas:
#1: First get the openid of following this fan. Openid is the WeChat ID of following a certain public account. , so that this person can be located as the operator of the order.
2: Send xml data to request WeChat server.
The code has two php files
1.oauth2.php
<?php $code=$_GET['code']; $state=$_GET['state']; $appid='XXXX'; $appsecret='XXXXXXXX';// if (empty($code)) $this->error('授权失败'); $token_url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code'; $token=json_decode(file_get_contents($token_url)); if (isset($token->errcode)) { echo '<h1 id="错误">错误1</h1>'.$token->errcode; echo '<br/><h2 id="错误信息">错误信息1:</h2>'.$token->errmsg; exit; } session_start(); $_SESSION['openid']= $token->openid; header('location:http://www.XXXXXXX.com/XXXXX/XXXXXX/XXXXXX/hongbao.php');//要跳转的文件路径 ?>
2.hongbao.php
<?php //XXXXX。。是需要开发者自己填写的内容,注意不要泄密 // 从session中获取到openid; $openid=$_SESSION["openid"]; if(empty($openid)) { header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=XXXXXXXX&redirect_uri=http://www.XXXXXXX.com/oauth2.php&respose_type=code&scope=snsapi_base&state=XXXX&connect_redirect=1#wechat_redirect'); } } // 关键的函数 public function weixin_red_packet(){ // 请求参数 // 随机字符串 $data['nonce_str']=$this->get_unique_value(); //商户号,输入你的商户号 $data['mch_id']="XXXXXXX"; //商户订单号,可以按要求自己组合28位的商户订单号 $data['mch_billno']=$data['mch_id'].date("ymd")."XXXXXX".rand(1000,9999); //公众帐号appid,输入自己的公众号appid $data['wxappid']="XXXXXXX"; //商户名称 $data['send_name']="XXXXX"; //用户openid,输入待发红包的用户openid session_start(); $data['re_openid']=$_SESSION["openid"]; //付款金额 $data['total_amount']="XXXX"; //红包发放总人数 $data['total_num']="XXXX"; //红包祝福语 $data['wishing']="XXXX"; //IP地址 $data['client_ip']=$_SERVER['LOCAL_ADDR']; //活动名称 $data['act_name']="XXXXX"; //备注 $data['remark']="XXXXX"; // 生成签名 //对数据数组进行处理 //API密钥,输入自己的K 微信商户号里面的K $appsecret="XXXXXXXXXXXXXX"; // $data=array_filter($data); ksort($data); $str=""; foreach($data as $k=>$v){ $str.=$k."=".$v."&"; } $str.="key=".$appsecret; $data['sign']=strtoupper(MD5($str)); /* 发红包操作过程: 1.将请求数据转换成xml 2.发送请求 3.将请求结果转换为数组 4.将请求信息和请求结果录入到数据库中 4.判断是否通信成功 5.判断是否转账成功 */ //发红包接口地址 $url="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; //将请求数据由数组转换成xml $xml=$this->arraytoxml($data); //进行请求操作 $res=$this->curl($xml,$url); //将请求结果由xml转换成数组 $arr=$this->xmltoarray($res); } // 生成32位唯一随机字符串 private function get_unique_value(){ $str=uniqid(mt_rand(),1); $str=sha1($str); return md5($str); } // 将数组转换成xml private function arraytoxml($arr){ $xml="<xml>"; foreach($arr as $k=>$v){ $xml.="<".$k.">".$v."</".$k.">"; } $xml.="</xml>"; return $xml; } // 将xml转换成数组 private function xmltoarray($xml){ //禁止引用外部xml实体 libxml_disable_entity_loader(true); $xmlstring=simplexml_load_string($xml,"SimpleXMLElement",LIBXML_NOCDATA); $arr=json_decode(json_encode($xmlstring),true); return $arr; } //进行curl操作 private function curl($param="",$url) { $postUrl = $url; $curlPost = $param; //初始化curl $ch = curl_init(); //抓取指定网页 curl_setopt($ch, CURLOPT_URL,$postUrl); //设置header curl_setopt($ch, CURLOPT_HEADER, 0); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //post提交方式 curl_setopt($ch, CURLOPT_POST, 1); // 增加 HTTP Header(头)里的字段 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); // 终止从服务端进行验证 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //证书放到网站根目录的cert文件夹底下 curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).DIRECTORY_SEPARATOR. 'cert'.DIRECTORY_SEPARATOR.'apiclient_cert.pem'); curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).DIRECTORY_SEPARATOR. 'cert'.DIRECTORY_SEPARATOR.'apiient_key.pem'); curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).DIRECTORY_SEPARATOR. 'cert'.DIRECTORY_SEPARATOR.'rootca.pem'); //运行curl $data = curl_exec($ch); //关闭curl curl_close($ch); return $data; } ?>
Related recommendations:
Sharing of development ideas for generating WeChat red envelopes with php
Detailed explanation of WeChat’s WeChat red envelope implementation
Summary of how to use WeChat red envelope interface
The above is the detailed content of Code sharing for developing WeChat red envelope function using PHP. For more information, please follow other related articles on the PHP Chinese website!

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
